C if... Else

The if...else is a type of conditional statement that will execute a block of code when the condition in the if statement is satisfied.


If:

Use the if statement to specify a block of C code to be executed if a condition is true.



    int main()
    {
    int x = 20;
    int y = 18;
    if (x > y)
    {
    printf("x is greater than y");
    }

    return 0;
    }


Output

x is greater than y


The > operator is used in the example above to determine whether two variables, x and y, are greater than one another. We print "x is greater than y" to the screen since x is 20 and y is 18, and we know that 20 is greater than 18 because of this.


Else:

Use the else statement to specify a block of code to be executed if the condition is false.



  #include 
  int main() {
  int time = 20;
  if (time < 18) {
  printf("Good day.");
  } else {
  printf("Good evening.");
  }
  return 0;
  }


Output

Good evening


Because time (20) in the previous example is larger than 18, the condition is false. As a result, we continue on to the next condition and print "Good evening" on the screen. "Good day" would be printed by the programme if the time was less than 18.


If .. Else:

Use the else if statement to specify a new condition if the first condition is false.



  #include 
  int main() {
  int time = 22;
  if (time < 10) {
  printf("Good morning.");
  } else if (time < 20) {
  printf("Good day.");
  } else {
  printf("Good evening.");
  }
  return 0;
  }


Output:

Good evening

The first condition is incorrect in the example above since time (22) is more than 10, which explains why. Since both the first and second conditions in the otherwise if statement are false, we continue on to the else condition and print the words "Good evening" on the screen.


When the time was 14, though, our programme printed "Good day."







© Copyright 2022 Advanced PLC. All rights reserved.