Friday, December 11, 2009

4.1 THE if-else STATEMENT

Till now we have written programs in which instructions were executed in order of their appearance.There will be many situations where such execution sequence mat not be
sufficient .For example we want to find the bigger out of two numbers.This problem requires comparision of the two numbers and based on comparision result,the bigger number will be found.This can be implemented using the if instruction.The instruction can be written in
simple form as

if(expr) statement

The expression must be placed in paenthesis,as shown.In this form, the statement will be executed only if the expression is true.if the expression is false then the statement will be ignored.

Many times the program requires to take a specific action if a particular condition is true and another action if the condition is not true(i.e. false).Such a situation can be effectively implemented using the if else instruction.The general form of the if else instruction is

if(expr) statement1 else statement2

Let us try to use to use the if-else instruction to find the bigger out of two numbers.

#include

main()

{

int first,second;
scanf("%d %d",&first,&second);
if(first>second)
printf("First number is bigger\n");
else
printf("Second number is bigger\n");

}

In the above program,if the input value of the first number is higher than the second number then the output shown on the screen will be

First number is bigger

otherwise the output shown on the screen will be

Second number is bigger

No comments:

Post a Comment