If Else Control Statements In C:
Sometimes we want a set of instructions to be executed if a certain condition is satisfied and an entirely different set of instructions to be executed if the condition does not fulfill. This kind of situation is dealt with in C language using decision control instruction. In today’s tutorial, we will discuss if-else statements in C programming.
Like other programming languages, C also uses the if keyword to implement decision control instruction. The condition for if the statement is always enclosed within a pair of parentheses. If the condition is true, then the set of statements will execute. If the condition is not true then the statement will not execute, instead the program skips that part.
We express a condition for if statements using relational operators. The relational operators allow us to compare two values to see whether they are equal, unequal, greater than, or less than.
Conditions | Meaning |
a == b | a is equal to b |
a != b | a is not equal to b |
a < b | a is less than b |
a> b | a is greater than b |
a <= b | a is less than or equal to b |
a >= b | a is greater than or equal to b |
The if-else Statement:
The statement written in if block will execute when the expression following it evaluates to true. But when the if is written with else block, then when the condition written in if block turns to be false, then the set of statements in the else block will execute.
Following is the syntax of if-else statements:
if ( condition ){
statements;}
else {
statements;}
Example:
Here is a program, which demonstrates the use of the if-else statement.
#include <stdio.h>
int main( ) {
int num ;
printf ( "Enter a number less than 10 " );
scanf ( "%d", &num );
if ( num <= 10 ){
printf ( "Number is less than 10");}
else{
printf("Number is greater than 10");
}
return 0;
}
On execution of this program, if you type a number less than or equal to 10, the program will show a message on the screen through printf( ).
Nested If-Else Statements:-
We can write an entire if-else statement within either the body of the if statement or the body of an else statement. This is called ‘nesting’ of ifs. The Example of nested if-else statements is given below.
#include <stdio.h>
int main( )
{
int a;
printf ( "Enter either 0 or 1 " ) ;
scanf ( "%d", &a ) ;
if ( a == 1 ){
printf ( "Number 1 is entered!" ) ; }
else {
if ( a == 0 ){
printf ( "Number 0 is entered" ) ;}
else {
printf ( "Wrong Input" ) ; }
}
return 0;
}
0 Comments