0% found this document useful (0 votes)
16 views

Lec 9-10 (Loop)Finish

Uploaded by

CapturedSkull
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)
16 views

Lec 9-10 (Loop)Finish

Uploaded by

CapturedSkull
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/ 35

1

ITERATIVE STATEMENTS

DR. Samar A. Said


First term
2023-2024
POINTS TO BE COVERED:
• Looping
• For
• While
• Do while

• Nested loop

2
LOOP STATEMENTS
• A loop is a program construction that repeats a
statement or sequence of statements a number
of times
• Loop design questions:
• What should the loop body be?
• How many times should the body be iterated?
LOOP STATEMENTS

• C++ programming language provides following types of iterative


(loop) statements.

4
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)

While
#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;
}

7
(COUNTER-CONTROLLED REPETITION)

• Counter-controlled repetition
• Loop repeated until counter reaches a certain value.

• Definite repetition
• Number of repetitions is known

• Example
A class of ten students took a quiz. The grades (integers in the range 0 to
100) for this quiz are available to you. Determine the class average on
the quiz.
(COUNTER-CONTROLLED REPETITION)
• Pseudocode for example:
Set total and grade counter to zero
While grade counter <= 10
input the next grade
add the grade into the total
grade counter++
Average = total divided / 10
Print the class average

• Following is the c++ code for this example


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 time
14 average; // average of grades the loop executes. Eventually, the counter
15
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; Step )
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 Step


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)

For

#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;
}
15
THE FOR AND WHILE REPETITION

• For loops can usually be rewritten as while loops:


Initialization;
While ( loopcontinuationtest){
Statement
Step(Increment or Decrement);
}
• 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 0 to 10
• all actions are performed at least once.
FLOW CHART OF DO/WHILE

statement

true
condition

false
Example on (do-while)

Do-while
#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;

20
WHEN TO CHOOSE A WHILE, FOR, OR
DO-WHILE LOOP

• A while-loop is typically used

• When a for-loop is not appropriate


• A "While" Loop is used to repeat a specific block of code an unknown
number of times, until a condition is met

• 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
• Common uses of the break statement:
• Escape early from a loop
• Skip the remainder of a switch structure
The break Statement

23
THE CONTINUE STATEMENT

• Continue
• In computer programming, the continue
statement is used to skip the current
iteration of the loop and the control of the
program goes to the next iteration.
• 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 the for structure, the increment
expression is executed, then the loop-
continuation test is evaluated
• In while and do/while, the loop-
continuation test is evaluated immediately
after the continue statement is executed
25
.

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)

cin >> a >> b;

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


{
for (int j=0; j < b; j++) *************
{
cout << “*”;
a *************
*************
}
cout << endl; *************
}

32
EXAMPLE 3 :NESTED LOOPS (LOOP IN LOOP)

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; ***
} ****

33
EXAMPLE 2:NESTED LOOPS (LOOP IN LOOP)

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;
} 34

You might also like