Professional Documents
Culture Documents
Lecture 5 Control Structures - Repetitive Statements Loops II 28102022 113205am
Lecture 5 Control Structures - Repetitive Statements Loops II 28102022 113205am
LECTURE
Abrar Ahmed
abrarahmed.buic@bahria.edu.pk
Outline
• while Loop
• do-while Loop
1
10/27/2022
Control Structures
• All programs can be written in terms of 3 control structures
1. Sequence Structure
2. Selection Structure
• If (Single Selection Statement)
• If-else (Double Selection Statement)
• Switch (Multiple Selection Statement)
3. Repetition Structure
• For
• While
• Do-while
while Loop
2
10/27/2022
while Loop
• The while statement, like if statement, test a condition.
• The syntax of while loop is
while ( expression )
{
statement 1;
statement 2;
}
While Loops
• The while loop evaluates the test expression.
• If the test expression is true, code inside the body of while
loop is evaluated.
• Then, the test expression is evaluated again. This process
goes on until the test expression is false.
• When the test expression is false, while loop is terminated.
• Pretest loop:
• Incase the expression is false the body of the loop is not
executed resulting in a situation where the loop is never once
executed.
3
10/27/2022
void main ( )
{
int i = 0;
while ( i <10 )
{
cout<<i<<endl;
i++;
}
}
4
10/27/2022
Tips
• The statement within the while loop would keep on getting executed till the condition being tested remains
true. When the condition becomes false, the control passes to the first statement that follows the body of
the while loop.
• The condition being tested may use relational or logical operators as shown in the
following example.
• while ( i <= 10 )
• while ( i <= 10 && j <= 15 )
• while ( j > 10 && ( b < 15 || c < 20))
• It is not necessary that a loop counter must be an int. It can even be a float.
int main ()
{
double a=10.0;
while ( a <= 10.5 )
{
cout<<a<<endl;
a = a + 0.1;
} Output:
10
return 0; 10.1
} 10.2
10.3
10.4
10.5
CSC 113 – Computer Programming
Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 10
10
5
10/27/2022
11
• Example
int main()
{
int loop = 0; int main()
while (loop < 10) {
{ = for (int loop = 0; loop < 10; loop++)
cout << loop << endl; cout << loop << endl;
loop++; }
}
}
12
6
10/27/2022
int number = 0;
while (number <= 1000)
number++;
true
number <= 1000 number++;
false
13
14
7
10/27/2022
15
int main()
{
int counter = 1;
int n = 4;
while (counter <= n)
{
cout << counter << endl;
counter = counter + 1;
}
return 0;
}
16
8
10/27/2022
Fibonacci Series
17
Fibonacci Series
int limit;
cout << "Enter a positive integer for Fibonacci Series limit : ";
cin >> limit;
int first = 0;
int second = 1;
cout << first << ", " << second;
int temp = first + second;
18
9
10/27/2022
19
int counter = 1;
int j = 0;
int n = 3;
while (counter <= n)
{
j = j + 1;
cout << counter << endl;
}
cout << "Do we ever get here?" << endl;
20
10
10/27/2022
int Count = 1;
while(Count > 0)
{
………..
cout << “Enter your answer” << endl;
cin >> Ans;
Count++;
………
}
21
Infinite Loops
• How do you terminate a program containing an infinite loop?
• X, Cntrl-C,
• Cntrl-Alt-Del and terminate task.
22
11
10/27/2022
Types of while-loop
• Counter controlled loops
• when the programmer knows the number of iterations required
while(x<5)
{
}
• Sentinel controlled loops
• when the programmer lets an EVENT control the number of repetitions
While(x!=-1)
{
}
23
24
12
10/27/2022
• 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.
25
Counter-Controlled Repetition
• Pseudocode for example:
26
13
10/27/2022
1
2 // Class average program with counter-controlled repetition.
Counter-Controlled 3 #include <iostream.h>
4
Repetition 5 // function main begins program execution
6 int main()
7 {
8 int total; // sum of grades input by user
9 int gradeCounter; // number of grade to be entered next
10 int grade; // grade value
11 int average; // average of grades
12
13 // initialization phase
14 total = 0; // initialize total
15 gradeCounter = 1; // initialize loop counter
16
Enter grade: 98
17 while ( gradeCounter <= 10 ) { // loop 10 times
Enter grade: 76
18 cout << "Enter grade: "; // prompt for input
Enter grade: 71
19 cin >> grade; // read grade from user
Enter grade: 87
20 total = total + grade; // add grade to total
Enter grade: 83 21 gradeCounter = gradeCounter + 1; // increment counter
Enter grade: 90 22 }
Enter grade: 57 23
Enter grade: 79 24 average = total / 10; // integer division
Enter grade: 82 25
Enter grade: 94 26 // display result
Class average is 81 27 cout << "Class average is " << average << endl;
28 The counter gets incremented each time
29 the loop executes. Eventually, the
Department of Computer Sciences 30 } // CSC 113 – Computer Programming
counter causes the loop to end.
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 27
27
28
14
10/27/2022
Sentinel-Controlled Repetition
• Suppose problem becomes:
Develop a class-averaging program that will process an arbitrary number of grades each time the program is run
• Unknown number of students
29
Contd…
• Sentinel value
• Indicates “end of data entry”
• Loop ends when sentinel input
• Sentinel chosen so it cannot be confused with regular input
• -1 in this case
30
15
10/27/2022
1
2 // Class average program with sentinel-controlled repetition.
3 #include <iostream.h>
4
5
6 // function main begins program execution
7 int main()
8 {
9 int total; // sum of grades
10 int gradeCounter; // number of grades entered
11 int grade; // grade value
12
13 double average; // number with decimal point for average
14
15 // initializations
16 total = 0; // initialize total
17 gradeCounter = 0; // initialize loop counter
18
19 // get first grade from user
20 cout << "Enter grade, -1 to end: "; // prompt for input
21 cin >> grade; // read grade from user
22
23 // loop until sentinel value read from user
24 while ( grade != -1 ) {
25 total = total + grade; // add grade to total
26 gradeCounter = gradeCounter + 1; // increment counter Enter grade, -1 to end: 75
27 Enter grade, -1 to end: 94
28 cout << "Enter grade, -1 to end: "; // prompt for input Enter grade, -1 to end: 97
29 cin >> grade; // read next grade
30 Enter grade, -1 to end: 88
31 } // end while Enter grade, -1 to end: 70
32
Enter grade, -1 to end: 64
33 // if user entered at least one grade ...
34 if ( gradeCounter != 0 ) { Enter grade, -1 to end: 83
35 Enter grade, -1 to end: 89
36 // calculate average of all grades entered
37 average = (double)( total ) / gradeCounter; Enter grade, -1 to CSC end:113 -1
– Computer Programming
Department of Computer Sciences
Class average
4. Control is 82.50– Repetitive Statements/Loops
Structures
Bahria University, Islamabad
Slide: 31
31
32
16
10/27/2022
int totalInputs = 5;
int total = 0; // sum of grades input by user
int gradeCounter = 1; // number of grade to be entered next
int grade; // grade value
double average; // average of grades
33
int value;
cout << "Enter a positive value : ";
cin >> value; // 5
for (int line = 1; line <= value; line++)// print new lines
{
for (int space = 1; space <= value - line; space++)// print spaces
{
cout << " ";
}
for (int star = 1; star <= line; star++)// print stars
{
cout << "*";
}
cout << endl;
}
34
17
10/27/2022
int value;
cout << "Enter a positive value : ";
cin >> value; // 5
int line = 1;
while ( line <= value)// print new lines
{
int space = 1;
while ( space <= (value - line))// spaces
{
cout << space;
space++;
}// end print spaces loop
int star = 1;
while ( star <= line )// print stars
{
cout << "*";
star++;
}// end print stars loop
cout << endl;
line++;
}// end print lines loop
CSC 113 – Computer Programming
Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 35
35
Exercise 1
• Find the powers of 3 less than 100
void main ( )
{
int product = 3;
while ( product <= 100)
{
cout<<"Product="<<product<<endl;
product = 3 * product;
}
}
36
18
10/27/2022
Exercise 2
• calculates and prints the sum of the integers from 1 to 10
void main ( )
{
int sum = 0, i=1;
while ( i <= 10)
{
sum=sum+i;
i++;
}
cout<<"sum="<<sum<<endl;
}
37
Task to be done
• Print the table of a number entered by the user
38
19
10/27/2022
• Typically, for statements are used for counter-controlled repetition and while statements are used for
sentinel-controlled repetition.
39
do-while Loop
40
20
10/27/2022
41
Do-while loop
• The codes inside the body of loop is executed at least
once. Then, only the test expression is checked.
• If the test expression is true, the body of loop is
executed. This process continues until the test
expression becomes false.
• When the test expression is false, do...while loop is
terminated.
• Syntax:
do
{
statements;
} while(condition);
42
21
10/27/2022
action(s)
true
condition
false
43
1 2 3 4 5 6 7 8 9 10
44
22
10/27/2022
void main()
{
int i=0; // initialize counter
do
{
cout << i<< endl;
i++;
} while ( i < 10 ); // end do/while
45
} while(condition);
46
23
10/27/2022
char Option = ‘’ ;
do
{
cout << "Enter N)ew, O)pen, S)ave: ";
cin >> Option;
47
#include <iostream.h>
#define PI 3.141593
int main(void)
{
int degrees=0;
double radians;
cout<<"Degrees to Radians”;
do
{
radians = degrees*PI/180;
cout<<radians;
degrees += 10;
} while (degrees <= 360);
return 0;
}
48
24
10/27/2022
• 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
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
49
50
25
10/27/2022
1
2 // Using the break statement in a for structure.
3 #include <iostream.h>
4
5 // function main begins program execution
6 void main()
7 {
8
9 int x;
10 // loop 10 times
11 for ( x = 1; x <= 10; x++ ) {
12
13 // if x is 5, terminate loop
14 if ( x == 5 )
15 break; // break loop only if x is 5
16
17 cout << x << " "; // display value of x
18
19 } // end for
20
21 cout << "\nBroke out of loop when x became " << x << endl;
22
23 } // end function main
1234
Broke out of loop when x became 5
CSC 113 – Computer Programming
Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 51
51
52
26
10/27/2022
1
2 // Using the continue statement in a for structure.
3 #include <iostream.h>
4
5 // function main begins program execution
6 void main()
7 {
8 // loop 10 times
9 for ( int x = 1; x <= 10; x++ ) {
10
11 // if x is 5, continue with next iteration of loop
12 if ( x == 5 )
13 continue; // skip remaining code in loop body
14
15 cout << x << " "; // display value of x
16
17 } // end for structure
18
19 cout << "\nUsed continue to skip printing the value 5"
20 << endl;
21
22 } // end function main
53
◦ The initialization part of loop is optional. If this part is omitted, then a semicolon is used in
its place.
◦ for(;a<10;a++)
54
27
10/27/2022
• Increment/decrement
• In this part, the loop variable(s) is incremented or decremented.
• To increment or decrement more than one variable, they are written comma
separated.
• This part is executed after executing loop body.
• This part is also optional. If this part is not used then loop variable must be
incremented/decremented inside loop body.
for(;a<10;)
55
• Example
goto myLabel;
//other program statements
myLabel: //control will shift here and execute the following
//statements
//statements;
56
28
10/27/2022
57
58
29
10/27/2022
Type of Loop
• The number of repetitions is known in advance or read as input, use a counter-controlled for loop
• If you must stop the loop when some event occurs during execution of the loop, use an event-controlled
while loop
• If the loop must always execute once (to validate input), use a do-while loop
59
int j, n;
float x, sum;
while(j <= n)
{
cout << "Enter a number: ";
cin >> x;
sum = sum + j;
j++;
}
60
30
10/27/2022
Examples
61
Examples
// Filename: DoWhile.CPP
// A totaling program using a do-while loop.
#include <iostream.h>
void main()
{
int total = 0; // Initialize total
int num = 5;
do
{
total += num; // Add num to total
num++; // Increment counter
}while (num <= 10);
cout << "The total is " << total << "\n";;
}
63
31
10/27/2022
Examples
// Filename: FOR.CPP
// Demonstrates totaling using a for loop.
#include <iostream.h>
void main()
{
int total, ctr;
total = 0;
for (ctr=5; ctr<=10; ctr++) // ctr is 5, 6, 7, 8, 9, 10
{
total += ctr; // Add value of ctr to each iteration.
}
cout << "The total is " << total << "\n";
}
64
int lowerLimit;
int upperLimit;
int value;
cout << "Enter Lower Limit : "; /* Write a program that takes 2 values from user
cin >> lowerLimit;
as lowerLimit and upperLimit, and prints all
cout << "Enter Upper Limit : ";
cin >> upperLimit; prime numbers between that.
value = lowerLimit; e.g. 200 - 500
*/
while (value <= upperLimit)
{
int sqrtOfValue = sqrt(value) + 1;
bool divided = false; // true/false; 1/0;
for (int loop = 2; loop <= sqrtOfValue; loop++)
{
if (value % loop == 0)
{
divided = true;
break;
}
}
if (!divided)
cout << value << " "
value++;
}
65
32
10/27/2022
char choice;
do {
int lowerLimit;
int upperLimit;
int value;
cout << "Enter Lower Limit : ";
cin >> lowerLimit;
cout << "Enter Upper Limit : ";
cin >> upperLimit;
value = lowerLimit;
while (value <= upperLimit)
{
int sqrtOfValue = sqrt(value) + 1;
bool divided = false; // true/false; 1/0;
for (int loop = 2; loop <= sqrtOfValue; loop++)
{
if (value % loop == 0)
{
divided = true;
break;
}
}
if (!divided)
cout << value << " ";
value++;
}
cout << endl << "Do You Want to continue? (Y|N) : ";
cin >> choice;
66
Tasks to be done
Exercise: Develop a program to print following series.
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9
Exercise: Develop a program to print following series.
1
1 2
1 2 3
1 2 3 4
67
33