Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

10/27/2022

LECTURE

5 Control Structures – Repetitive Statements/Loops


CSC 113
Computer Programming
Fall 2022

Abrar Ahmed
abrarahmed.buic@bahria.edu.pk

Department of Computer Science


Bahria University, Islamabad

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 1

Outline

• while Loop
• do-while Loop

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 2

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

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 3

while Loop

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 4

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

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 5

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.

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 6

3
10/27/2022

while Loop Example


void main ( )
{
int n = 99;
while ( n != 0 )
{
cout<<“Enter any number or 0 to quit the program”;
cin >> n;
}
}

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 7

while Loop Example

void main ( )
{
int i = 0;
while ( i <10 )
{
cout<<i<<endl;
i++;
}
}

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 8

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.

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 9

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

Nested while loop


while(condition)
{
while(condition)
{
statement(s);
}
statement(s); // you can put more statements.
}

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 11

11

The while loop

• Action repeated while some condition remains true


• Psuedocode
while there are more items on the shopping list
Purchase next item and cross it off my list

• 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++; }
}
}

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 12

12

6
10/27/2022

The while loop

int number = 0;
while (number <= 1000)
number++;

true
number <= 1000 number++;

false

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 13

13

The while Loop

When a while loop executes, the loop-test is evaluated.


If true, the iterative part is executed and the loop-test is
reevaluated. This process continues until the loop test
is false. For example, counter <= n must eventually
become false for the following loop to terminate:

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 14

14

7
10/27/2022

The while loop


• for loops can usually be rewritten as while loops
Initialization expression;
while ( Test Expression){
statement
increment expression;
}

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 15

15

The while Loop

int main()
{
int counter = 1;
int n = 4;
while (counter <= n)
{
cout << counter << endl;
counter = counter + 1;
}
return 0;
}

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 16

16

8
10/27/2022

Fibonacci Series

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 17

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;

while (temp <= limit)


{
cout << ", " << temp;
first = second;
second = temp;

temp = first + second;


}

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 18

18

9
10/27/2022

The while Loop


• All Loops have
1. A primer or initial value for the first test
2. A test in the loop that must become false in order to exit the loop.
3. A statement(s) that brings the loop closer to termination or the potential for setting the decision variable to false in
order to terminate the loop.

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 19

19

The Infinite Loop


• An infinite loop is one that never terminates.
• They are usually not desirable––an example:

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;

There is no step that brings us closer to loop termination––it's an infinite loop.

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 20

20

10
10/27/2022

Another Infinite Loop

int Count = 1;
while(Count > 0)
{
………..
cout << “Enter your answer” << endl;
cin >> Ans;
Count++;
………
}

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 21

21

Infinite Loops
• How do you terminate a program containing an infinite loop?
• X, Cntrl-C,
• Cntrl-Alt-Del and terminate task.

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 22

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)
{
}

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 23

23

Requirements for counter-controlled while-loop


• Counter variable initialization before check of condition
• Counter variable is incremented/decremented inside the loop body
int linectr = 0;
while (linectr <= 3)
{
cout << linectr << endl;
linectr = linectr + 1;
}
How many lines of output??

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 24

24

12
10/27/2022

The while loop

• Formulating Algorithms (Counter-Controlled Repetition)


• Loop repeated until counter reaches certain value

• 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.

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 25

25

Counter-Controlled Repetition
• Pseudocode for example:

Set total to zero


Set grade counter to one
While grade counter is less than or equal to ten
Input the next grade
Add the grade into the total
Add one to the grade counter

Set the class average to the total divided by ten


Print the class average

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 26

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

Requirements for sentinel-controlled while-loop


• Sentinel variable initialization before check of condition
• Sentinel variable is modified inside the loop body
int num;
cin >> num;
while (num != -1)
{
cout << num;
cin >> num;
}
How many repetitions of the body??

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 28

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

• How will program know when to end?

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 29

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

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 30

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

Sentinel-Controlled Repetition - Example


#include<iostream>
using namespace std;
int main ()
{
int n;
char choice='y';
while (choice =='y' )
{
cout<<"Enter number: ";
cin>>n;
(n%2)?cout<<"Odd":cout<<"Even";
cout<<"to continue press y...";
cin>>choice;
}
return 0;
}

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 32

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

while (gradeCounter <= totalInputs)


{
//0-100
cout << "Enter grade [0-100] : "; // prompt for input
cin >> grade; // read grade from user

while (grade < 0 || grade>100)


{
cout << "ERROR!! Incorrect Grade Value" << endl;
cout << "Enter grade [0-100] : "; // prompt for input
cin >> grade; // read grade from user
}

total = total + grade; // add grade to total


gradeCounter = gradeCounter + 1; // increment counter
}

average = (double)total / 10; // integer division


// display result
cout << "Class average is " << average << endl;

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 33

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

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 34

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

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 36

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

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 37

37

Task to be done
• Print the table of a number entered by the user

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 38

38

19
10/27/2022

• Typically, for statements are used for counter-controlled repetition and while statements are used for
sentinel-controlled repetition.

• for loops can usually be rewritten as while loops


initialization;
while ( loopContinuationTest){
statement
increment;
}

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 39

39

do-while Loop

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 40

40

20
10/27/2022

do/while Repetition Structure


• Similar to while structure
• Makes loop continuation test at end, not beginning
• Loop body executes at least once
• Format
do
{
statement
} while ( condition );

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 41

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

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 42

42

21
10/27/2022

do/while Repetition Structure

action(s)

true
condition

false

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 43

43

do/while Repetition Structure


1
2 // Using the do/while repetition structure.
3 #include <iostream.h>
4 // function main begins program execution
5 void main()
6 {
7 int counter = 1; // initialize counter
8
9 do {
10 cout << counter << " "; // display counter
11 } while ( ++counter <= 10 ); // end do/while
12
13 cout << endl;
14
15 } // end function main

1 2 3 4 5 6 7 8 9 10

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 44

44

22
10/27/2022

void main()
{
int i=0; // initialize counter

do
{
cout << i<< endl;
i++;
} while ( i < 10 ); // end do/while

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 45

45

Nested do-while loop


do
{
statement(s); // you can put more statements.
do
{
statement(s);
} while(condition);

} while(condition);

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 46

46

23
10/27/2022

do/while Repetition Structure


• The do while loop is a good choice for obtaining interactive input from menu selections.
• Consider a function that will not stop executing until the user enters an N, O, or S:

char Option = ‘’ ;
do
{
cout << "Enter N)ew, O)pen, S)ave: ";
cin >> Option;

} while (Option != 'N' && Option != 'O' &&


Option != 'S');

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 47

47

do/while Repetition Structure

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

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 48

48

24
10/27/2022

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

 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

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 49

49

break and continue Statements


• break statement
• Immediate exit from while, for, do/while, switch
• Program continues with first statement after structure
• Common uses
• Escape early from a loop
• Skip the remainder of switch

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 50

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

break and continue Statements


• continue statement
• Used in while, for, do/while
• Skips remainder of loop body
• Proceeds with next iteration of loop

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 52

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

CSC 113 – Computer Programming


Department of Computer Sciences
1 2 3 4 6 7 8 9 10 4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Used continue to skip printing the value 5 Slide: 53

53

For loop – syntax explained


• Initialization expr
◦ In this part, the loop variable (or variables) is initialized. The variable is already declared. If not
then it may be declared and initialized within this part of loop, e.g.,
◦ for(a=1;a<3;a++)
◦ for(int a=1,b=5;a<10;a++)

◦ The initialization part of loop is optional. If this part is omitted, then a semicolon is used in
its place.

◦ for(;a<10;a++)

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 54

54

27
10/27/2022

For loop – syntax explained


• Condition
• In this part, the test condition is given. The body of the loop is executed only if the test
condition evaluates to true.

• 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;)

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 55

55

Other control statements


• The goto statement
◦ You can insert a label into your program code at the desired location. The label ends with a a
colon.
◦ The keyword goto followed by the label name then takes you to the label.
◦ goto should be avoided as it leaves to spaghetti code that is difficult to debug and understand.

• Example
goto myLabel;
//other program statements
myLabel: //control will shift here and execute the following
//statements
//statements;

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 56

56

28
10/27/2022

Loop Selection and Design


• The following outline is offered to help you choose and design loops in a variety of situations:
• 1. Write the statements to be repeated.
• 2. Determine which type of loop to use.
• 3. Determine the loop-test.
• 4. Bring the loop one step closer to termination.
• 5. Initialize variables as necessary.

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 57

57

Bring the Loop closer to termination


• To avoid an infinite loop, there should be at least one action in the loop body that brings it closer to
termination.
• Examples:
• 1. Increment the counter by +1.
• 2. Extract data from the user e.g., Yes or No.
• 3. Use a decision in the loop to set the loop condition/decision to false.

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 58

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

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 59

59

Initialize the variables as required


• Check to see if any variables used in either the body of the loop or the loop-test need to be initialized.
• Consider this loop:

int j, n;
float x, sum;
while(j <= n)
{
cout << "Enter a number: ";
cin >> x;
sum = sum + j;
j++;
}

Which variables need to be initialized before this while( ) loop is encountered??

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 60

60

30
10/27/2022

Examples

//This is a test for a while


#include<iostream.h>
void main()
{
int counter=1;
float total;
float score;
while (counter <5)
{
cout<<"Enter score: ";
cin>>score;
total=total+score;
counter=counter+1;
}
cout<<"Your total is: "<<total<<endl;
}//close main

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 61

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

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 63

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

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 64

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

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 65

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;

} while (choice=='Y' || choice=='y');

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 66

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

CSC 113 – Computer Programming


Department of Computer Sciences
4. Control Structures – Repetitive Statements/Loops
Bahria University, Islamabad
Slide: 67

67

33

You might also like