You are on page 1of 19

Chapter Six: Loops

91
Chapter Six: Loops

6.1 Introduction
-In programming languages, loops are START
used to execute a set of statements
repeatedly until a particular condition is Iß1
unsatisfied.
No
-This sequence of statements to be
I <= 10 END
executed is kept inside the curly braces {
} known as the Loop body. Yes

-Before every execution of loop body,


PRINT I
condition is verified, and if it is found to
be true the loop body is executed. When
IßI+1
the condition check returns false, the
loop body is not executed.

Ex: Printing 1,2,…10 →

-There are three types of loops:


1- for loop
2- while loop
3- do while loop

6.2 The for Loop


-for loop is used to execute a set of statements repeatedly until a particular
condition is not satisfied.

- for loop syntax:


for (initialization; condition; increment/decrement)
statement;

Introduction to Algorithms Lecture Notes Version 5. Prepared by Dr. Alaa Al-Obaidi. January 2023
Chapter Six: Loops

92
- The other form is:

for (initialization; condition; increment/decrement) {


block of statements;
}

-The initialization is an assignment statement (example: I = 1) that is used to set


the loop control variable.

-The condition is a relational expression (example: i <= 10) that determines when
the loop exits.

-The increment/decrement (example: i = i + 1) defines how the loop control


variable changes each time the loop is repeated.

initialization Ex: i = 1
outside the loop

The condition returns false


condition Ex: i <= 10 The condition returns true
inside the loop
……
…..
Loop body… repeated
statement(s)
…..
….
….

increment Ex: i = i + 1
inside the loop

Outside the loop


The condition returns false
Resume from this place

Introduction to Algorithms Lecture Notes Version 5. Prepared by Dr. Alaa Al-Obaidi. January 2023
Chapter Six: Loops

93
-We must separate these three major sections by semicolons. The for loop
continues to execute as long as the condition is true. Once the condition becomes
false, program execution resumes on the statement following the for. Ex: a for
loop for printing 1 2 3 4 5 6 7 8 9 10

int i;
for (i = 1; i <= 10; i = i + 1)
cout << i << " ";

START
initialization: i = 1 (executed only once)
iß1
condition: i <= 10
repeated statement: cout << i << " ";
No
i <= 10 END
increment: i = i + 1

output: 1 2 3 4 5 6 7 8 9 10 Yes

PRINT i , “ “

ißi+1

Introduction to Algorithms Lecture Notes Version 5. Prepared by Dr. Alaa Al-Obaidi. January 2023
Chapter Six: Loops

94
-We can rewrite the previous example START
as:
for (int i = 1; i <= 10; ++i)
iß2
cout << i << " ";

-Example: Write the even numbers No


from 2 to 60. i <= 60 END
for (int i = 2; i <= 60; i=i+2)
cout << i << " "; Yes

or we can write it as: PRINT i , “ “


for (int i = 2; i <= 60; i += 2)
cout << i << " ";
ißi+2

Note: The increment is 2 to print only


even numbers.

-Write the odd numbers START

from 31 to -17
k ß 31
for (int k = 31; k >= -17; k = k - 2)
cout << k << " ";
No
Output: k >= -17 END
31 29 27 25 23 21 19 17 15 13 11 9 7 5 3
1 -1 -3 -5 -7 -9 -11 -13 -15 -17 Yes

or PRINT k , “ “

for (int k = 31; k >= -17; k -= 2)


cout << k << " "; kßk-2

Introduction to Algorithms Lecture Notes Version 5. Prepared by Dr. Alaa Al-Obaidi. January 2023
Chapter Six: Loops

95
6.3 Examples

Example 1
Write a complete program to print the numbers from X to Y where X, Y are
integer numbers and Y > X.

#include <iostream> START


using namespace std;
int main() { Read X, Y
int x, y;
cout << "Enter X and Y:";
JßX
cin >> x >> y;
for (int j = x; j <= y; j += 1)
cout << j << " "; No
return 0; J <= Y END
}

Input: Enter X and Y: 3 9 Yes


Output: 3 4 5 6 7 8 9 PRINT J , “ “

JßJ+1

Questions:
1- Print the odd numbers from -20 to 20 in different ways.
2- Print the letters from ‘A’ to ‘Z’ using a loop.
3- Print the following sequence, in addition, calculate their summation:
-7 -4 -1 2 5 8 11 14 17 20 23

Introduction to Algorithms Lecture Notes Version 5. Prepared by Dr. Alaa Al-Obaidi. January 2023
Chapter Six: Loops

96
Example 2
START
-Write a complete program that prints the
maximum number among n numbers. Read n, num

#include <iostream> max ß num


using namespace std; jß2
int main() {
int n, num, max; No
J <= n
cout << "Number of numbers: ";
Yes
cin >> n;
Read num
cout << "Enter a number: ";
cin >> num;
No
max = num; num > max
for (int j = 2; j <= n; j += 1) {
Yes
cout << "Enter a number: ";
cin >> num; max ß num
if (num > max)
max = num;
}// end of loop
cout << "\nMaximum is: " << max<<’\n’;
jßj+1
return 0;
} Print max

END

-Now, suppose n is 6 (that is you will enter six numbers). First num you enter it is
outside the loop and is assigned to max, therefore, we have max ß num.
suppose num is 555, then
num max
555 555

- The loop starts with 2 since first number 555 has been read and it has the sequence 1.
Entering the loop with
num max j
555 555 2

Introduction to Algorithms Lecture Notes Version 5. Prepared by Dr. Alaa Al-Obaidi. January 2023
Chapter Six: Loops

97

j (j<= 6) num (num > max) max START


2 true 44 false 555
Read n, num

j (j<= 6) num (num > max) max max ß num


3 true 600 true 600 jß2

No
j (j<= 6) num (num > max) max J <= n
4 true 100 false 600 Yes
Read num
j (j<= 6) num (num > max) max
5 true 701 true 701 num > max
No

Yes
j (j<= 6) num (num > max) max
max ß num
6 true -90 false 701

j (j<= 6)
7 false
jßj+1

Output: 701 Print max

END

Questions:
1- Solve the same previous example but for finding the minimum number.
2- Solve the same previous example but for finding the maximum and the
minimum numbers.
3- Calculate and print the areas of n circles.

Introduction to Algorithms Lecture Notes Version 5. Prepared by Dr. Alaa Al-Obaidi. January 2023
Chapter Six: Loops

98
6.4 Nested for Loops

-The for loop can be nested. The statement that is going to be repeated is another
for loop statement.
for (initialization; condition; increment/decrement)
for (initialization; condition; increment/decrement)
statement;

The other form

for (initialization; condition; increment/decrement)


for (initialization; condition; increment/decrement) {
Block of Statements;
…………………….
}
START
Example 3
#include <iostream> row ß 1

using namespace std;


int main() { No
row <= 5 END
int row, col;
for (row = 1; row <= 5; row++) {
Yes
for (col = 1; col <= 5; col++) col ß 1

cout << "* "; // repeated row * col times


cout << '\n'; // repeated row times No
} // row col <= 5

return 0; Yes

}
PRINT “* “

col ß col + 1

The above program


prints 5 by 5 stars
PRINT newline

row ß row + 1

Introduction to Algorithms Lecture Notes Version 5. Prepared by Dr. Alaa Al-Obaidi. January 2023
Chapter Six: Loops

99

Example 4
#include <iostream>
using namespace std;
int main() {
int row, col;
for (row = 1; row <= 5; row++) {
for (col = 1; col <= row; col++)
cout << "* "; // repeated row * col times
cout << '\n'; // repeated row times
} // row
return 0;
}

The above program


prints a triangle of
stars

Introduction to Algorithms Lecture Notes Version 5. Prepared by Dr. Alaa Al-Obaidi. January 2023
Chapter Six: Loops

100

Example 5
#include <iostream>
using namespace std;
int main() {
int i, j, k;
cout << 'i' << '\t' << 'j' << '\t' << 'k' << '\n';
for (i = 1; i <= 4; i++)
for (j = 1; j <= 3; j++)
for (k = 1; k <= 2; k++)
cout << i << '\t' << j << '\t' << k << '\n';
return 0;
}

The above program is an


example of three nested for
loops: 4 by 3 by 2

Introduction to Algorithms Lecture Notes Version 5. Prepared by Dr. Alaa Al-Obaidi. January 2023
Chapter Six: Loops

101
6.5 The while Loop
-The while loop is similar to the for loop but here the programmer has the
responsibility to write the initialization, condition, and the increment/decrement
in the right places.

-The condition (expression) specified inside the parentheses is evaluated. If the


result of the expression evaluation is true. The program statement that
immediately follows is executed. After execution of this statement (or
statements, if enclosed in braces), expression is again evaluated. If the result of
the evaluation is true, the program statement is again executed. This process
continues until expression finally evaluates false, at which point the loop is
terminated. Execution of the program then continues with the statement that
follows program statement. The condition may be any expression, and true is any
nonzero value.
START START
….
int i;
initialization iß1
i = 1;
while ( i <= 10) { No No
condition END i <= 10 END
cout << “* “;
i = i + 1;
Yes Yes
}
PRINT i , “ “ PRINT i , “ “

increment ißi+1

Introduction to Algorithms Lecture Notes Version 5. Prepared by Dr. Alaa Al-Obaidi. January 2023
Chapter Six: Loops

102
Example 6: Write part of a program to calculate and print the summation and
average of n numbers (use while).
int n, i;
double num, sum, ave;
cout << "Enter n: ";
cin >> n;
i = 1;
sum = 0;
while (i <= n){
cout << "\nNew Number: ";
cin >> num;
sum += num; // sum = sum + num
i = i + 1;
} // while
ave = sum / double (n);
cout << "\n\nsum = " << sum << "\nave = " << ave;

Example 7: Write part of a program that reads a positive integer number. The program
prints all the numbers that divide the original number with no remainder (use while).

int i, n;
cout << " Enter an integer number n: ";
cin >> n;
i = 1;
while (i <= (n / 2)) {
if (n % i == 0)
cout << i << " ";
i++; // i = i + 1
}

Introduction to Algorithms Lecture Notes Version 5. Prepared by Dr. Alaa Al-Obaidi. January 2023
Chapter Six: Loops

103
6.6 Nested while
The while loop can also be nested, that is, the statement that is effected by the
while loop is another while loop.

Example 8: Write a program to calculate and print the multiplication table (1×1 to
3× 3). (use while).

int i,j;
i = 1;
while (i <= 3){
j = 1;
while (j <= 3) {
cout << i * j << '\t';
j += 1;
} // while j
i += 1;
cout << '\n';
}//while i

Question:
Resolve the program using only two for
statements, then one for statement and
one while statement.

6.7 do while loop


-A do-while loop is the same as a while loop except that it executes the loop body
first and then checks the loop continuation condition. That is, in do-while, loop
body gets executed once whatever may be the condition but condition must be
true if you need to execute body for a second time.

Introduction to Algorithms Lecture Notes Version 5. Prepared by Dr. Alaa Al-Obaidi. January 2023
Chapter Six: Loops

104

START

initialization

Repeated
Statement(s)

Yes
condition

No

END

Introduction to Algorithms Lecture Notes Version 5. Prepared by Dr. Alaa Al-Obaidi. January 2023
Chapter Six: Loops

105
Example 9
Write a program to print the following series: 7 9 11 13 15 17 ………101
besides to calculate and print the summation.

START
#include <iostream>
using namespace std; i ß 7
int main() { Sum ß 0

int i, sum = 0;
i = 7; PRINT i

do {
cout << i << `\t`; sum ß sum + i

sum = sum + i;
i += 2; // i=i+2 i ß i + 2

}
while (i <= 101); Yes
cout << "\n Sum = " << sum<< '\n'; i <= 101
return 0;
} No

PRINT sum

END

Introduction to Algorithms Lecture Notes Version 5. Prepared by Dr. Alaa Al-Obaidi. January 2023
Chapter Six: Loops

106
Example 10
Write a program to calculate the minimum number among five numbers you read
them (use do while).
START

#include <iostream> Read First


using namespace std; Number num

int main() { min ß num


K ß 1
int k;
double num, min; Read Next
Number num
k = 1;
cout << "First number: "; k ß k + 1
cin >> num;
min = num;
No
do { num < min

cout << "Next number: ";


Yes
cin >> num;
min ß num
k = k + 1; // k++
if (num < min)
min = num;
} while (k != 5); Yes
cout << "\n Minimum = " << min << '\n'; K != 5

return 0;
No
}
PRINT min

END

Introduction to Algorithms Lecture Notes Version 5. Prepared by Dr. Alaa Al-Obaidi. January 2023
Chapter Six: Loops

107

-Tracing the Previous Example

#include <iostream>
using namespace std;
int main() {
int k;
double num, min;
k = 1;
cout << "First number: ";
cin >> num;
min = num;
do {
cout << "Next number: ";
cin >> num;
k = k + 1; // k++
if (num < min)
Note that the condition
min = num;
(k != 5)
} while (k != 5);
can be rewritten as
cout << "\n Minimum = " << min <<‘\n’;
(k < 5) or it can be (k <= 4)
return 0;
}

Example 11
Nested do while: Write a program to calculate and print the multiplication table
(1×1 to 5×6). (use do while)

Introduction to Algorithms Lecture Notes Version 5. Prepared by Dr. Alaa Al-Obaidi. January 2023
Chapter Six: Loops

108
START
#include <iostream>
using namespace std; iß1
int main() {
int i, j; jß1

i = 1; //row counter
do { PRINT i * j

j = 1; //col counter
jßj+1
do {
cout << i * j << '\t';
Yes
j++; // incr th col j <= 6
} while (j <= 6);
No
cout << '\n';
i++; // incr the row ißi+1

} while (i <= 5);


PRINT newline
return 0;
}
Yes No
i <= 5 END

Introduction to Algorithms Lecture Notes Version 5. Prepared by Dr. Alaa Al-Obaidi. January 2023
Chapter Six: Loops

109
6.8 A Comparison between the Loops
-Example: Print the numbers from 1 to 5

for loop while loop do while loop


int i; int i; int i;
for (i = 1; i <= 5; i++) i = 1; i = 1;
cout << i << " "; while (i <= 5) { do {
cout << i << " "; cout << i << " ";
i++; i++;
} } while (i <= 5);
while loop do while loop
int i; int i;
i = 0; i = 0;
while (i != 5) { do {
i++; i++;
cout << i << " "; cout << i << " ";
} } while (i != 5);
Example 12: Print the sequence: -25 -20 -15 -10 -5 0 5 10 15 20 25

for loop while loop do while loop


int i; int i; int i;
for (i = -25; i <= 25; i+=5) i = -25; i = -25;
cout << i << " "; while (i <= 25) { do {
cout << i << " "; cout << i << " ";
i+=5; i = i + 5;
} } while (i <= 25);
while loop do while loop
int i; int i;
i = -30; i = -30;
while (i != 25) { do {
i = i + 5; i = i + 5;
cout << i << " "; cout << i << " ";
} } while (i != 25);

Introduction to Algorithms Lecture Notes Version 5. Prepared by Dr. Alaa Al-Obaidi. January 2023

You might also like