Previous | Home | Next |
Statement is a part of our program that can be executed. In other words every statement in our program alone or in combination specifies an action to performed by our program.
Conditional Statement
Its also called a selection statement, depends on the condition that decide the flow of statements based on evaluation of the results of condition. if - else and switch statements are conditional statements.
# if statement
In C programming we want the program to be executed sequentially. we want a set of instruction to be executed at one time and an entirely set of instruction to be executed in another situation. in this type of situation will have to use the decision control structure
General form of if statement
if (condition) //if this condition is true) { expresion1; //execute the statement }
/* Demonstration of if statement */ main( ) { int num ; printf ( "Enter a number less than 10 " ) ; scanf ( "%d", &num ) ; if ( num <= 10 ) printf ( "What an obedient servant you are !" ) ; }
Explanation: When we execute the above program then if you type the number less than 10 then you will get a message on screen through printf(). If you type the number which is greater than 10 then program will do nothing.
# if-else condition
The if statement by itself will execute the single statement or a group of statement when the expression follow ‘if’ evaluates true and another expression with in single group of statement follow’if’ evaluates falls then we generally use th ‘if-else’ condition.
To understand the ‘if-else’ condition we can take an example which is given below:/* Calculation of gross salary */ main( ) { float bs, gs, da, hra ; printf ( "Enter basic salary " ) ; scanf ( "%f", &bs ) ; if ( bs < 1500 ) //when condition is true { hra = bs * 10 / 100 ; da = bs * 90 / 100 ; } else //when condition is not true { hra = 500 ; da = bs * 98 / 100 ; } gs = bs + hra + da ; printf ( "gross salary = Rs. %f", gs ) ; }
# else-if condition
else if condition is nothing but this this a way to arrange the else with the if that follows it.
if (i == 2) // [1] if i is equal to 2 { printf ( "With you…" ); } else if(i==3) // [2] if i is equal to 3 { printf("…All the time"); } else // when [1] and [2] conditions are false { printf("…false condition"); }
# Nested if-else condition
It is perfectly all right if we write an entire if-else construct within either the body of the if statement or the body of an else statement. This is called ‘nesting’of ifs. This is shown in the following program.
Example/* A quick demo of nested if-else */ main( ) { int i ; printf ( "Enter either 1 or 2 " ) ; scanf ( "%d", &i ) ; if ( i == 1 ) printf ( "You would go to heaven !" ) ; else { if ( i == 2 ) printf ( "Hell was created with you in mind" ) ; else printf ( "How about mother earth !" ) ; } }
Previous | Home | Next |