C Programming Tutorial - ITDeveloper

ITDeveloper : C Programming

C Programming

Step by Step Tutorials


Share with a Friend

if...else Statement In C

 

An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.

Syntax

The syntax of an if...else statement in C programming language is −

if(boolean_expression) {

   /* statement(s) will execute if the boolean expression is true */

} else {

   /* statement(s) will execute if the boolean expression is false */

}

If the Boolean expression evaluates to true, then the if block will be executed, otherwise, the else block will be executed.

C programming language assumes any non-zero and non-null values as true, and if it is either zero or null, then it is assumed as false value.

Flow Diagram

C if...else statement

Example 1:

 

// Check whether an integer is odd or even

#include <stdio.h>
int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);

// True if the remainder is 0
if (num%2 == 0) {
printf("%d is an even integer.",num);
}
else {
printf("%d is an odd integer.",num);
}

return 0;
}

OUTPUT 1:

Enter an integer: 7
7 is an odd integer.

OUTPUT 2:

Enter an integer: 8
8 is an even integer.

Example 2:

// Program to relate two integers using =, > or < symbol

#include <stdio.h>
int main() {
int num1, num2;
printf("Enter two integers: ");
scanf("%d %d", &num1, &num2);

//checks if the two integers are equal.
if(num1 == num2) {
printf("Result: %d = %d",num1,num2);
}

//checks if num1 is greater than num2.
else if (num1 > num2) {
printf("Result: %d > %d", num1, num2);
}

//checks if both test expressions are false
else {
printf("Result: %d < %d",num1, num2);
}

return 0;
}

OUTPUT 1:

Enter two integers: 12 18
Result: 12 < 18

OUTPUT 2:

Enter two integers: 18 12
Result: 18 > 12

OUTPUT 3:

Enter two integers: 12 12
Result: 12 = 12