Previous Next

C if...else Statements

The if-else statement in C is employed to make decisions based on conditions. It enables you to run a block of code if a given condition is true, and another block of code if the condition is false.

The syntax of the C if-else statement is:

if (condition) {
  //code to be executed if the condition is true
} else {
  //code to run if the condition is untrue
}

Example:

#include <stdio.h>

int main ()
{
    int num = 15;
              
    if (num > 0) {
      printf ("%d is a positive number.\n", num);
    } else {
      printf ("%d is a negative number.\n", num);
    }
    return 0;
}

Output:

15 is a positive number.

if-else Ladder

If we wish to verify several conditions, then an if-else ladder may be employed.
Syntax:

if (condition) {
  //code
}
else if (condition) {
  //code
}
else if (condition) {
  //code
}
else {
  //code
}

Example:

#include <stdio.h>

int main ()
{
    int num = -6;

    if (num > 0) {
      printf ("%d is a positive number.\n", num);
    } else if (num < 0) {
      printf ("%d is a negative number.\n", num);
    } else { 
      printf("%d is a Zero.\n", num);
    }
    return 0;
}

Output:

-6 is a negative number.
Previous Next