SlideShare a Scribd company logo
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:

More Related Content

What's hot (20)

PPT
C language control statements
suman Aggarwal
 
PDF
C programming decision making
SENA
 
PPTX
FLOW OF CONTROL-INTRO PYTHON
vikram mahendra
 
PPT
Mesics lecture 6 control statement = if -else if__else
eShikshak
 
PPT
Control All
phanleson
 
PPT
Control structure
Samsil Arefin
 
PPT
If-else and switch-case
Manash Kumar Mondal
 
PPT
The Three Basic Selection Structures in C++ Programming Concepts
Tech
 
PPTX
C# conditional branching statement
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Control statement-Selective
Nurul Zakiah Zamri Tan
 
PPTX
Control structure of c language
Digvijaysinh Gohil
 
PPTX
Conditional statements
University of Potsdam
 
PPTX
Vb decision making statements
pragya ratan
 
PPT
Control Structures
Ghaffar Khan
 
DOCX
C Control Statements.docx
JavvajiVenkat
 
PPT
Selection Control Structures
PRN USM
 
PPTX
Decision making statements in C
Rabin BK
 
PPT
03a control structures
Manzoor ALam
 
C language control statements
suman Aggarwal
 
C programming decision making
SENA
 
FLOW OF CONTROL-INTRO PYTHON
vikram mahendra
 
Mesics lecture 6 control statement = if -else if__else
eShikshak
 
Control All
phanleson
 
Control structure
Samsil Arefin
 
If-else and switch-case
Manash Kumar Mondal
 
The Three Basic Selection Structures in C++ Programming Concepts
Tech
 
C# conditional branching statement
baabtra.com - No. 1 supplier of quality freshers
 
Control statement-Selective
Nurul Zakiah Zamri Tan
 
Control structure of c language
Digvijaysinh Gohil
 
Conditional statements
University of Potsdam
 
Vb decision making statements
pragya ratan
 
Control Structures
Ghaffar Khan
 
C Control Statements.docx
JavvajiVenkat
 
Selection Control Structures
PRN USM
 
Decision making statements in C
Rabin BK
 
03a control structures
Manzoor ALam
 

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

PPT
Fcp chapter 2 upto_if_else (2)
Jagdish Kamble
 
PDF
C Programming Unit II Sharad Institute college
SatishPise4
 
PPTX
Ch5 Selection Statements
SzeChingChen
 
PPTX
Decision Making and Branching
Munazza-Mah-Jabeen
 
PDF
Selection & Making Decisions in c
yndaravind
 
PPTX
Programming note C#
Ahmad Syahmi Irfan
 
PDF
control statement
Kathmandu University
 
PPTX
COM1407: Program Control Structures – Decision Making & Branching
Hemantha Kulathilake
 
PDF
Programming Fundamentals Decisions
imtiazalijoono
 
PDF
C Language Lecture 4
Shahzaib Ajmal
 
PPTX
Computer Programming - if Statements & Relational Operators
John Paul Espino
 
PDF
Control statements anil
Anil Dutt
 
PDF
Unit 2=Decision Control & Looping Statements.pdf
Dr. Ambedkar Institute of Technology, Bangalore 56
 
PPTX
Conditional Statements in C.pptx
DelnazBehal
 
PPT
CHAPTER-3a.ppt
Tekle12
 
PPT
Control statments in c
CGC Technical campus,Mohali
 
PPTX
Programming in C
Nishant Munjal
 
PDF
Unit ii chapter 2 Decision making and Branching in C
Sowmya Jyothi
 
PPTX
6 Control Structures-1.pptxAAAAAAAAAAAAAAAAAAAAA
EG20910848921ISAACDU
 
PPTX
Decision Control Structure If & Else
Abdullah Bhojani
 
Fcp chapter 2 upto_if_else (2)
Jagdish Kamble
 
C Programming Unit II Sharad Institute college
SatishPise4
 
Ch5 Selection Statements
SzeChingChen
 
Decision Making and Branching
Munazza-Mah-Jabeen
 
Selection & Making Decisions in c
yndaravind
 
Programming note C#
Ahmad Syahmi Irfan
 
control statement
Kathmandu University
 
COM1407: Program Control Structures – Decision Making & Branching
Hemantha Kulathilake
 
Programming Fundamentals Decisions
imtiazalijoono
 
C Language Lecture 4
Shahzaib Ajmal
 
Computer Programming - if Statements & Relational Operators
John Paul Espino
 
Control statements anil
Anil Dutt
 
Unit 2=Decision Control & Looping Statements.pdf
Dr. Ambedkar Institute of Technology, Bangalore 56
 
Conditional Statements in C.pptx
DelnazBehal
 
CHAPTER-3a.ppt
Tekle12
 
Control statments in c
CGC Technical campus,Mohali
 
Programming in C
Nishant Munjal
 
Unit ii chapter 2 Decision making and Branching in C
Sowmya Jyothi
 
6 Control Structures-1.pptxAAAAAAAAAAAAAAAAAAAAA
EG20910848921ISAACDU
 
Decision Control Structure If & Else
Abdullah Bhojani
 
Ad

More from Muhammad Hammad Waseem (20)

PDF
[ITP - Lecture 17] Strings in C/C++
Muhammad Hammad Waseem
 
PDF
[ITP - Lecture 16] Structures in C/C++
Muhammad Hammad Waseem
 
PDF
[ITP - Lecture 15] Arrays & its Types
Muhammad Hammad Waseem
 
PDF
[ITP - Lecture 14] Recursion
Muhammad Hammad Waseem
 
PDF
[ITP - Lecture 13] Introduction to Pointers
Muhammad Hammad Waseem
 
PDF
[ITP - Lecture 12] Functions in C/C++
Muhammad Hammad Waseem
 
PDF
[ITP - Lecture 11] Loops in C/C++
Muhammad Hammad Waseem
 
PDF
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
Muhammad Hammad Waseem
 
PDF
[ITP - Lecture 09] Conditional Operator in C/C++
Muhammad Hammad Waseem
 
PDF
[ITP - Lecture 07] Comments in C/C++
Muhammad Hammad Waseem
 
PDF
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
Muhammad Hammad Waseem
 
PDF
[ITP - Lecture 05] Datatypes
Muhammad Hammad Waseem
 
PDF
[ITP - Lecture 04] Variables and Constants in C/C++
Muhammad Hammad Waseem
 
PDF
[ITP - Lecture 03] Introduction to C/C++
Muhammad Hammad Waseem
 
PDF
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
Muhammad Hammad Waseem
 
PDF
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
Muhammad Hammad Waseem
 
PPTX
[OOP - Lec 20,21] Inheritance
Muhammad Hammad Waseem
 
PPTX
[OOP - Lec 19] Static Member Functions
Muhammad Hammad Waseem
 
PPTX
[OOP - Lec 18] Static Data Member
Muhammad Hammad Waseem
 
PPTX
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
Muhammad Hammad Waseem
 
[ITP - Lecture 17] Strings in C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 16] Structures in C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 15] Arrays & its Types
Muhammad Hammad Waseem
 
[ITP - Lecture 14] Recursion
Muhammad Hammad Waseem
 
[ITP - Lecture 13] Introduction to Pointers
Muhammad Hammad Waseem
 
[ITP - Lecture 12] Functions in C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 11] Loops in C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 09] Conditional Operator in C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 07] Comments in C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
Muhammad Hammad Waseem
 
[ITP - Lecture 05] Datatypes
Muhammad Hammad Waseem
 
[ITP - Lecture 04] Variables and Constants in C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 03] Introduction to C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
Muhammad Hammad Waseem
 
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
Muhammad Hammad Waseem
 
[OOP - Lec 20,21] Inheritance
Muhammad Hammad Waseem
 
[OOP - Lec 19] Static Member Functions
Muhammad Hammad Waseem
 
[OOP - Lec 18] Static Data Member
Muhammad Hammad Waseem
 
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
Muhammad Hammad Waseem
 
Ad

Recently uploaded (20)

PPTX
How to Create a Customer From Website in Odoo 18.pptx
Celine George
 
PPTX
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
PPTX
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PDF
Introduction presentation of the patentbutler tool
MIPLM
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
PPTX
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
PDF
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PDF
Council of Chalcedon Re-Examined
Smiling Lungs
 
PPTX
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PDF
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
PPTX
DAY 1_QUARTER1 ENGLISH 5 WEEK- PRESENTATION.pptx
BanyMacalintal
 
PPTX
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
PPTX
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 
How to Create a Customer From Website in Odoo 18.pptx
Celine George
 
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
Introduction presentation of the patentbutler tool
MIPLM
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
Council of Chalcedon Re-Examined
Smiling Lungs
 
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
DAY 1_QUARTER1 ENGLISH 5 WEEK- PRESENTATION.pptx
BanyMacalintal
 
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 

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

  • 1. 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 !" ) ; }
  • 2. 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 ) ; }}
  • 3. 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 ) ; }
  • 4. 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" ) ;
  • 5. 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).
  • 6. 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: