If Statement, Types of If Statement Intro to Programming
MUHAMMAD HAMMAD WASEEM 1
Decision Control Structures
The statements of a computer program are executed one after the other in the order in which
they are written. This is known as sequential execution of the program. Many a times, we want a set of
instructions to be executed in one situation, and an entirely different set of instructions to be executed
in another situation. This kind of situation is dealt in C programs using a decision control instruction. A
decision control instruction can be implemented in C using:
 The if statement
 The if-else statement
 The conditional operators
The if Statement
Like most languages, C uses the keyword if to implement the decision control instruction. The
general form of if statement looks like this:
if ( this condition is true )
execute this statement ;
The keyword if tells the compiler that what follows is a decision control instruction. The condition
following the keyword if is always enclosed within a pair of parentheses. If the condition, whatever it is,
is true, then the statement is executed. If the condition is not true then the statement is not executed;
instead the program skips past it.
But how do we express the condition itself in C? And how do we evaluate its truth or falsity? As
a general rule, we express a condition using C’s ‘relational’ operators. The relational operators allow us
to compare two values to see whether they are equal to each other, unequal, or whether one is greater
than the other. Here’s how they look and how they are evaluated in C.
Expression Is true if
x == y x is equal to y
x != y x is not equal to y
x < y x is less than y
x > y x is greater than y
x <= y x is less than or equal to y
x >= y x is greater than or equal to y
The relational operators should be familiar to you except for the equality operator == and the
inequality operator! =.
Note that: = is used for assignment, whereas, == is used for comparison of two quantities.
Here is a simple program, which demonstrates the use of if and the relational operators.
main( )
{
int num ;
printf ( "Enter a number less than 10 " ) ;
scanf ( "%d", &num ) ;
if ( num <= 10 )
printf ( "What an obedient servant you are !" ) ;
}
If Statement, Types of If Statement Intro to Programming
MUHAMMAD HAMMAD WASEEM 2
Example 1: While purchasing certain items, a discount of 10% is offered if the quantity purchased is more
than 1000. If quantity and price per item are input through the keyboard, write a program to calculate
the total expenses.
main( )
{
int qty, dis = 0 ;
float rate, tot ;
printf ( "Enter quantity and rate " ) ;
scanf ( "%d %f", &qty, &rate) ;
if ( qty > 1000 )
dis = 10 ;
tot = ( qty * rate ) - ( qty * rate * dis / 100 ) ;
printf ( "Total expenses = Rs. %f", tot ) ;
}
You can also use expression instead of condition in if statement the syntax is as follow:
if ( expression )
statement ;
Here the expression can be any valid expression including a relational expression. We can even use
arithmetic expressions in the if statement. For example all the following if statements are valid.
if ( 3 + 2 % 5 )
printf ( "This works" ) ;
if ( a = 10 )
printf ( "Even this works" ) ;
if ( -5 )
printf ( "Surprisingly even this works" ) ;
Note that: in C a non-zero value is considered to be true, whereas a 0 is considered to be false.
Multiple Statements within if
It may so happen that in a program we want more than one statement to be executed if the
expression following if is satisfied. If such multiple statements are to be executed then they must be
placed within a pair of braces as illustrated in the following example.
Example 2: The current year and the year in which the employee joined the organization are entered
through the keyboard. If the number of years for which the employee has served the organization is
greater than 3 then a bonus of Rs. 2500/- is given to the employee. If the years of service are not greater
than 3, then the program should do nothing.
main( )
{
int bonus, cy, yoj, yr_of_ser ;
printf ( "Enter current year and year of joining " ) ;
scanf ( "%d %d", &cy, &yoj ) ;
yr_of_ser = cy - yoj ;
if ( yr_of_ser > 3 )
{
bonus = 2500 ;
printf ( "Bonus = Rs. %d", bonus ) ;
}}
If Statement, Types of If Statement Intro to Programming
MUHAMMAD HAMMAD WASEEM 3
The if-else Statement
The if statement by itself will execute a single statement, or a group of statements, when the
expression following if evaluates to true. It does nothing when the expression evaluates to false. Can we
execute one group of statements if the expression evaluates to true and another group of statements if
the expression evaluates to false? Of course! This is what the purpose of the else is statement.
The “if-else” statement tests the given relational condition. If the condition is true then the first
block of statements is executed. If the condition is false, the first block of statement is ignored and the
second block following the else is executed. The syntax of if-else statement is:
If (condition)
Statement;
else
Statement;
In case of multiple or block of statements the syntax is:
If (condition)
{
Statement;
Statement; //First Block
}
else
{
Statement;
Statement; //Second Block
}
Example 3: If his basic salary is less than Rs. 1500, then HRA = 10% of basic salary and DA = 90% of basic
salary. If his salary is either equal to or above Rs. 1500, then HRA = Rs. 500 and DA = 98% of basic salary.
If the employee's salary is input through the keyboard write a program to find his gross salary.
main( )
{
float bs, gs, da, hra ;
printf ( "Enter basic salary " ) ;
scanf ( "%f", &bs ) ;
if ( bs < 1500 )
{
hra = bs * 10 / 100 ;
da = bs * 90 / 100 ;
}
else
{
hra = 500 ;
da = bs * 98 / 100 ;
}
gs = bs + hra + da ;
printf ( "gross salary = Rs. %f", gs ) ;
}
If Statement, Types of If Statement Intro to Programming
MUHAMMAD HAMMAD WASEEM 4
The else if Clause
The else if clause is nothing different. It is just a way of rearranging the else with the if that follows
it. This would be evident if you look at the following code:
if ( i == 2 )
printf ( "With you…" ) ;
else
{
if ( j == 2 )
printf ( "…All the time" ) ;
}
if ( i == 2 )
printf ( "With you…" ) ;
elseif(j==2)
printf("…Allthetime");
Example 4: The marks obtained by a student in 5 different subjects are input through the keyboard. The
student gets a division as per the following rules:
Percentage above or equal to 60 - First division
Percentage between 50 and 59 - Second division
Percentage between 40 and 49 - Third division
Percentage less than 40 - Fail
Write a program to calculate the division obtained by the student.
main( )
{
int m1, m2, m3, m4, m5, per ;
per = ( m1+ m2 + m3 + m4+ m5 ) / per ;
if ( per >= 60 )
printf ( "First division" ) ;
else if ( per >= 50 )
printf ( "Second division" ) ;
else if ( per >= 40 )
printf ( "Third division" ) ;
else
printf ( "fail" ) ;
}
Nested if-elses
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.
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" ) ;
If Statement, Types of If Statement Intro to Programming
MUHAMMAD HAMMAD WASEEM 5
else
printf ( "How about mother earth !" ) ;
}
}
Note that the second if-else construct is nested in the first else statement. If the condition in the
first if statement is false, then the condition in the second if statement is checked. If it is false as well,
then the final else statement is executed.
Use of Logical Operators
C allows usage of three logical operators, namely, &&, || and !. These are to be read as ‘AND’
‘OR’ and ‘NOT’ respectively. The first two operators, && and ||, allow two or more conditions to be
combined in an if statement.
There are several things to note about these logical operators. Most obviously, two of them are
composed of double symbols: || and &&. Don’t use the single symbol | and &. These single symbols also
have a meaning. They are bitwise operators.
There are two ways in which we can write a program for example 4.
/* Method – I */
main( )
{
int m1, m2, m3, m4, m5, per ;
printf("Entermarks in five subjects");
scanf("%d%d%d%d%d",&m1,&m2,&m3,&m4,&m5);
per=(m1 + m2 + m3 + m4 + m5)/ 5 ;
if ( per >= 60 )
printf ("First division");
else
{
if (per >= 50)
printf ("Second division");
else
{
if (per >= 40)
printf ("Third division");
else
printf ("Fail") ;
} } }
/* Method – II */
main( )
{
int m1, m2, m3, m4, m5, per ;
printf("Entermarks in five subjects");
scanf("%d%d%d%d%d",&m1,&m2,&m3,&m4,&m5);
per =(m1 + m2 + m3 + m4 + m5)/5 ;
if (per >= 60)
printf ("First division");
if (( per >= 50 ) && ( per < 60 ))
printf ("Second division");
if (( per >= 40 ) && ( per < 50 ))
printf ("Third division");
if ( per < 40 )
printf ("Fail");
}
The third logical operator is the NOT operator, written as !. This operator reverses the result of
the expression it operates on. For example, if the expression evaluates to a non-zero value, then applying
! operator to it results into a 0. Vice versa, if the expression evaluates to zero then on applying ! operator
to it makes it 1, a non-zero value. The final result (after applying !) 0 or 1 is considered to be false or true
respectively. Here is an example of the NOT operator applied to a relational expression.
! ( y < 10 )
This means “not y less than 10”. In other words, if y is less than 10, the expression will be false,
since (y < 10) is true. We can express the same condition as (y >= 10).
If Statement, Types of If Statement Intro to Programming
MUHAMMAD HAMMAD WASEEM 6
Hierarchy of Operators Revisited
Operator Type
! Logical NOT
* / % Arithmetic & Modulus
+ - Arithmetic
< > <= >= Relational
== != Relational
&& Logical AND
|| Logical OR
= Assignment
Practice Time
Exercise 1: A company insures its drivers in the following cases:
− If the driver is married.
− If the driver is unmarried, male & above 30 years of age.
− If the driver is unmarried, female & above 25 years of age.
In all other cases the driver is not insured. If the marital status, sex and age of the driver are the
inputs, write a program to determine whether the driver is to be insured or not.
Exercise 2: Write a program to calculate the salary as per the following table:

[ITP - Lecture 08] Decision Control Structures (If Statement)

  • 1.
    If Statement, Typesof If Statement Intro to Programming MUHAMMAD HAMMAD WASEEM 1 Decision Control Structures The statements of a computer program are executed one after the other in the order in which they are written. This is known as sequential execution of the program. Many a times, we want a set of instructions to be executed in one situation, and an entirely different set of instructions to be executed in another situation. This kind of situation is dealt in C programs using a decision control instruction. A decision control instruction can be implemented in C using:  The if statement  The if-else statement  The conditional operators The if Statement Like most languages, C uses the keyword if to implement the decision control instruction. The general form of if statement looks like this: if ( this condition is true ) execute this statement ; The keyword if tells the compiler that what follows is a decision control instruction. The condition following the keyword if is always enclosed within a pair of parentheses. If the condition, whatever it is, is true, then the statement is executed. If the condition is not true then the statement is not executed; instead the program skips past it. But how do we express the condition itself in C? And how do we evaluate its truth or falsity? As a general rule, we express a condition using C’s ‘relational’ operators. The relational operators allow us to compare two values to see whether they are equal to each other, unequal, or whether one is greater than the other. Here’s how they look and how they are evaluated in C. Expression Is true if x == y x is equal to y x != y x is not equal to y x < y x is less than y x > y x is greater than y x <= y x is less than or equal to y x >= y x is greater than or equal to y The relational operators should be familiar to you except for the equality operator == and the inequality operator! =. Note that: = is used for assignment, whereas, == is used for comparison of two quantities. Here is a simple program, which demonstrates the use of if and the relational operators. main( ) { int num ; printf ( "Enter a number less than 10 " ) ; scanf ( "%d", &num ) ; if ( num <= 10 ) printf ( "What an obedient servant you are !" ) ; }
  • 2.
    If Statement, Typesof If Statement Intro to Programming MUHAMMAD HAMMAD WASEEM 2 Example 1: While purchasing certain items, a discount of 10% is offered if the quantity purchased is more than 1000. If quantity and price per item are input through the keyboard, write a program to calculate the total expenses. main( ) { int qty, dis = 0 ; float rate, tot ; printf ( "Enter quantity and rate " ) ; scanf ( "%d %f", &qty, &rate) ; if ( qty > 1000 ) dis = 10 ; tot = ( qty * rate ) - ( qty * rate * dis / 100 ) ; printf ( "Total expenses = Rs. %f", tot ) ; } You can also use expression instead of condition in if statement the syntax is as follow: if ( expression ) statement ; Here the expression can be any valid expression including a relational expression. We can even use arithmetic expressions in the if statement. For example all the following if statements are valid. if ( 3 + 2 % 5 ) printf ( "This works" ) ; if ( a = 10 ) printf ( "Even this works" ) ; if ( -5 ) printf ( "Surprisingly even this works" ) ; Note that: in C a non-zero value is considered to be true, whereas a 0 is considered to be false. Multiple Statements within if It may so happen that in a program we want more than one statement to be executed if the expression following if is satisfied. If such multiple statements are to be executed then they must be placed within a pair of braces as illustrated in the following example. Example 2: The current year and the year in which the employee joined the organization are entered through the keyboard. If the number of years for which the employee has served the organization is greater than 3 then a bonus of Rs. 2500/- is given to the employee. If the years of service are not greater than 3, then the program should do nothing. main( ) { int bonus, cy, yoj, yr_of_ser ; printf ( "Enter current year and year of joining " ) ; scanf ( "%d %d", &cy, &yoj ) ; yr_of_ser = cy - yoj ; if ( yr_of_ser > 3 ) { bonus = 2500 ; printf ( "Bonus = Rs. %d", bonus ) ; }}
  • 3.
    If Statement, Typesof If Statement Intro to Programming MUHAMMAD HAMMAD WASEEM 3 The if-else Statement The if statement by itself will execute a single statement, or a group of statements, when the expression following if evaluates to true. It does nothing when the expression evaluates to false. Can we execute one group of statements if the expression evaluates to true and another group of statements if the expression evaluates to false? Of course! This is what the purpose of the else is statement. The “if-else” statement tests the given relational condition. If the condition is true then the first block of statements is executed. If the condition is false, the first block of statement is ignored and the second block following the else is executed. The syntax of if-else statement is: If (condition) Statement; else Statement; In case of multiple or block of statements the syntax is: If (condition) { Statement; Statement; //First Block } else { Statement; Statement; //Second Block } Example 3: If his basic salary is less than Rs. 1500, then HRA = 10% of basic salary and DA = 90% of basic salary. If his salary is either equal to or above Rs. 1500, then HRA = Rs. 500 and DA = 98% of basic salary. If the employee's salary is input through the keyboard write a program to find his gross salary. main( ) { float bs, gs, da, hra ; printf ( "Enter basic salary " ) ; scanf ( "%f", &bs ) ; if ( bs < 1500 ) { hra = bs * 10 / 100 ; da = bs * 90 / 100 ; } else { hra = 500 ; da = bs * 98 / 100 ; } gs = bs + hra + da ; printf ( "gross salary = Rs. %f", gs ) ; }
  • 4.
    If Statement, Typesof If Statement Intro to Programming MUHAMMAD HAMMAD WASEEM 4 The else if Clause The else if clause is nothing different. It is just a way of rearranging the else with the if that follows it. This would be evident if you look at the following code: if ( i == 2 ) printf ( "With you…" ) ; else { if ( j == 2 ) printf ( "…All the time" ) ; } if ( i == 2 ) printf ( "With you…" ) ; elseif(j==2) printf("…Allthetime"); Example 4: The marks obtained by a student in 5 different subjects are input through the keyboard. The student gets a division as per the following rules: Percentage above or equal to 60 - First division Percentage between 50 and 59 - Second division Percentage between 40 and 49 - Third division Percentage less than 40 - Fail Write a program to calculate the division obtained by the student. main( ) { int m1, m2, m3, m4, m5, per ; per = ( m1+ m2 + m3 + m4+ m5 ) / per ; if ( per >= 60 ) printf ( "First division" ) ; else if ( per >= 50 ) printf ( "Second division" ) ; else if ( per >= 40 ) printf ( "Third division" ) ; else printf ( "fail" ) ; } Nested if-elses 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. 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" ) ;
  • 5.
    If Statement, Typesof If Statement Intro to Programming MUHAMMAD HAMMAD WASEEM 5 else printf ( "How about mother earth !" ) ; } } Note that the second if-else construct is nested in the first else statement. If the condition in the first if statement is false, then the condition in the second if statement is checked. If it is false as well, then the final else statement is executed. Use of Logical Operators C allows usage of three logical operators, namely, &&, || and !. These are to be read as ‘AND’ ‘OR’ and ‘NOT’ respectively. The first two operators, && and ||, allow two or more conditions to be combined in an if statement. There are several things to note about these logical operators. Most obviously, two of them are composed of double symbols: || and &&. Don’t use the single symbol | and &. These single symbols also have a meaning. They are bitwise operators. There are two ways in which we can write a program for example 4. /* Method – I */ main( ) { int m1, m2, m3, m4, m5, per ; printf("Entermarks in five subjects"); scanf("%d%d%d%d%d",&m1,&m2,&m3,&m4,&m5); per=(m1 + m2 + m3 + m4 + m5)/ 5 ; if ( per >= 60 ) printf ("First division"); else { if (per >= 50) printf ("Second division"); else { if (per >= 40) printf ("Third division"); else printf ("Fail") ; } } } /* Method – II */ main( ) { int m1, m2, m3, m4, m5, per ; printf("Entermarks in five subjects"); scanf("%d%d%d%d%d",&m1,&m2,&m3,&m4,&m5); per =(m1 + m2 + m3 + m4 + m5)/5 ; if (per >= 60) printf ("First division"); if (( per >= 50 ) && ( per < 60 )) printf ("Second division"); if (( per >= 40 ) && ( per < 50 )) printf ("Third division"); if ( per < 40 ) printf ("Fail"); } The third logical operator is the NOT operator, written as !. This operator reverses the result of the expression it operates on. For example, if the expression evaluates to a non-zero value, then applying ! operator to it results into a 0. Vice versa, if the expression evaluates to zero then on applying ! operator to it makes it 1, a non-zero value. The final result (after applying !) 0 or 1 is considered to be false or true respectively. Here is an example of the NOT operator applied to a relational expression. ! ( y < 10 ) This means “not y less than 10”. In other words, if y is less than 10, the expression will be false, since (y < 10) is true. We can express the same condition as (y >= 10).
  • 6.
    If Statement, Typesof If Statement Intro to Programming MUHAMMAD HAMMAD WASEEM 6 Hierarchy of Operators Revisited Operator Type ! Logical NOT * / % Arithmetic & Modulus + - Arithmetic < > <= >= Relational == != Relational && Logical AND || Logical OR = Assignment Practice Time Exercise 1: A company insures its drivers in the following cases: − If the driver is married. − If the driver is unmarried, male & above 30 years of age. − If the driver is unmarried, female & above 25 years of age. In all other cases the driver is not insured. If the marital status, sex and age of the driver are the inputs, write a program to determine whether the driver is to be insured or not. Exercise 2: Write a program to calculate the salary as per the following table: