Sie sind auf Seite 1von 13

CSC128

Mahfudzah Othman
UiTM Perlis

CHAPTER 4
REPETITION (LOOPING)

 The real powers of computers are in their ability to repeat an operation or a


series of operations many times. This repetition, called looping, is one of the
basic structured programming concepts.

The concept of a loop:


An action or series a++ // a=a+1
of actions

 In the above flowchart, the action is repeated over & over again. It never
stops.
 To write a meaningful program, however we must be able to make a loop and
stop when the work is done.
 To make sure that the loop ends, we must have a condition that controls it.
 In other words, the loop must be designed so that before or after each
iteration, it checks to see if it is done. If it is not done, it repeats one more
time. If it is done, it exits the loop.

WHERE SHOULD THE TEST BE PLACED?BEFORE OR AFTER EACH


ITERATION?

 In many programming languages, they provide 2 types of tests:


o Pre-test loop
o Post-test loop

Pre-test loop
 In each iteration, the loop expression is tested first. If it is TRUE, the loop
action(s) are executed. If it is FALSE, the loop is terminated.

Post-test loop
 In each iteration, the loop action(s) are executed. Next, the loop control
expression is tested. If it is TRUE, a new iteration is started, otherwise the
loop terminates.

1
CSC128
Mahfudzah Othman
UiTM Perlis

CONDITION F
An action or series
of actions
T

An action or series
of actions T CONDITION

PRE-TEST LOOP POST-TEST LOOP

RULES FOR LOOP:

1. Should have loop control variable.


2. Must assign an initial value to loop control variable.
3. Should have a loop control condition.
4. A loop control variable either increases (increment) or decreases (decrement)
its value.

Example:

void main()
{
int x = 1;
int counter; //1) loop control variable
counter = 1; //2) assign an initial value to loop control variable

while (counter<=10) //3)loop control condition


{
x = x * 2;
cout<< x;
counter++; //4)loop control variable increases/decreases
}
}

2
CSC128
Mahfudzah Othman
UiTM Perlis
LOOP STATEMENTS

WHILE FOR DO-WHILE

WHILE LOOP

 It is a pretest loop. It uses an expression to control the loop.


 It tests the expression BEFORE every iteration of the loop.
 Syntax:
Single statement: while (expression)
Statement;
Multiple statement: while (expression)
{
statement;
statement;
:
}

 No semicolon is required at the end of the while statement. The loop body is
a single statement, that is the body of the loop must be one, and only one
statement.
 If we want to include statements in the body, we must put them in a
compound statement.
 While statement can also be used to display the SUM & AVERAGE of certain
items. For example, we would like to calculate the sum & average of 5 marks
that are entered by user.
Example:
void main ()
{ int mark;
int sum = 0;
int count = 0; // control variable & assign an initial value
float average;

while (count<5) // loop control condition


{
cin>>mark;
sum+=mark;
count++; //change the value of control variable
}
average = sum/count;

3
CSC128
Mahfudzah Othman
UiTM Perlis

cout<<”The sum of 5 marks is: ”<<sum<<endl;


cout<<”The average is: ”<<average;
}

 Sometimes, the user will determine how many times the loop body will be
executed.
 Example: The program will calculate the sum of marks that are entered by
user and will only stop when value -1 is keyed in by user.
 In this case, value -1 which will end the execution of a loop is known as
SENTINEL value.
 A sentinel value is NOT part of data to be processed.
 Solution:

void main ()
{ int mark; //loop control variable
int sum = 0;
int count = 0;

cout<<”Enter mark or enter -1 to stop:”;


cin>>mark; //initial a value to loop control variable

while (mark!= -1) //loop control condition


{
sum += mark;
count++;
cout<<”Enter mark or enter -1 to stop:”;
cin>>mark; //change the value of loop control variable
}
cout<<”Sum = ”<<sum;
}

4
CSC128
Mahfudzah Othman
UiTM Perlis

DO-WHILE LOOP

 It is a post-test loop.
 Like while and for loops, it is also use an expression to control the loop, but it
tests this expression after the execution of the body.
 Syntax:
Single statement: do
statement;
while (expression);
Multiple statement: do
{
statement;
statement;
:
} while (expression);

 Note that the do-while ends with a semicolon, making it different in that
respect from the other loops.
 Example: The difference between WHILE & DO-WHILE loop

WHILE DO-WHILE
void main () void main ()
{ int x = 0; { int x = 0;

while (x<10) do
{ {
cout<<x++; cout<<x++;
} } while (x<10);
} }

 Like the while loop, do-while loop can also be used to display sum and
average of marks that are keyed in by users.
 Example: Write a program using the DO-WHILE loop that will calculate the
sum and average of 5 marks entered by user.
 Solution:
void main()
{
int mark;
int count=0; //loop control variable & initial a value to loop control variable
int sum=0;
float average;

5
CSC128
Mahfudzah Othman
UiTM Perlis

do
{
cout<<"Enter 5 marks:";
cin>>mark;
sum+=mark;
count++;//change the value of loop control variable
} while(count<5); //loop control condition

average=sum/count;
cout<<"Sum="<<sum<<endl;
cout<<"Average="<<average;
}
 Do-While loop also can be used with sentinel value that will control the loop to
end.
 Example: Write a program using the DO-WHILE loop that will calculate the
sum and average of marks entered by user.
 Solution:
void main()
{
int mark; //loop control variable
int count=0;
int sum=0;
float average;

cout<<"Enter mark or -1 to stop:";


cin>>mark; //initial a value to loop control variable

do
{
sum+=mark;
count++;
cout<<"Enter mark or -1 to stop:";
cin>>mark; //change the value of loop control variable

} while(mark!=-1); //loop control condition

average=sum/count;
cout<<"Sum="<<sum<<endl;
cout<<"Average="<<average;
}
 There are times when a post-test environment is used where the compound
statement has to be executed at least once before the logical expression is
tested.
 A menu-driven program uses this environment. Since it will be executed at
least once, the initial value of control variable is not required.

6
CSC128
Mahfudzah Othman
UiTM Perlis

 Example: This is a program that will ask the user to choose between A, B or
C that will calculate either A: area of a triangle, B: area of a circle, C:
terminates the program. Used do-while loop and switch statement to execute
this program.
 Solution:
void main()
{
char choice;
float tri, circle, height, base, radian;
const float pie=3.142;

do
{
cout<<"A:Area of a triangle"<<endl;
cout<<"B:Area of a circle"<<endl;
cout<<"C:Terminates the program"<<endl;
cout<<"Enter your choice:"<<endl;
cin>>choice;//loop control variable

switch(choice)
{
case 'A':cout<<"Enter height & base:"<<endl;
cin>>height>>base;
tri=0.5*height*base;
cout<<"Area of a triangle:"<<tri<<endl;
break;
case 'B':cout<<"Enter the radian of a circle:"<<endl;
cin>>radian;
circle=pie*pow(radian,2);
cout<<"Area of a circle:"<<circle<<endl;
break;
case 'C':cout<<"Invalid code.Program will terminates.";
}
} while(choice!='C');//loop control condition
}

7
CSC128
Mahfudzah Othman
UiTM Perlis

FOR LOOP

 The for statement is a pretest loop that uses 3 expressions.


 Initialization statement (expression 1)
 Initialization expression (expression 2)
 Updating expression (expression 3)

EXPR 1
EXPR 1 F
EXPR 3
EXPR 2
F
T EXPR 2

STATEMENT T

STATEMENT

EXPR 3

 Syntax:
Single statement: for (expr1; expr2; expr3)
statement;
Multiple statement: for (expr1; expr2; expr3)
{
statement;
statement;
:
}

Example: The difference between WHILE & FOR loop

8
CSC128
Mahfudzah Othman
UiTM Perlis

WHILE

Void main ()
{ int x = 0;
int count ; // 1)loop control variable
count = 0; //2)initial a value to loop control variable

while (count<5) // 3)loop control condition


{
cout<<x<<”\t”;
x = x + 1;
count++; // 4)control variable increases/decreases
}
}

FOR

Void main ()
{ int x = 0;
int count; // 1)loop control variable

for (count=0; count<5; count++)//2)initial a value, 3)loop control


condition,4)control variable
increases/decreases
{
cout<<x<<”\t”;
x = x + 1;
}
}

 A for loop is used when your loop to be executed is a known number of


times.
 You can do the same thing with a while loop but the for loop is easier to read
& more natural for counting loop.
 Example:

WHILE FOR
void main () void main ()
{ int x = 1; { int x, limit;
int limit;
while (x<10) for (x = 1; x<10; x++)
{ cout<<”Enter a limit:”: { cout<<”Enter a limit:”:
cin>>limit; cin>>limit;
cout<<”x = ”<<x<<endl; cout<<”x = ”<<x<<endl;
cout<<x++; cout<<x++;
} }
} }

9
CSC128
Mahfudzah Othman
UiTM Perlis

 Example: The program will calculate the sum of 5 marks that are entered by
user.
 Solution:

void main()
{
int mark;
int count;//loop control variable
int sum=0;
float average;

for(count=0;count<5;count++)//initial a value to loop control variable, loop


control condition & control variable increases
{
cout<<"Enter mark:";
cin>>mark;
sum+=mark;
}
average=sum/count;

cout<<"Sum="<<sum<<endl;
cout<<"Average="<<average;
}

Flag-Controlled WHILE Loop

A flag is a boolean variable (only can be set to true or false). If a flag is used in a
while loop to control the loop execution, then the while loop is referred to as a
flag-controlled while loop. Hence, the end-of-file-controlled while loop is a special
case of a flag-controlled while loop.

The following is a flag-controlled while loop code segment.

int sum; // the sum of the numbers read


bool done; // used to control the while loop
int number; // the number read
sum = 0; // initialize the sum
done = false; // initialize the boolean variable done
while ( !done ) // loop while not done
{
cin >> number; // read next number
if ( number > 0 ) // sum number if positive
sum = sum + number; // sum the number
else
done = true; } // terminate the loop

10
CSC128
Mahfudzah Othman
UiTM Perlis

The loop logical expression ( !done ) indicates the loop should be executed as
long as done is false.

Exercise
Modify the code given in Example 4 above to sum up nonzero input data items
(integers) and display the results. Place your answer on the answer sheet.

Exercise
Given the following code fragment, what is the value of the variable done after
the while loop exits if user enters -1?

a. false
sum = 0; b. true
done = false; c. the same value as number
while (!done) d. the same value as sum
{ e. an arbitrary value
cin >> number;
if(number < 0)
done = true;
else
sum = sum + number;
}

11
CSC128
Mahfudzah Othman
UiTM Perlis

NESTED LOOP

 A loop (inner) as one of the statements in the body of another loop (outer)
 Syntax:
while (condition 1)
while (condition 2)
Loop body 2;
loop body 1;
OR
for (expr1; expr2; expr3)
{
for (expr1; expr2; expr3)
{
statement 1;

}
statement 2;
}

 Example: Write a program that will produce the following output:

***
***
***
***

 Solution:
void main()
{
int row;
int column;

for(row=1;row<=4;row++)
{ for(column=1;column<=3;column++)
{cout<<"*";}
cout<<endl;
}
}

12
CSC128
Mahfudzah Othman
UiTM Perlis

 Example: What will be the output for the following program?

#include<iostream.h>
#include<conio.h>

void main()
{
int x;
int y;

for(x=1; x<=5; x++)


{
for(y=50; y>=10; y-=10)
cout<<x*y<<"\t";
cout<<endl;
}
getch();
}

 Solution:

50 40 30 20 10
100 80 60 40 20
150 120 90 60 30
200 160 120 80 40
250 200 150 100 50

 What will happened if the program has been changed as follows:

#include<iostream.h>
#include<conio.h>

void main()
{ int x=1;
int y;

while(x<=5)
{ for(y=50; y>=10; y-=10)
cout<<x*y<<"\t";
cout<<endl;
x++;}
getch();}

 It will produce the same output.

13

Das könnte Ihnen auch gefallen