DKT121 05 - Loop

Download Report

Transcript DKT121 05 - Loop

Loops
UniMAP DKT121 Sem 2
2010/2011
Outline


Introduction
While loops




Three types of while loops
Do-while loops
For loops
Nested loops
UniMAP DKT121 Sem 2
2010/2011
Why Need Loops ?


Suppose we want to add five numbers and
find the average.
From what you have learned so far, you could
proceed as follows
scanf(“%d %d %d %d %d”, &num1, &num2,
&num3, &num4, &num5);
sum = num1 + num2 + num3 + num4 + num5;
average = sum / 5;

If 100 numbers, 1000 numbers?
UniMAP DKT121 Sem 2
2010/2011
Repetition (Loop)



Used to control the flow of a program
Loops are basically repetitions or iterations used to
repeat a segment of code
Three statements can be used to implement loops in
C





while statement
do-while statement
for statement
while and for statements are similar in
implementation, but have different syntax
The do-while statement is different - the following
code is executed at least once
UniMAP DKT121 Sem 2
2010/2011
The while loop structure

The general form of the while statement is:
while (expression)
statement;


To avoid an infinite loop, make sure that
the loop’s body contains statement (s) that
assure that the exit condition i.e. the
expression in the while statement will
eventually be false.
while loop repeated until condition becomes
false
UniMAP DKT121 Sem 2
2010/2011
Flowchart of a while statement
UniMAP DKT121 Sem 2
2010/2011
The while loop structure-cont

There are basically three types of while
loops:



Counter-controlled while loop
Sentinel-controlled while loop
Flag-controlled while loop
UniMAP DKT121 Sem 2
2010/2011
Counter-Controlled while
Loops


Definite repetition: know how many times loop will execute
Control variable used to count repetitions
Example:
int counter = 1;
// declare and initialize
while ( counter <= 10 ) // test condition
{
printf( "%d\n", counter );
++counter;
// update
}
Requirement:
1. Declare and initialize
control variable value (or
loop counter)
2. A condition that tests
for the final value of the
control variable (i.e.,
whether looping should
continue)
3. Update control variable
(incr/decr)
UniMAP DKT121 Sem 2
2010/2011
Counter-Controlled while
Loops

Another example:
declare and initialize
test condition
int product = 2;
while ( product <= 1000 )
increment
product = 2 * product;
product <= 1000
false
true
product = 2 * product
UniMAP DKT121 Sem 2
2010/2011
Sentinel-Controlled while
Loops



Indefinite repetition
Used when number of repetitions not known
and loop needs to input value repeatedly for
each iteration
Sentinel value indicates "end of data“
UniMAP DKT121 Sem 2
2010/2011
Sentinel-Controlled while
Loops-cont
Example:
int number, count, sum;
Requirement:
1. Read control
variable value
printf(“To stop enter -999. Enter positive numbers : " );
before enter loop
scanf(“%d”, &number);
2. A condition that
while (number != -999)
{
tests control
Sentinel value
sum = sum + number; //find sum of numbers entered
variable’s validity
count++; //count how many numbers entered
(i.e., whether
printf(“To stop enter -999. Enter positive numbers : " );
looping should
scanf(“%d”, &number);
continue)
}
3. Read again
printf(“\nThe sum of %d numbers is %d“, count, sum);
control variable
before end of loop
UniMAP DKT121 Sem 2
2010/2011
Sentinel-Controlled while
Loops-cont

Another example:
char choice;
read control variable
printf(“Continue?y-yes n-no :”);
scanf(“%c”, &choice);
test condition
while ( choice == ‘y’)
{
printf(“\nEnter grade point:”);
scanf(“%f”, &grade_pt);
if(grade_pt > 2.0)
printf(“\nPass);
printf(“Continue?y-yes n-no :”);
scanf(“%c”, &choice);
read again
}
UniMAP DKT121 Sem 2
2010/2011
Flag-Controlled while Loops


Uses a boolean variable to control the loop.
Loop exit when expression is evaluated to false.
bool found = false;
Set to false
test condition
while (!found)
{ printf(“Enter number between 1 and 200:”);
scanf(%d”, &guess);
if ((guess>= 88) &&(guess <=128))
decision
{found = true;
printf(“\nBINGO!”);}
structure
}
Set to true
UniMAP DKT121 Sem 2
2010/2011
Requirement:
1. Set control variable to
false before loop
2. A condition that tests
control variable. If expr
evaluated to true, loop
continue
3. A decision structure to
test value validity
4. Set control variable to
true to indicate found
The do-while Repetition
Structure





Similar to the while structure
Condition for repetition tested after the body
of the loop is performed
All actions are performed at least once
Expression can be written as count-controlled
or sentinel-controlled
Format:
do {
statement;
} while ( condition );
UniMAP DKT121 Sem 2
2010/2011
Flowchart of a do-while
structure
action(s)
true
condition
false
UniMAP DKT121 Sem 2
2010/2011
The do-while Repetition
Structure

Example : prints the integers from 1 to 10
int counter = 1;
do {
printf( "%d ", counter );
++counter;
} while (counter <= 10);

count-controlled
Another example:
do{
printf(“\nEnter grade point:”);
scanf(“%f”, &grade_pt);
if(grade_pt > 2.0)
printf(“\nPass);
printf(“Continue?y-yes n-no :”);
scanf(“%c”, &choice);
}while ( choice == ‘y’)
UniMAP DKT121 Sem 2
2010/2011
sentinel-controlled
The do-while Repetition
Structure
To avoid an infinite loop, make sure that the loop body contains a
statement that ultimately makes the expression false and assures that
it exits

Another example:
int i = 0;

do
{
Printf(“%d ”, i);
i = i + 5;
} while (i <= 20);
The output is:
0 5 10 15 20
UniMAP DKT121 Sem 2
2010/2011
The do-while Looping
Structure (Example)

Example: Consider the following two loops
UniMAP DKT121 Sem 2
2010/2011
The do-while Looping
Structure (Example)


In (a), the while loop, produces nothing
In (b) the do...while loop, outputs the
number 11
UniMAP DKT121 Sem 2
2010/2011
The for Repetition Structure

Format when using for loops
for ( initialization; loopContinuationTest; increment statement)


Use for loops when already know how
many times to repeat
Example:
for(counter = 1; counter <= 10;counter++ )
printf( "%d\n", counter );

Prints the integers from one to ten
UniMAP DKT121 Sem 2
2010/2011
The for Repetition Structure

For loops can usually be rewritten as while loops:
initialization;
while ( loopContinuationTest ) {
statement;
increment statement;
}

Initialization and increment
 Can be comma-separated lists
 Example:
for (int i = 0, j = 0; j + i <= 10; j++, i++)
printf( "%d\n", j + i );
UniMAP DKT121 Sem 2
2010/2011
Flow of a for statement
UniMAP DKT121 Sem 2
2010/2011
Nested loop



Loop within a loop
Inner loop is performed first
E.g.
Output
for(i=1;i<4;i++){
1234
1234
for(j=1;j<5;j++)
1234
printf(“%d”, j);
printf(“\n”);}
UniMAP DKT121 Sem 2
2010/2011
Nested loop

Another example:

Program find and print avg of three test scores, then asks
whether want to continue
do{
for(count=0; count <3;count++)
{
printf(“\nEnter test marks:”);
scanf(“%d”, marks);
total=total+marks;
}
avg=total/count;
printf(“\nAverage:%5.2f”, avg);
printf(“\nContinue?”);
scanf(“%c”, &choice);
}while(choice == ‘y’);
UniMAP DKT121 Sem 2
2010/2011
End Loops
Q & A!
UniMAP DKT121 Sem 2
2010/2011