Programming Fundamentals
INSTRUCTED BY: Shahid
Javaid
Lecture 15
Control Structures
2
Control Structures
Programs are written using three basic structures:
–> Sequence
• a sequence is a series of statements that execute one after another
–> Selection (branching/conditional)
• selection (branch) is used to execute different statements depending on certain
conditions
–> Repetition (loop or iteration)
• repetition is used to repeat statements
3
while loop
Various forms of while loops:
1. Counter controlled
2. Sentinel controlled
3. Flag controlled
while loop – Counter-Controlled
If you know exactly how many times pieces of data need to be
executed, the while loop becomes a counter-controlled loop
General syntax:
while loop – Counter-Controlled
Example
#include <iostream>
#include <conio>
int main()
{
int count;
initializing
count = 1;
while (count <= 10)
{
cout << count << endl;
count++;
} updating
getch();
return 0;
}
while loop – Counter-Controlled
Problem: Create a program that displays the word
‘Hello’ on the screen 10 times.
Solution:
Pseudocode
Begin
Initialize lcv to 0
While lcv is less than
10
Display “Hello”
Update lcv
End while
End
while loop – Counter-Controlled
Flowchart
Begin
Initialize
counter = 0
T update
counter < 10 Hello
counter
End
while loop – Counter-Controlled
Program and output
int main()
{
int count;
count = 0;
while (count < 10)
{
cout << "Hello" << endl;
count++;
}
getch();
return 0;
}
while loop – Counter-Controlled
Exercise: Write a C++ statement associated to the
following flowchart.
Begin
Initialize
counter = 10
T Add 10 to
counter < 100 Display counter
Multiplied by 2 counter
F
End
while loop – Counter-Controlled
Program and output
int main()
{
int count;
count = 10;
while (count < 100)
{
cout << count * 2 << endl;
count += 10;
}
getch();
return 0;
}
while loop – Sentinel-Controlled
A sentinel-controlled while loop uses a special value called sentinel
to control the loop.
o Sentinel value is a special value that indicates the end of a set of data or of a
process
Sentinel variable is tested in the condition and loop ends when sentinel
is encountered
while loop – Sentinel-Controlled
General syntax :
while loop – Sentinel-Controlled
Example
#include <iostream>
#include <conio>
int main()
{
char answer;
cout << "Do you want to quit (Y - yes, N - no) : ";
cin >> answer;
while (answer != 'Y') Sentinel value
{
cout << "Welcome to the program." << endl;
cout << "Do you want to quit (Y - Yes, N - No) : ";
cin >> answer;
}
cout << "Bye.";
getch();
return 0;
}
while loop – Sentinel-Controlled
Output screen
while loop – Sentinel-Controlled
Exercise: to create a program that process the loop as long as user
enter an even number
while loop – Sentinel-Controlled
Solution
o Flowchart
Begin
Prompt for
a number
Get
a number
True Get another
number % 2 == 0
number
False
End
while loop – Sentinel-Controlled
Program
int main()
{
int number;
cout << "Enter a number : ";
cin >> number;
while (number % 2 == 0)
{
cout << "Enter the next number : ";
cin >> number;
}
cout <<"You have entered an odd number to
terminate”
<<“the program.";
getch();
return 0;
}
while loop – Sentinel-Controlled
Output
while loop – Flag-controlled
A flag-controlled while loop uses a bool variable to control the
loop
The flag-controlled while loop takes the form:
while loop – Flag-controlled
void main()
Example {
bool found = false;
char continue;
while (!found)
{
cout << " Program continued..still want to
continue"
<< " the loop? Press Y for yes, N for No"<<
endl;
cin>>continue;
if(continue == ‘Y’)
found = false;
else
found = true;
}
cout << "Program terminated";
getch();
}
More Examples which output is true?
void main()
{
int x;
while (cin >> x, x!=-999)
cout << x << ’ ’;
}
inputs
2 3 -6 -999 2 3 -6 -999
2 3 -6 OR -999
output
22
int main() {
To find sum of positive integers
int sum = 0;
int value;
bool nonNegative = true; // Initilizing flag variable
while (nonNegative) { // Test if nonNegative is true
cout << "Enter a positive number: ";
cin >> value;
if (value < 0)
nonNegative = false;
else
sum += value;
}
cout << "You entered a negative number, you can not proceed.... \n";
cout << "Sum of input numbers is " << sum << endl;
return 0; } 23
The for Loop
INSTRUCTED BY: Shahid
Javaid
for loop
Also called as a counted or indexed for loop
The general form of the for statement is:
for ([initial statement]; loop condition; [update statement])
statement;
for([initial statement]; loop condition; [update statement])
{ statement1;
statement2;
…
}
The initial statement, loop condition, and update statement are called for
loop control statements
Items in square brackets ([ ]) are optional.
In C++, for is a reserved word
for loop
Flowchart
initialization
condition
evaluated false
true
statement
increment
for loop
for ([initial statement]; loop condition; [update statement])
statement;
The for loop executes as follows:
1. First of all the initial statement executes
2. Then the loop condition is evaluated. If the loop condition evaluates to
true
i. Execute the statements in the body of the for loop
ii. Execute the update statement (the third expression in the
parentheses)
3. Repeat Step 2 until the loop condition evaluates to false
o The initial statement usually initializes a variable
for loop – Example
Using for loop to display ‘Welcome to C++’ three times
Pseudocode:
Start
For( set i to 1; i less than or equal to 3; add 1 to i)
display “welcome to C++”
Endfor
End
for loop – Example
Flowchart Start
i=1
False
i <= 3 End
True
Display “welcome
to C++”
i ++
for loop – Example 1
Example: Displaying the numbers 1 through 3
initialization condition update
for (int number = 1; number <= 3; number = number + 1)
{ cout << number << endl; }
Result:
1
2
3
for loop – Example
Iteration - 1
for (int x =1; x<=3; x++)
Source Code
Iterations
Iteration - 2
{ Iteration - 3
cout<<x; Iteration - 4
}
initialization
condition
x x<=3
Execution Flow
evaluated
false
1 1<=3
Working
true
2
3
2<=3
3<=3
1
12
123 statement
increment
4 4<=3
for loop – Example 2
Example: Write a program to create a program to display backward
the first 10 non negative number.
for loop – Exercises
Exercise 1: create a program that display the first 10 positive odd
integers.
1, 3, 5, 7, 9, 11, 13, 15, 17, 19
for loop – Exercises
Exercise 1 – Answer 1
int num;
for (num = 1; num <= 20; num = num + 2)
{
cout << num << “, ” << endl;
}
Exercise 1 – Answer 2
int num;
for (num = 1; num <= 20; num++)
{
if (num % 2 != 0)
{
cout << num << “, ” << endl;
}
}
for loop – Exercises
Exercise 2: how many time the following loop processed?
for (int count = 6; count < 6; count = count + 1)
cout << count << endl;
Answer:
for loop – Exercises
Exercise 3: how many time the following loop processed?
for (int count = 4; count <= 10; count = count + 2)
cout << count << endl;
Answer:
for loop – Example 3
Calculate and display total of 3 numbers
Pseudocode:
Start
Initialize total = 0
for (set counter to 1; counter less than or
equal to 3; add 1 to counter)
input number
total = total + number
Endfor
Display total
End
for loop – Example 3
Flowchart Start
counter=1, total = 0,
for False
counter Output
<= 3 total
True
Input End
number
total = total + number
counter = counter + 1
for loop – Example 3
C++ program segment
total = 0;
for (int count = 1; count <= 3; count = count + 1)
{
cin>>number;
total = total + number;
}
cout << “total:” <<total<<endl;
for loop – Exercises
Exercise 4: Suppose j, sum, and num are int variables, and the input values are
26, 34, 61, 4, and -1. What is the output of the code below?
cout << "Enter a number : ";
cin >> num;
for (j = 1; j <= 4; j++)
{
sum = sum + num;
cout << "Enter a number : ";
cin >> num;
}
cout << sum << endl;
for loop – Exercises
Exercise 4: Answer
for loop
A semicolon at the end of the for statement (just before the
body of the loop) is a semantic error. In this case, the action of
the for loop is empty.
for (initialization; condition; update statement) ;
Statement;
In the for statement, if the loop condition is omitted, it is
assumed to be true.
for loop
In a for statement, you can omit all three statements—initial
statement, loop condition, and update statement.
o The following is a legal for loop:
for (;;)
cout << "Hello" << endl;
BUT
This is an infinite loop, continuously printing the word Hello
Example
void main()
{
int i;
for(i=1; i<7; i++)
cout << i << ” ”;
}
1 2 3 4 5 6
44
Example
void main()
{
int i;
for(i=1; i<7; ++i)
cout << i << ” ”;
}
1 2 3 4 5 6
45
Example
void main()
{
int i;
for(i=1; i++<7; )
cout << i << ” ”;
}
2 3 4 5 6 7
46
Example
void main()
{
int i;
for(i=1; ++i<7; )
cout << i << ” ”;
}
2 3 4 5 6
47
Example
void main()
{
int i;
for(i=9; i>5; --i)
cout << i << ” ”;
}
9 8 7 6
48
while equivalent of for
Example
for (i=0; i<5; i++)
for(e1; e2; e3)
cout << i;
s;
same as
same as
e1; i=0;
while(e2) { while (i<5) {
s; cout << i;
i++;
e3;
}
}
49