0% found this document useful (0 votes)
6 views37 pages

Lec 5 Iteration

The document provides an overview of loop structures in C++, including 'while', 'for', and 'do-while' loops, along with examples and common errors. It discusses the design of loops, the use of nested loops, and control statements like 'break' and 'continue'. Additionally, it outlines when to use different types of loops and presents various programming exercises involving loops.

Uploaded by

ahmedbedawy65
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)
6 views37 pages

Lec 5 Iteration

The document provides an overview of loop structures in C++, including 'while', 'for', and 'do-while' loops, along with examples and common errors. It discusses the design of loops, the use of nested loops, and control statements like 'break' and 'continue'. Additionally, it outlines when to use different types of loops and presents various programming exercises involving loops.

Uploaded by

ahmedbedawy65
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/ 37

1

Iteration

Dr. Hadeer A. Hosny


2 Points to be covered:
 Looping
 For
 While
 Do While
 Nested Loop
Loop Statements

 A loop is a program construction that repeats a


statement or sequence of statements a number
of times
 The body of the loop is the statement(s) repeated
 Each repetition of the loop is an iteration
 Loop design questions:
 What should the loop body be?
 How many times should the body be iterated?
Loop Statements
4

 C++ programming language provides following types of


Iterative (Loop) statements.
The while Repetition Structure

 Repetition structure
 Programmer specifies an action to be repeated while some
condition remains true
 while loop repeated until condition becomes false.
 Example
int product = 2;
while ( product <= 1000 )
product = 2 * product;

 Common errors:
 infinite loop
 unitialized variables
The while Repetition Structure

 Flowchart of while loop

true
condition statement

false

int x = 2;
while (x >= 0){
if ( x == 2){
cout << “Value of x is : “ << x << endl;
}
x = x – 1;
}
Example on (While)
7

#include <iostream>
using namespace std;

int main () {
// Local variable declaration:
int a = 10;

// while loop execution


while( a < 20 ) {
cout << "value of a: " << a << endl;
a++;
}

return 0;
}
1 // Fig. 2.7: fig02_07.cpp
2 // Class average program with counter-controlled repetition
3 #include <iostream>
4
5 using namespace std;
6
7
8
9 int main()
10 {
11 int total, // sum of grades
12 gradeCounter, // number of grades entered
13 grade, // one grade The counter gets incremented each
14 average; // average of grades time the loop executes. Eventually,
15
the counter causes the loop to end.
16 // initialization phase
17 total = 0; // clear total
18 gradeCounter = 1; // prepare to loop
19
20 // processing phase
21 while ( gradeCounter <= 10 ) { // loop 10 times
22 cout << "Enter grade: "; // prompt for input
23 cin >> grade; // input grade Enter grade: 98
Enter grade: 76
24 total = total + grade; // add grade to total
Enter grade: 71
25 gradeCounter = gradeCounter + 1; // increment counter
Enter grade: 87
26 } Enter grade: 83
27 Enter grade: 90
28 // termination phase Enter grade: 57
29 average = total / 10; Enter
// integer division grade: 79
30 cout << "Class average is " << average << endl; Enter grade: 82
31 Enter grade: 94
Class average is 81
32 return 0; // indicate program ended successfully
33 }
Ask Before Iterating

 A while loop is used here to implement the ask


before iterating method to end a loop

sum = 0;
cout << "Are there numbers in the list (Y/N)?";
char ans;
cin >> ans;
while (( ans == 'Y') || (ans == 'y'))
{
//statements to read and process the number
cout << "Are there more numbers(Y/N)? ";
cin >> ans;
}
The for Repetition Structure

 The general format when using for loops is


for(initialization; LoopContinuationTest; increment )
statement

 Example:
for( int counter = 1; counter <= 10; counter++ )
cout << counter << endl;

 Prints the integers from one to ten


Flowchart for for

Initialize variable

Condition true statement


Test the variable Increment variable

false
Extra Semicolon

 Placing a semicolon after the parentheses of a for loop


creates an empty statement as the
body of the loop
 Example: for(int count = 1; count <= 10; count++);
cout << "Hello\n";

prints one "Hello", but not as part of the loop!


 The empty statement is the body of the loop
cout << "Hello\n"; is not part of the loop body!
Example on (for)
13

#include <iostream>
using namespace std;

int main () {
// for loop execution
for( int a = 10; a < 20; a = a + 1 ) {
cout << "value of a: " << a << endl;
}

return 0;
}
The for and while Repetition

 For loops can usually be rewritten as while loops:


initialization;
while ( loopContinuationTest){
statement
increment;
}
 Initialization and increment as comma-separated lists
for (int i = 0, j = 0; j + i <= 10; j++, i++)
cout << j + i << endl;
• Program to sum the even numbers from 2 to 100
1 // Fig. 2.20: fig02_20.cpp
2 // Summation with for
3 #include <iostream>
4
5 using namespace std;
:cout;
6
7
8 int main()
9 {
10 int sum = 0;
11
12 for ( int number = 2; number <= 100; number += 2 )
13 sum += number;
14
15 cout << "Sum is " << sum << endl;
16
17 return 0;
18 }

Sum is 2550
The do/while Repetition Structure
 The do/while repetition structure is similar to the while
structure,
 Condition for repetition tested after the body of the loop is
executed
 Format:
do {
statement
} while ( condition );
 Example:
int counter=0;
do {
cout << counter << " ";
counter++;
} while (counter <= 10);
 This prints the integers from 1 to 10
 All actions are performed at least once.
Flow chart of do/while

statement

true
condition

false
Example on (do-while)
18

#include <iostream>
using namespace std;

int main () {
// Local variable declaration:
int a = 10;

// do loop execution
do {
cout << "value of a: " << a << endl;
a = a + 1;
} while( a < 20 );

return 0;
When to choose a while, for, or
do-while loop

 A while-loop is typically used

 When a for-loop is not appropriate


 When there are circumstances for which the loop body should not be
executed at all

 A do-while-loop is typically used

 When a for-loop is not appropriate


 When the loop body must be executed at least once
The break and continue Statements

 Break
 Causes immediate exit from a while, for, do/while or switch
structure
 Program execution continues with the first statement after the
structure
 Common uses of the break statement:
 Escape early from a loop
 Skip the remainder of a switch structure
21 The break Statement
The continue Statement

 Continue
 Skips the remaining statements in the body of a while, for or
do/while structure and proceeds with the next iteration of the
loop
 In while and do/while, the loop-continuation test is
evaluated immediately after the continue statement is
executed
 In the for structure, the increment expression is executed,
then the loop-continuation test is evaluated
The continue Statement

int next = 0;
while (true){
cin >> next;
if (next < 0)
break;
if (next % 2==0)
continue;
cout << next << endl;
}
cout << “negative num so here we are!” << endl;
.

Nested loops
Nested Loops

 A loop can be nested inside of another loop.

 C++ allows at least 256 levels of nesting

 When working with nested loops, the outer loop changes


only after the inner loop is completely finished
The syntax for a nested for
loop statement in C++

for ( init; condition; increment )


{
for ( init; condition; increment )
{
statement(s);
}
statement(s); // you can put more statements.
}
The syntax for a nested while
loop statement in C++

while(condition)
{
while(condition)
{
statement(s);
}
statement(s); // you can put more statements.
}
The syntax for a nested do...while
loop statement in C++
do {

statement(s); // you can put more statements.


do {
statement(s);
} while( condition );
} while( condition );
For loop nesting
Example 1:Nested loops (loop in loop)
30

cin >> a >> b;

for (int i = 0; i < a; i++) b


{
for (int j=0; j < b; j++) *************
{
a *************
cout << "*"; *************
}
*************
cout << endl;
}
Example 2:Nested loops (loop in loop)
31

int a,b;

cin >> a >> b; b

for (int i = 0; i < a; i++) *


{ a **
for (int j=0; j<b; j++) ***
{ ****
if (j > i)
break;
cout << "*";
}
cout << endl;
}
Example 3 :Nested loops (loop in loop)
32

int a,b;
if (j > i) break;
cin >> a >> b;

for (int i = 0; i < a; i++)


{ for (int j=0; j<b && j <
<=i;
i; j++)
b
{ *
cout << "*";
} a **
cout << endl;
***
} ****
Example 4 :Nested loops (loop in loop)
33

int a,b;

cin >> a >> b;

for (int i = 0; i < a; i++) b


{
for (int j=0; j<b; j++) *************
{
if (j < i) a ************
***********
cout << " ";
else
**********
cout << "*";
}
cout << endl;
}
.

Try to write a program in C++ that prints a tables Starting from 1 12.

1 2 3 4 5 6 7 8 9 10 11 12
2 4 6 8 10 12 14 16 18 20 22 24
3 6 9 12 15 18 21 24 27 30 33 36
4 8 12 16 20 24 28 32 36 40 44 48
5 10 15 20 25 30 35 40 45 50 55 60
6 12 18 24 30 36 42 48 54 60 66 72
7 14 21 28 35 42 49 56 63 70 77 84
8 16 24 32 40 48 56 64 72 80 88 96
9 18 27 36 45 54 63 72 81 90 99 108
10 20 30 40 50 60 70 80 90 100 110 120
11 22 33 44 55 66 77 88 99 110 121 132
12 24 36 48 60 72 84 96 108 120 132 144
.

Try to develop a code in C++ that generate the following series . Use
nested loop!

Series

No. 1 No. 2 No. 3

1 1 1
12 22 23
123 333 456
1234 4444 7 8 9 10
36
Outline of course
 Contents going to be covered during course:
 Problem Solving
 Flow chart, pseudo code, and Algorithm
 Starting write first C++ program
 Input and Output
 Conditions
 Loops
 Array
 Function
 Pointers
 String
 Classes and Objects
37

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy