If Else Statement in C Programming Language

IF ELSE statement in c programming; In this tutorial, i am going to show you if else statement in C programming with examples.

C if else Statement

The c programming if else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed.

Syntax of C if else Statement

The syntax of the if else statement in C programming; as shown below:

if (test expression) {
    // run code if test expression is true
}
else {
    // run code if test expression is false
}

Example 1 – C program to Check Number Is Even OR Odd using IF Else

See the following c program for if statement; as shown below:

// Check whether an integer is odd or even
#include <stdio.h>
int main() {
    int number;
    printf("Enter an integer: ");
    scanf("%d", &number);
    // True if the remainder is 0
    if  (number%2 == 0) {
        printf("%d is an even integer.",number);
    }
    else {
        printf("%d is an odd integer.",number);
    }
    return 0;
}

Output of the above c program

Enter an integer: 10
10 is an even integer.

Explaination of above c program

  • Take input from user in program.
  • Then the test expression number%2==0 is evaluated to false.
  • Hence, the statement inside the body of else is executed.

Example 2 – C Program to Check Whether a Number is Divisible by 5 using if else statement

See the second c program for if statement; as shown below:

// C Program To Check Whether a Number is Divisible by 5 and 11
#include <stdio.h>
int main(){
    int num;
    
    // Asking for Input
    printf("Enter an number: ");
    scanf("%d", &num);
    
    if ((num % 5 == 0)) {
        printf("%d is divisible by 5.", num);
    }
    else{
        printf("%d is not divisible by 5 ", num);
    }
    return 0;
}

Output of the above c program

Enter an number: 10
10 is divisible by 5.

Explanation of above c program

  • Take input number from user in program.
  • The condition (num % 5 == 0) specified in the “if” returns true, then body of if is executed.
  • Otherwise, body of else is executed.

Be First to Comment

Leave a Reply

Your email address will not be published.