C if-else statement

In C programming, an if-else statement is used to make decisions based on conditions. It allows the program to execute a block of code if a specified condition is true, or a different block of code if the condition is false.

Syntax:


if (condition) {
    // Block of code executed if the condition is true
} else {
    // Block of code executed if the condition is false
}

Example:


#include <stdio.h>

int main() {
    int age = 15;
    // Checking if the person is eligible to vote
    if (age >= 18)
     {
        printf("You are eligible to vote.");
     } else {
       printf("You are not eligible to vote.");
     }
    return 0;
}

Output:

You are not eligible to vote.

Example: If number is not positive


#include <stdio.h>

int main() {
   int number = -20;
        // Checking if the number is positive
        if (number > 0)
        {
            printf("Number is positive");
        } else {
           printf("Number is not positive");
         }
    return 0;
}

Explanation:

  1. Condition: number >= 0 is the condition being checked.
  2. Since number is less than 0, then condition evaluates to false.

Output:

Number is not positive