Basic if-else statements in C language

Conditional branching is accomplished with the if-else expression. If a certain condition is true, it enables the program to run a specific block of code, if the condition is false, it enables the program to run a different piece of code.

Basic syntax of if-else statement:

if(condition) {
  // code to execute if condition is true
} else {
  // code to execute if condition is false
}

Here’s an example of the if-else statement:

#include <stdio.h>

int main() {
  int x = 10;
  
  if(x > 5) {
    printf("x is greater than 5\n");
  } else {
    printf("x is less than or equal to 5\n");
  }
  
  return 0;
}

Output:

x is greater than 5

In this example, the program checks whether x is greater than 5. If it is, it prints “x is greater than 5”. Otherwise, it prints “x is less than or equal to 5”.

It’s important to note that the condition in the if statement must be enclosed in parentheses. Also, the curly braces are used to enclose the blocks of code that will be executed based on the condition.

Additionally, the else clause is optional. If it’s not included, the program will simply skip the block of code inside the if statement if the condition is false.

The if-else statement can also be nested to create more complex conditional structures.

Another example of basic if-else statement

#include <stdio.h>

int main()
{
   int num;
   printf("Enter a number: ");
   scanf("%d", &num);

   if (num % 2 == 0)
   {
      printf("%d is even.\n", num);
   }
   else
   {
      printf("%d is odd.\n", num);
   }

   return 0;
}

Output:

Enter a number: 8
8 is even.

Enter a number: 7
7 is odd.