IF STATEMENT
The if statement is a powerful decision making statement and is used to control the flow of execution of statements. It is basically a two way decision statement and is used in conjunction with an expression. It takes the following form.
If (Test expression)
It allows the computer to evaluate the expression first and then depending on whether the value of the expression is true or false , it transfers the control to a particular statement. This point of program has two parts to follow. One for the true condition and the other for the false condition.
The if statement may be implemented in different forms depending on the complexity of conditions to be tested.
1. Simple if statement
2. if …… else statement
3. nested if …… else statement
4. else if ladder
SIMPLE IF STATEMENT
The general form of simple if statement is
If (Test expression)
{
statement - block ;
}
statement – x;
The statement block may be single statement or a group of statements. If the test expression is true , the statement – block will be executed. Otherwise the statement block will be skipped and the execution will jump to the statement – x. Remember when the condition is true , both the statement block and statement – x are executed in sequence.
Consider the following segment of a program that is written for processing of marks obtained in an entrance examination.
. . . .
. . . .
if ( category == sports)
{
marks = marks + bonus_marks;
}
printf(“%d” , marks);
. . . .
. . . .
The program tests the type of category of the student. If the student belongs to the sports category , then additional bonus marks are added to his marks before they are printed. For others bonus marks are not added.
EXAMPLE : write a program to take four values from terminal a,b,c,d and evaluates the ratio
of (a+b) to (c-d) and prints the result if (c-d) not equal to zero.
#include<stdio.h>
int main()
{
int a,b,c,d;
float ratio;
printf(“Enter four integer Values\n”);
scanf(“%d%d%d%d”,&a,&b,&c,&d);
if(c-d != 0)
{
ratio = (float) (a+b) / (float) (c-d);
printf(“%.2f”,ratio);
}
return 0;
}
if values 12 , 23 , 34 , 45 are given for a,b,c,d the then the ratio of (a+b) to (c-d) is printed as –3.1818. When 12 , 23 , 34 , 34 are given , program neither produces result nor any message. Because value of (c-d) equal to zero and therefore the statements contained in statement – block are skipped. Since no other statements follows the statement – block , program stops without producing any output.
Note the use of float conversion in the statement , evaluating the ratio. This is necessary to avoid truncation due to division.
THE IF …. ELSE STATEMENT
The if …. Else statement is an extension of the simple if statement. The general form is
If ( Test expression)
{
True block statements
}
else
{
False block statements
}
Statement – x;
If the test expression is true , then true block statements immediately following the if statement are executed. Otherwise false block statements are executed. In either case either true block or false block will be executed , not both. In both cases control is transferred subsequently to statement – x.
Let us consider an example of counting the number of boys and girls in a class. We use code 1 for boys and 2 for girls. The program statement to do this may be written as follows.
. . . .
. . . .
if (code = = 1)
{
boy = boy + 1;
}
if (code = = 2)
{
girl = girl + 1;
}
. . . .
. . . .
The first test determines whether or not the student is a boy. If yes , the number of boy is increased by one and the program continues to the second test. The second test again determines whether the student is a girl. This is unnecessary. Once a student is identified as a boy , there is no need to test again for a girl. A student can be either a boy or a girl. Not both. The above program segment can be modified using else clause as follows.
. . . .
. . . .
if ( code = = 1)
{
boy = boy + 1;
}
else
{
girl = girl + 1;
}
. . . .
. . . .
Here , if the code is equal to one , the statement boy = boy + 1 is executed and the control is transferred to the statement – x , after skipping the else part. If the code is not equal to 1 , the statement girl = girl + 1 is executed before the control reaches the statement – x.
Consider the example program of simple if statement. When the value of (c-d) is zero , the ratio is not calculated and the program stops without any message. In such cases , we may not know whether the program stopped due to a zero value or some other error. This program can be improved by adding the else clause as follows.
#include<stdio.h>
int main()
{
int a,b,c,d;
float ratio;
printf(“Enter four integer Values\n”);
scanf(“%d%d%d%d”,&a,&b,&c,&d);
if(c-d != 0)
{
ratio = (float) (a+b) / (float) (c-d);
printf(“%.2f”,ratio);
}
else
{
printf(“C-D is Zero”);
}
return 0;
}
NESTING OF IF … ELSE STATEMENTS
When a series of decisions are involved , we may have to use more than one if … Else statement in nested form as follows.
If ( Test Condition 1)
{
if ( test condition 2)
{
statement 1;
}
else
{
statement 2;
}
}
else
{
statement 3;
}
statement – x;
If the statement 1 is false , statement 3 will be executed. Otherwise it continues to perform second test. If the condition 2 is true , the statement 1 will be executed. Otherwise statement 2 will be evaluated and then the control is transferred to the statement – x.
A commercial bank has introduced an incentive policy of giving bonus to all its deposit holders. The policy is as follows. A bonus of 2% of the balance held on 31st December is given to everyone irrespective of their balances , and 5% is given to female account holders , if their balance is more than Rs.5000. This logic can be coded as follows.
. . .
. . . .
if(sex = = ‘F’)
{
if(balance > 5000)
{
bonus = 0.05 * balance;
}
else
{
bonus = 0.02 * balance;
}
}
else
{
bonus = 0.02 * balnce;
}
balance = balance + bonus;
. . . .
. . . .
EXAMPLE :
#include<stdio.h>
main()
{
float a,b,c;
printf(“Enter Three values”);
scanf(“%F%F%F”,&a,&b,&c);
printf(“Largest Value is”);
if(a>b)
{
if(a>c)
{
printf(“%f”,a);
}
else
{
printf(“%f”,c);
}
}
else
{
if(c>b)
{
printf(“%f”,c);
}
else
{
printf(“%f”,b);
}
}
}
THE ELSE IF LADDER
There is another way of putting ifs together when multi path decisions are involved. A multi path decision is a chain of ifs in which the statement associated with each else is an if. It takes the following general form.
If(condition)
{
statement – 1;
}
else if(condition2)
{
statement – 2;
}
elseif(condition3)
{
statement – 3;
}
. . . .
elseif(condition n)
{
statement – n;
}
else
{
default statement;
}
statement – x;
The conditions are evaluated from the top , downwards. As soon as a true condition is found , the statement associated with it is executed and the control is transferred to statement – x(skipping the rest of the ladder). When all the n conditions become false , then the final else containing default statement will be executed.
Let us consider an example of grading the student in an academic institution. The grading is done according to the following rules.
Avg Marks Grade
80 to 100 Honours
60 to 79 First division
50 to 59 Second Division
40 to 49 Third Division
0 to 39 Fail
The grading can be done using the else if ladder as follows.
If(marks > 79)
{
grade = “Honours”;
}
elseif(marks > 59)
{
grade = “First”;
}
elseif(marks > 49)
{
grade = “Second”;
}
else if(marks > 39)
{
grade = “Third”;
}
else
{
grade = “Fail”;
}
printf(“%s\n”,grade);
THE SWITCH STATEMENT
We have seen that when one of the many alternatives is to be selected , we can design a program using if statements to control the selection. However , the complexity of such a program increases dramatically , when the number of alternatives increases. The program becomes difficult to read and follow. Fortunately , C has a built in multi way decision statement known as switch. The switch statement tests the value of a given variable against a list of case values and when a match is found , a block of statements associated with that case is executed. The general form of the switch statement is as shown below.
Switch (expression)
{
case value 1 :
block – 1
break;
case value 2 :
block – 2
break;
. . . .
. . . .
default :
default block
break;
}
statement – x ;
The expression is an integer expression or characters. Value 1 , Value 2 , …. Are constants or constant expressions and are known as case labels. Each of these values should be unique within a switch statement. Block – 1 , block – 2 , … are statement lists and may contain zero or more statements. There is no need to put braces around these blocks. Note that case labels end with a colon (:).
When the switch is executed , the value of the expression is successfully compared against the values Value – 1 , Value – 2 , … If a case is found , whose value matches with the value of the expression , then the block of statements that follows the case are executed.
The break statement at the end of each block signals the end of a particular case and causes an exit from the switch statement, transferring the control to the statement – x following the switch.
The default is an optional case. when present , it will be executed if the value of the expression does not match with any of the case values. If not present , no action takes place if all matches fail and the control goes to the statement – x.
EXAMPLE : switch statement can be used to grade the students.
#include<stdio.h>
main()
{
int a , b , c , d , e , tot , index , avg ;
printf(“Enter Marks In Five Subjects\n”);
scanf(“%d %d %d % d %d”, &a , &b , &c , &d , &e);
tot = a + b + c + d + e ;
avg = tot / 5 ;
index = avg / 10 ;
switch(index)
{
case 10 :
case 9 :
case 8 :
grade = “Honors” ;
break ;
case 7 :
case 6 :
grade = “First” ;
break ;
case 5 :
grade = “Second” ;
break ;
case 4 :
case 3 :
grade = “Third” ;
break ;
default :
grade = “Fail” ;
break ;
}
printf(“%s\n”, grade) ;
. . . .
. . . .
Note that we have used a conversion statement
Index = avg / 10 ;
Where index is defined as an integer. The variable index takes the following integer values.
Marks Index
100 10
90 – 99 9
80 – 89 8
70 – 79 7
60 – 69 6
. . . .
. . . .
0 – 9 0
This segment of the program illustrates two important features. First , it uses empty cases. The first three cases execute the same statements.
Grade = “Honors” ;
Break ;
Same is the case with case 7 and case 6. Second , default condition is used for all other cases where marks is lass than 30.
Q) Himanshu wants to write a program to print the larger of the two inputted number. He writes the following code:
int number1, number 2
input number1, number 2
if (??) // Statement 1
print number1
else
print number2
end if
Fill in the ?? in statement 1.
Op 1: number1>number2
Op 2: number2>number1
Op 3: number2 equals number1
Op 4: number1 <= number2
Correct Op : 1
Q) Shalini wants to program to print the largest number out of three inputted numbers. She writes the following program:
int number1, number 2, number3, temp;
input number1, number2, number3;
if (number1>number2)
temp = number1
else
temp = number2
end if
if (??) // Statement 1
temp = number3
end if
print temp
Fill in the ?? in Statement 1
Op 1: number3 > number2
Op 2: number3 > temp
Op 3: number3 < temp
Op 4: number3 > number1
Correct Op : 2
Q) Rohit writes the following program which inputs a number and prints "Double digit" if the number is composed of two digits and "Not a double digit" if it is not.
int number;
if (number>10 AND number < 100)
print "Double digit"
else
print "Not a double digit"
end if
Rohit tries the following inputs: 5 and 66. The program works fine. He asks his brother Ravi to try the program. When Ravi enters a number, the program doesn't work correctly. What did Ravi enter? Op 1: 8
Op 2: 100
Op 3: 99
Op 4: 10
Correct Op : 4
Q) Rohan writes the following program which inputs a number and prints "Triple digit" if the number is composed of three digits and "Not triple digit" if it is not.
int number;
if (number>99)
print "Triple digit"
else
print "Not triple digit"
end if
Op 1: 99
Op 2: 100
Op 3: 0
Op 4: 1000
Correct Op : 4
Q) A company offers commission for selling it products to its salesperson. The commission rate is Rs. 5 per product. However if the salesperson sells more than 200 items, he gets a commission of Rs. 10 on all items he sold after the first 200. Kanu writes a program to calculate the commission for the salesperson:
integer numberProducts, commission
input numberProducts
if ( numberProducts > 200 )
-- MISSING STATEMENT --
else
commission = numberProducts * 5
end if
print commission
Fill in the missing statement.
Op 1: commission = (numberProducts - 200) * 10
Op 2: commission = 200 * 5 + (numberProducts - 200) * 10
Op 3: commission = numberProducts * 10
Op 4: None of these
Correct Op : 2
Q) Consider the following code:
if (condition 1) {
if (condition 2)
{ // Statement A }
else
if (condition 3)
{ // Statement B }
else
{ // Statement C }
else
if (condition 4)
{ // Statement D }
else
{ // Statement E}
}
Which of the following conditions will allow execution of statement C?
Op 1: condition1 AND condition3
Op 2: condition1 AND condition4 AND !condition2
Op 3: NOT(condition2) AND NOT(condition3)
Op 4: condition1 AND NOT(condition2) AND NOT(condition3)
Correct Op : 4
Q) Consider the following code:
if (condition 1) {
if (condition 2)
{ // Statement A }
else
if (condition 3)
{ // Statement B}
else
{// Statement C }
else
if (condition 4)
{// Statement D}
else
{// Statement E}
}
Which of the following conditions will allow execution of statement E?
Op 1: condition1 AND condition3
Op 2: NOT(condition1) AND condition2 AND NOT(condition4)
Op 3: NOT(condition2) AND NOT(condition3)
Op 4: condition1 AND condition4 AND NOT(condition2) AND NOT(condition3)
Correct Op : 2
Q) Consider the following code:
if (condition 1) {
if (condition 2)
{ // Statement A }
else
if (condition 3)
{ // Statement B}
else
{// Statement C }
else
if (condition 4)
{// Statement D}
else
{// Statement E}
}
Which of the following condition will allow execution of statement A?
Op 1: NOT(condition2) AND NOT(condition3)
Op 2: condition1 AND condition4 AND NOT(condition2) AND NOT(condition3)
Op 3: condition1 AND condition2 AND condition4
Op 4: NOT(condition1) AND condition2 AND NOT(condition4)
Correct Op : 3