If Else Statement In C Programming





The if-else statement is a control structure in programming that allows you to perform different actions based on a condition. It evaluates a condition and executes a block of code if the condition is true. If the condition is false, it executes a different block of code.


Syntax:

The syntax for the if-else statement in C programming is as follows:

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

The condition is an expression that evaluates to either true or false. If the condition is true, the code within the if block is executed. Otherwise, the code within the else block is executed.


Example:

In this example, we have a simple c-language code to demonstrate the usage of the if-else statement.

#include <stdio.h>
int main() {
   int temperature;
    
    printf("Enter the Temperature :\t");
    scanf("%d",&temperature);

    if (temperature > 30) {
        printf("It's a hot day!");
    } else {
        printf("It's a moderate day.");
    }

    return 0;
}
output:
Enter the Temperature : 35
It's a hot day!
Enter the Temperature : 25
It's a moderate day.

In the above example, the variable temperature is assigned a value of 25. The if-else statement checks if the temperature is greater than 30. Since 25 is not greater than 30, the condition evaluates to false, and the code within the else block is executed. Therefore, the output will be "It's a moderate day."

Additional Notes:

  • The if-else statement can be nested within each other to handle multiple conditions.
  • You can also use multiple else if statements to handle different cases.
  • The else block is optional. If you don't provide an else block, the code will simply continue executing after the if block.