if-else statement
Table of Content
Decision control Statement
If-else statement
C uses the keyword if and else to implement the decision control
statement. The general form of this statement look like this:
Syntax:
if(expression)
statement1;
else
statement2;
The expression inside the parenthesis is evaluated and if it is
true(Non-zero value), then statement1 is execute and if the expression is
false(Zero) then the statement2 is executed. This expression often called
the if condition. The below following flow chart shows the if-else
statement.
if(expression) { statement ................. } else { statement ............. } |
if(expression) statement1 else { statement .............. } |
if(expression) { statement ................. } else statement2 |
Enter the number:26
26 is an Even.
If statement
In the decision control statement else part is optional, i.e. an if-else
statement can be written with or without the else clause. In case of
missing else the syntax would be-
Syntax:
if(expression) statement1 |
if(expression) { statement ............. } |
If the expression is true, then statement1 is executed and if is false
then control transfer to the next statement.
The below flow chart shows the working of an if statement:
Enter the number:-9
Number enter is Negative.
Welcome to Education ki duniya!
Enter the number:5
Welcome to Education ki duniya!
Nested if-else
We have another if-else statement in the if part or the else part. This
is called nested if-else statement
Syntax:
If(expression1)
{
If(expression2)
Statement1;
else
Statement2;
}
Else
{
if(expression3)
Statement3;
else
statement4;
}
The following program to illustrate nesting of if-else statement.
Input the numbers a,b and c:
365
564
695
Largest number is 695
Dangling else problem
Since the else part in an if-else statement is optional, it is possible that in the nested if-else statements an else part is omitted. In this case confusion may arise in associating else part with the appropriate if part.
now take an example:
if(a>c)
printf("a is greater");
else
printf("c is greater");
if(a>c)
printf("a is greater");
else
printf("c is greater");
NOTE: We get this problem there is an else part missing in the nested if-else structure. The if(a>c) is not have any else part. We should tell the compiler about this by putting braces at proper manner. see in below :
{
if(a>c)
printf("a is greater");
}
else
{
printf(" a is less than b");
}
else-if Ladder
Syntax;
statementA;
else if(expression2
statementB;
else if(expression3)
statementC;
else
Marks in Hindi:85
Marks in Physics:69
Marks in Maths:65
Marks in Chemistry:78
Total percentage marks:71.00%
B Grade
if we don't use if else ladder ,then equivalent code for this problem :
printf("A+ Grade");
if (per < 90 && per >= 80)
printf("A Grade");
if (per < 80 && per >= 70)
printf("B Grade");
if (per < 70 && per > 60)
printf("C Grade");
if (per < 60 && per >= 50)
printf("D Grade");
if (per < 50 && per >= 40)
printf("E Grade");
Comments
Post a Comment