Professional Documents
Culture Documents
4
Bilal Ashfaq Ahmed
In The Previous Lectures
Basic structure of C program
Variables and Data types
Operators
‘cout’ and ‘cin’ for output and input
Manipulators
Relational Operators
Selection/Conditional Statements
Decision Making Statements
IF Selection Structure
IF-ELSE Selection Structure
For Example: Suppose the passing grade on an exam is 60. The pseudo code statement
if ( grade >= 60 )
cout << "Passed";
IF Statement in C
Single Statement
if (condition)
Statement ;
Multiple Statement
if ( condition )
{
Statement1 ;
Statement2 ;
:
}
Example
Suppose, we have ages of two students (say for the
time being we have got these ages in variables). These
variables are age1 and age2. Now we say that if the
age1 is greater than age2, then display the statement
‘Student 1 is older than student 2’.
The coding for this program will be as below
#
#
void main()
{
int age 1,age2;
clrscr();
cout<<“Enter the age of first student”<<endl;
cin>>age1;
cout<<“Enter the age of Second student”<<endl;
cin>>age2;
if (age1 > age2)
cout << “Student 1 is older than student 2”;
getch();
}
Flow Charts
Description Symbol
Start / End
Processing
Input / Output
Decision/Condition
Connector
Flow lines
Stored Procedure
Comments …..
Boolean
Exp
Statement(s)
Rest of the
program
Examples Using two IF
Statement
/* This program checks the age of Amer and Amara and displays the
appropriate the message. The program is using two if statements.*/
# include <iostream.h>
#include<conio.h>
void main ( )
{
int AmerAge, AmaraAge;
clrscr();
//prompt the user to enter Amer’s age
cout << “Please enter Amer’s age “ ;
cin >> AmerAge;
//prompt the user to enter Amara’s age
cout << “Please enter Amara’s age “ ;
cin >> AmaraAge;
//perform the test
if (AmerAge > AmaraAge )
{
cout << “ Amer is older than Amara”;
}
if (AmerAge < AmaraAge )
{
cout << “ Amer is younger than Amara”;
}
}
Logical Operators
AND &&
OR ||
NOT !
IN C
if(a > b && d > c)
if (age>18 || height>5)
IF ELSE Statement
if ( condition)
{
statement(s);
}
else
{
statement(s);
}
IF ELSE Flow chart
IF Example
Code
#include<iostream.h>
#include<conio.h>
void main()
{
int num;
clrscr();
cout<<" Enter Number : “<<endl;
cin>>num;
if(num % 2 == 0)
cout<<“EVEN Number”<<endl;
else
cout<<“ODD Number”<<endl;
getch();
}
Conditional Operator
Symbol (?:)
Closely related to if–else statement
Only ternary operator in C++
Syntax:
(condition)? Statement A : Statement B;
Example
cout<<(num%2 == 0) ? “EVEN Number” : “ODD Number” ;
Nested IF Structure
if structure is used within an other if structure
Syntax
if ( condition-1 ) //outer if statement
{
if ( condition-2 ) //inner if statement
{
Statement(s) ;
}
}