0% found this document useful (0 votes)
9 views57 pages

5-Lecture-FoP-Control Structures

C++ control structure

Uploaded by

bilalasim1020
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views57 pages

5-Lecture-FoP-Control Structures

C++ control structure

Uploaded by

bilalasim1020
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

CS-114 Fundamentals of Programming

Control Structures – Selection Structures

Dr Ayesha Zeb
Email: [email protected]
Lecture Contents

• Pseudocodes
• Flow Charts
• Control structures
– Selection structures
• If-else statements
• Switch case statement
• Conditional operator
Pseudocodes

• For branching and looping, pseudocodes use four


statement keywords to portray logic:
1. IF, THEN, ELSE, and DO.
2. Repetitive processing logic is portrayed using the statements DO
WHILE (repeat an activity as long as a certain condition exists).
3. DO UNTIL (repeat an activity until a certain condition is met), and
4. END DO (stop repeating the activity).
• The logic statement keywords are capitalized, and
several levels of standard indentation are used.
• The keywords DATA, INPUT and RESULT, OUTPUT
may also be used
Pseudocode Example
START “murder of Jamal Khan”
“Solve murder of Jamal Khan” Statement of problem
DO WHILE there are suspects Objective
IF Kashif’s fingerprints are on the sword THEN
Identify Kashif’s as the murderer
ELSE
Question Sarfraz
IF Sarfraz has an alibi THEN
Continue
Grill Asif
searching
Give Miss Rifat the third degree as long as
Identify
there are
fingerprints on sword
suspects
ENDIF
ENDIF
Arrest murderer
END DO
END “murder of Jamal Khan”
Pseudocode practice exercises

• Write down a pseudocode for the following problems


– Calculate the average of 5 numbers input from the user.
– Input 5 numbers from the user and find the smallest number
among them.
Flowcharts

• A program flowchart graphically details the processing


steps of a particular program.
• A program flowchart is a diagram that uses standard
ANSI symbols to show the step-by-step processing
activities and decision logic needed to solve a problem.
• The flow of logic in a program flowchart normally goes
from top to bottom and left to right.
• Arrows are used to show a change from those directions.
Symbols
Make a flowchart for the following:
Find the smallest of 5 numbers input by the user.

Symbol Description
TERMINAL - To start or end a flowchart

INPUT / OUTPUT - Used with Read, Input, Print and other I/O commands.
PROCESSING - Used for operations done inside the computer. Such as
calculations, storing and moving of data.
DECISION - Used to ask a question in programming. Questions are Yes/No
format (Used with the If Statement).

DIRECTION FLOW - Used to connect symbols and to represent the direction


of flow. Lines should not cross each other. Arrowheads should be placed at
the end close to the symbol.

Connector - or joining of two parts of program


Flowcharts

• A flowchart is used to;


– Clarify the program logic.
– Identify alternate processing methods available.
– Serve as a guide for program coding.
– Serve as documentation.

• The book follows UML (Unified Modeling Language) for


flowcharts.
UML Activity Diagram / Flowchart
Basic programming Building Blocks

• There are only three basic building blocks to develop a


solution to a problem.
• They are language independent and can be used to
develop a conceptual plan to tackle any problem.
• The three basic building blocks are:
– Sequential Execution:, where instructions are performed one
after the other.
– Branching Operations:, where a decision is made to perform
one block of instruction or another; and
– Looping Operations, where a block of instructions is repeated.
Flowchart example

• Pseudocode:
Read in n
Is n<0 ?
If yes, n is negative
Print “Negative”
If no, is n==0?
Print “Zero”
If no, n is “Positive”
End Branch
End Branch
Flowchart example

Construct a flow chart that finds the sum, average and


product of three numbers.
Flowchart example

Variables Algorithm

X: First Number Step 1- Start


Y: Second Number Step 2- Read X, Y, Z

Z: Third Number Step 3- Calculate S = X+Y+Z

S: Sum (X+Y+Z) Step 4- Calculate A = S/3

A: Average (S/3) Step 5- Calculate P = X*Y*Z

P: Product (X*Y*Z) Step 6- Print S, A, P


Step 7- Stop
Flowchart example

Start

Flowchart Read X,Y,Z

S= X+Y+Z
A=S/3
P=X*Y*Z

Print S,A,P

Stop
Flowchart example

Construct a flow chart for the


following function

X X>=0
F(x) = { -X X<0
Flowchart example

Variables Algorithm

X : Number Step 1- Start


F: function of X Step 2- Read X
Step 3- if X >=0 then F =X
Step 4- if X <0 then F =-X
Step 5- Print F
Step 6- Stop
Flowchart example

Start

Flowchart Read X

NO YES
X>=0

F=-X F=X

Print F

Stop
Flowchart practice exercises

• Make a flowchart for the following problems


– Calculate the average of 5 numbers input from the user
– Input 5 numbers from the user and find the smallest number
among them
Class Activity

Problem: Write Algorithm and Flowchart to find solution of


Quadratic equation
Problem: Write Algorithm and Flowchart to find
solution of Quadratic equation
START

• Algorithm: Read
• Step 1: Start a, b, c
• Step 2: Read a, b, c
• Step 3: d  sqrt ( b  b − 4  a  c ) d  sqrt(b x b – 4 x a x c)
• Step 4: x1  (–b + d) / (2 x a)
• Step 5: x2  (–b – d) / (2 x a) x1 (–b + d) / (2 x a)
• Step 6: Print x1, x2
• Step 7: Stop X2  (–b – d) / (2 x a)

Print X1, X2

STOP
Writing Programs

• Control Structures control the flow of the program


• Any program can be written using the following control
structures
– Sequence
– Selection
– Repetition
Sequence Structure

• Built into C++


Selection Structures

• Selection structures cause one section of code to be


executed or not depending on a conditional clause.
– Conditional operator (also called Ternary Operator)
– if statement
– switch statement
Control Structures: If… Else If … Else

• Used to execute only


certain portions of
code

• If
• Else
• Else if
Control Structures: If… Else If … Else

• Used to execute only certain


portions of code
• If
• Else
• Else if
• Block { … }
The if statement

• Used where the execution of an action depends on the


satisfaction of a condition.
– if condition is true -> action is done

T
The if statement

• Used where the execution of an


action depends on the satisfaction
of a condition.
– if condition is true -> action is done
– if condition is false -> action is not done

F
The if statement

• Develop a system that tells the user that he is over-


speeding if his speed crosses120km/hr.

• Pseudocode
IF speed is greater than 120km/hr
THEN print “over-speeding”
Any
The if statement statement
that results in
True or False
Syntax Logical or
Relational

if (condition)
{ statement1;
statement 2; T
F
….
statement n;
}
The if statement

if (speed>120)
{cout<<"over speeding";
cout << "reduce speed now";
}

T
… F

If - else
• if is a single-selection statement which performs an
indicated action only when the condition is TRUE;
otherwise the action is skipped.

• if-else is a double-selection statement which performs an


action when the condition is TRUE and a different action
when the condition is FALSE.
If - else
• Used where there are
different actions to be
executed depending on the
result of a given condition.
– if condition is true -> action is
done
– if condition is false -> a
different action is done
If - else

• Syntax:
if (condition)
{statement1; statement 2;…. statement n;
}
else
{statement1; statement 2;….statement n;
}

• Note: if the specified condition is true, then all the


statements in the first curly braces will be executed, else
all the statements in the next curly braces will be
executed.
If - else
• Determine whether a number
is positive or negative.

• Pseudocode
• IF number is greater than or
equal to 0, THEN print
“positive”
• ELSE print “negative”
If - else

if (number>=0)
cout<<"number is positive";
else
cout<<"number is negative";
If - else

• TRY ME! : for even numbers add half the number to y.


For odd numbers, subtract half.

if (x%2==0)
y += x/2;
else
y -= x/2;
Some notes

• If there is only one statement following the if, then the curly
braces are optional.
• If there are multiple statements, the braces are necessary.
• Same is true for the statements following the else.
Some notes

– E.g.
if (a<b)
b = a+1;
b = b + 10;
cout<<"print A"<<b;

Output (if condition is true)


Some notes

• An if can exist without an else.


• An else, without an if has no meaning.
The else if keyword
• Used where there are multiple actions to be executed
based on different conditions.
– if condition is true -> action is done
– if condition is false -> next condition is checked
The else if keyword

• Syntax:
if (condition)
{statement1; statement 2;…. statement n;
}
else if (condition 2)
{statement1; statement 2;….statement n;
}
else
{statement1; statement 2;….statement n;
}
The else if keyword

if (x==0)
{cout << " x is ZERO" <<endl;}
else if (x>0)
{cout << " x is positive" <<endl;}
else
{cout << " x is negative" <<endl;}
The else if keyword
• Additional alternative control paths
• Conditions evaluated in order until one is met; inner statement
(or statements) are then executed
• If multiple conditions are true, only first condition is executed,
the remaining are ignored
Nested if statements
• An if statement within the
executable block of another if
statement
• Use?
• Used where several conditions
need to be met for the execution
of an action.
• Is this completely true? How?
Nested if statements
• Conditions are checked in order,
i.e. the inner condition is checked
only if the outer condition is
satisfied.
– if condition is true -> inner condition
is checked
– if inner condition is true -> action is
done
Nested if statements

• Syntax:
if (condition)
{if (condition)
statement1;//(…. to n)
else
statement;
}
else
{statement1;statement 2;….
statement n;
}
Nested if statements
• Determine whether the number is
positive even, positive odd, or
zero.
• Pseudocode
IF number is greater than 0,
IF number is divisible by 2,
THEN print “positive even”
ELSE print “positive odd”
ELSE print “zero”
Nested if statements

if (num>0)
{if ((num%2)==0)
cout << "positive even" <<
endl;
else
cout << "positive odd" <<
endl;
}
else
cout << "zero" << endl;
Nested if statements
1. if (x%4 == 0)
{if (x%2 == 0)
y= 2;
To associate else with outer if statement: use
}
braces
else
y= 1;

2. if (x < 0)
if (y != 4)
z = y * x;
else
z = y / x;
else if (y > 4)
z = y + x;
else
z = y - x;
Pseudocode Example
START “murder of Jamal Khan”
“Solve murder of Jamal Khan”
DO WHILE there are suspects
IF Kashif’s fingerprints are on the sword
THEN Identify Kashif as the murderer
ELSE
Question Sarfraz
IF Sarfraz has an alibi THEN
Grill Asif
Give Miss Rifat the third degree
Identify fingerprints on sword
ENDIF
ENDIF
Arrest murderer
END DO
END “murder of Jamal Khan”
TRY ME

1. Develop a software to display the different climatic


conditions based on weather, e.g. for temperature less
than 0 degrees it should display “freezing”. Conditions
should be: freezing, cold, pleasant, warm, hot.
If else-if
if (day == 1) if (day == 1)
cout<< "Sunday”; cout<< "Sunday”;

if (day == 2) else if (day == 2)


cout << "Monday”; cout<< "Monday”;

if (day == 3) else if (day == 3)


cout << "Tuesday”; cout<< "Tuesday”;

if (day == 4) else if (day == 4)


cout << “Wednesday”; cout <<"Wednesday”;

Here, each if condition will Here, the compiler will skip the
be checked even if the true remaining if conditions following the
one is found earlier on. true one.
Control Structures: If… Else If … Else
#include <iostream> else if ((x> y) && (x < z))
#include <string> {
using namespace std; cout << "x is greater
than y and less than z";
int main() { }
int x = 5; else {
int y = 10; cout << "x is greater
int z = 3; than y and z";

if ((x < y) && (x < z)){ }

cout << "x is less cout << endl;


than z and y "; return 0;
} }
Decision: Using the switch statement

#include <iostream>
using namespace std;
int main(){
int x,y; char op;
cout << "Enter two integers: "; cin >> x >> y;
cout << "Enter an operator [+,-,*,/,%]: "; cin >> op;
switch (op){
case '+': cout << x + y << endl; break;
case '-': cout << x - y << endl; break;
case '*': cout << x * y << endl; break;
case '/': cout << x / y << endl; break;
case '%': cout << x % y << endl; break;
default: cout <<"Invalid Operator \n";
} return 0; }
Decision: Using the ? : statement

// demonstrates ? :
#include <iostream>
using namespace std;
int main(){
int m,n;
cout << "Enter two integers: ";
cin >> m >> n;
cout << ( m < n ? m : n ) << " is the minimum. \n";
return 0;
}// The conditional expression ( m<n ? m : n ) evaluates
// to m if m < n, and to n otherwise.
Acknowledgement/References
• Slides contents taken from Ma’am Fatima Faruq

• Deital and Deital, “C++ How to Program”, Latest Edition

• Stroustrup, “Programming – Principles and Practice


Using C++”, Latest Edition

You might also like