Вы находитесь на странице: 1из 50

EKT120

COMPUTER PROGRAMMING
Control Structure:
Repetition

Rusnida Romli
Recaps... Control Structure

• All programs could be written in terms of three


control structures:
1. Sequence structure
2. Selection structure
• one-way selection: if
• if ... else
• switch
3. Repetition structure

2
Today’s Outline
• Introduction to Repetition Structure
(Loops)
• Type of loops
– while loops
– do-while loops
– for loops
• Nested loops
3
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(“%f %f %f %f %f”, &fNum1, &fNum2,
&fNum3, &fNum4, &fNum5);
fSum = fNum1 + fNum2 + fNum3 + fNum4 + fNum5;
fAverage = fNum / 5;

• If 100 numbers or 1000 numbers?

4
Repetition Structures (Loop)

• Used to control the flow of a program


• Loops are basically repetitions or iterations used to repeat a
segment of code
• Three statements used to implement loops in C:
1. while statement
2. do-while statement
3. for statement
• while and for statements are similar in implementation,
but have different syntax
• The do-while statement is different
– do-while statement is executed at least once
5
1. while Repetition Structure

• The general form of the while statement is:


while (expression)
statement;
• To avoid an infinite loop, the loop’s body must
contains statement (s) that assure the exit condition
– i.e. the expression in the while statement will
eventually be false.
• while loop repeats until condition becomes false

6
Flowchart of a while statement

7
Types of while Loops
• There are basically three types of while
loops:
– Counter-controlled while loop
– Sentinel-controlled while loop
– Flag-controlled while loop

8
Counter-Controlled while Loops

 Count-controlled while loop uses a loop control


variable in the logical expression
 Control variable used to count repetitions
 Loop control variable should be initialized before
entering the while loop, and a statement in the body of
the while loop should increment/decrement the
control variable
 Definite repetition: know how many times loop will
execute
9
Example : Counter-Controlled while

#include <stdio.h>
int main()
{ Declare and initialize control variable
value (or loop counter)
int iCounter = 1;
test condition  A condition that tests for
the final value of the control variable (i.e.,
while ( iCounter <= 10 )
whether looping should continue)
{
printf( "%d\n", iCounter );

++iCounter; Update control variable (increment/decrement)


}
return 0;
}

10
Example : Counter-Controlled while

#include <stdio.h>
int main()
{
1
2
int iCounter = 1;
3
4
while ( iCounter <= 10 )
5
{
6
printf( "%d\n", iCounter );
7
8
++iCounter;
9
}
10
return 0;
}

11
Example : Counter-Controlled while
• Adding integers from 1 to 100

true
iCounter <= 100 iSum = iSum + iCounter
false

int iCount = 1; declare and initialize


int iSum=0;
while (iCount <= 100 ){ test condition
printf(“Adding %d to %d ”, iCount,iSum);
iSum = iSum + iCount;
printf(“ = %d”, iSum);

++iCounter; increment
} 12
Example : Counter-Controlled while
• Adding integers from 1 to 100

true
iCounter <= 100 iSum = iSum + iCounter
false
Adding 1 to 0 = 1
Adding 2 to 1 = 3
int iCount = 1; declare and initialize
Adding 3 to 3 = 6
int iSum=0; …
while (iCount <= 100 ){ … test condition
printf(“Adding %d to %d ”, iCount,iSum);

iSum = iSum + iCount; Adding 100 to 4950 = 5050
printf(“ = %d”, iSum);

++iCounter; increment
} 13
Sentinel-Controlled while Loops

• An event-controlled while loop may use a special


data value, sentinel, in conjunction with the logical
expression to signal the loop exit.
• Sentinel value indicates "end of data“
• As long as the sentinel value does not meet the
logical expression (specified data value), the loop is
executed
• Used when the number of repetitions is unknown
and loop needs to input value repeatedly for each
iteration
14
Example: Sentinel-Controlled while
 Adding multiple numbers
int iNumber; //declaration control variable
int iSum = 0;
int iCount = 0;

printf("To stop enter -999. Enter numbers : " );


scanf("%d",&iNumber);//read control variable value before enter loop

while (iNumber != -999) // test condition


{
iSum = iSum + iNumber; //find sum of numbers entered
iCount++;//counting numbers entered (increment of control
variables)

printf("To stop enter -999. Enter numbers : " );


scanf("%d", &iNumber); //Read again control variable value
}
printf("\nThe sum of %d numbers is %d", iCount, iSum);
15
Example: Sentinel-Controlled while
 Adding multiple numbers

int iNumber; //declaration control variable


int iSum = 0;
To stop enter -999. Enter numbers : 4
int iCount = 0;
To stop enter -999. Enter numbers : 900
To numbers
printf("To stop enter -999. Enter stop enter: -999.
" );Enter numbers : 1600
To stop
scanf("%d",&iNumber);//read control enter -999.
variable Enter
value numbers
before : -999
enter loop

while (iNumber != -999) The sum of //


3 numbers is 2504
test condition
{
iSum = iSum + iNumber; //find sum of numbers entered
iCount++;//counting numbers entered (increment of control
variables)

printf("To stop enter -999. Enter numbers : " );


scanf("%d", &iNumber); //Read again control variable value
}
printf("\nThe sum of %d numbers is %d", iCount, iSum);
16
Example: Sentinel-Controlled while
 Evaluating grade points
char cChoice; declare control variable
float fGradePt=0;

printf(“Do want to begin? y-yes n-no: ”);


scanf(“%c”, &cChoice);
read control variable
while ( cChoice == ‘y’)
{
printf(“\nEnter grade point: ”);test condition
scanf(“%f”, &fGradePt);

if(fGradePt > 2.0)


printf(“\nPass\n”);
else
printf(“\n Fail \n”);

printf(“Continue? y-yes n-no: ”);


scanf(“%c”, &cChoice); read again
}
17
Example: Sentinel-Controlled while
 Evaluating grade points
char cChoice;
float fGradePt=0;
declare control variable
printf(“Do want to begin? y-yes n-no: ”);
scanf(“%c”, &cChoice); read control variable
while ( cChoice == ‘y’) test condition
{
printf(“\nEnter grade point:
Do ”);
you want to begin? y-yes n-no : y
scanf(“%f”, &fGradePt); Enter grade point : 2.5
Pass
if(fGradePt > 2.0) Continue? y-yes n-no: y
printf(“\nPass\n”); Enter grade point : 1.9
else
Fail
printf(“\n Fail \n”);
Continue? Y-yes n-no: n
printf(“Continue? y-yes n-no: ”);
scanf(“%c”, &cChoice);
} read again
18
Flag-Controlled while Loops

• 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
• Loop exit when expression is evaluated to false

19
Example : Flag-Controlled while
 Adding multiple numbers
bool proceed; // used to control the while loop
int sum; // the sum of the numbers read
int number; // the number read

sum = 0; // initialize the sum


proceed = true; // initialize the boolean variable done

while ( proceed ) // while proceed is true


{
scanf(“%d”,&number); // read next number
if ( number > 0 ) // sum number if positive
sum = sum + number; // sum the number
else
proceed = false; // terminate the loop
}

printf(“Sum is %d \n”,sum); 20
Example : Flag-Controlled while
 Adding multiple numbers
bool proceed; // used to control the while loop
int sum; // the sum of the numbers read
int number; // the number read

sum = 0; // initialize the sum


proceed = true; // initialize the boolean variable done

while ( proceed ) // while proceed is true


{
scanf(“%d”,&number); // read next number
if ( number > 0 ) // sum number
100 if positive
sum = sum + number; // sum
200the number
else 300
proceed = false; // terminate
400 the loop
} 0
Sum is 1000
printf(“Sum is %d \n”,sum); 21
2. do-while Repetition Structure

• Similar to the while structure


• Condition for repetition is tested after the body of
the loop is performed at least once
• Expression can be written as count-controlled or
sentinel-controlled
• Format:
do {
statement;
} while ( condition );

22
Flowchart of a do-while loop

action(s)
true

condition

false

23
Example: Counter-Controlled do-while
• Adding integer from 1 to 10

int iCounter = 1;
int iSum=0;

do {
printf(“Adding %d to %d =",iCounter,iSum );
 
iSum=iSum+iCounter;
printf(“ %d\n”,iSum);

} while ( ++iCounter <= 10 );

24
Example: Counter-Controlled do-while
• Adding integer from 1 to 10 Adding 1 to 0 = 1
Adding 2 to 1 = 3
int iCounter = 1; Adding 3 to 3 = 6

int iSum=0; …

do { Adding 10 to 45 = 55

printf(“Adding %d to %d =",iCounter,iSum );
 
iSum=iSum+iCounter;
printf(“ %d\n”,iSum);

} while ( ++iCounter <= 10 );

25
Example: Sentinel-Controlled while
 Evaluating grade points

char cChoice; declare control variable


float fGradePt=0;

do
{
printf(“\nEnter grade point: ”);
scanf(“%f”, &fGradePt);

if(fGradePt > 2.0)


printf(“\nPass\n”);
else
printf(“\n Fail \n”);

printf(“Continue? y-yes n-no: ”);


scanf(“%c”, &cChoice);
read control variable
}while( cChoice == ‘y’) test condition
Example: Sentinel-Controlled while
 Evaluating grade points

char cChoice;
float fGradePt=0;

do
{
printf(“\nEnter grade point: ”);
scanf(“%f”, &fGradePt);

if(fGradePt > 2.0)


printf(“\nPass\n”);
else
printf(“\n Fail \n”);

printf(“Continue? y-yes n-no:


Enter grade ”);
point : 2.5
scanf(“%c”, &cChoice);
Pass read control variable
}while( cChoice == ‘y’) Continue? n
test condition
Infinite loop in do-while
• To avoid an infinite loop, the loop body must contain a
statement that ultimately makes the expression false and
assures exit from the loop
• Another example:
int iLoop = 0;
do {
printf (“%d ”,iLoop);
iLoop = iLoop + 5;
} while (iLoop <= 20);

The output is:


28
0 5 10 15 20
Comparison between
while and do-while
• Example: Adding integers
(a) (b)
iLoop = 11;
iLoop = 11; do
while (iLoop <= 10) {
{ printf("%d",iLoop);
printf("%d",iLoop); iLoop = iLoop + 5;
iLoop = iLoop + 5; }while (iLoop <= 10);
}

In (a), the while loop, produces nothing


In (b) the do…while loop, outputs the number 11
29
3. for Repetition Structure
• Format when using for loops
for (initialization ; loop continuation test ;
increment statement)

• Use for loops when the repetition count is known


• Example: Printing integer from 1 to 10
for(iCounter = 1;iCounter <= 10;iCounter++)
printf("%d\n",iCounter);

30
3. for Repetition Structure
• for loops can usually be rewritten as while loops:
initialization;
while ( loop continuation test ) {
statement;
increment statement;
}
• Initialization and increment can be comma-separated lists
int iVar1, iVar2;
for(iVar1=0,iVar2=0; iVar2+iVar1<=10; iVar2+
+,iVar1++)
printf(“%d\n”,iVar2+iVar1);

31
Flowchart of for statement

32
Nested loop
• Loop within a loop
• Inner loop is performed first
• Example 1:

for(iLoop1=1 ; iLoop1<4 ; iLoop1++)


{
for(iLoop2=1 ; iLoop2<5 ; iLoop2++)
printf(“%d”, iLoop2);
printf(“\n”); 1234
} 1234
1234
33
Nested loop
• Example 2: Program finds and prints average of
three test scores, then asks if user wants to
continue
do
{
for(iCount=0; iCount <3;iCount++)
{ printf(“\nEnter test marks: ”);
scanf(“%d”, &iMarks);
iTotal=iTotal+iMarks;
}

fAvg=iTotal/iCount;
printf(“\nAverage:%5.2f”, fAvg);

printf(“\nContinue?”);
scanf(“%c”, &cChoice);
}while(cChoice == ‘y’); 34
Nested loop
• Example 2: Program finds and prints average of
three test scores, then asks if user wants to
continue
do
{
for(iCount=0; iCount <3;iCount++)
{ printf(“\nEnter test marks: ”);
scanf(“%d”, &iMarks); Enter test marks : 78
iTotal=iTotal+iMarks; Enter test marks : 85
} Enter test marks : 82
Average : 81.67
fAvg=iTotal/iCount; Continue? y
printf(“\nAverage:%5.2f”, fAvg);
Enter test marks : 65
printf(“\nContinue?\n”); Enter test marks : 73
scanf(“%c”, &cChoice); Enter test marks : 68
}while(cChoice == ‘y’); Average : 68.67
Continue? n 35
Exercise 1
• Write a C code segment using the while loop
to find the sum of the first 99 positive integers
1,2,3…99.
Display the resulting sum.
Declare and initialize variables used.

36
ANSWER: Exercise 1
#include <stdio.h>
void main(){
int counter, sum; // declare variables
counter = 1; // initialization
sum = 0;
while (counter < 100){ // iterate 99 times
sum = sum + counter; // adding values to
sum
++counter; // increment the counter
}
printf("The sum is %d “, sum ); // Display the sum
}
37
ANSWER: Exercise 1
The sum is 495
#include <stdio.h>
void main(){
int counter, sum; // declare variables
counter = 1; // initialization
sum = 0;
while (counter < 100){ // iterate 99 times
sum = sum + counter; //adding values to sum
++counter; // increment the counter
}
printf("The sum is %d “, sum ); // Display the sum
}

38
Exercise 2
• Write a C program to read characters from the
keyboard until a ‘q’ character is read.
Use a sentinel-controlled while loop to find
the number of nonblank characters read from
the keyboard

39
ANSWER: Exercise 2
#include <stdio.h>
void main(){
char letter; //declaration of letters read
int counter=0; //declaration and initialization
scanf(“%s”,&letter); // read the first letter
while ( letter != 'q'){ // loop until 'q' is read
printf(“%s\n”,letter);
++counter; // increment letter counter
scanf(“%s”,&letter); // read next letter
}
printf("The number of letters read is %d\n“,
counter);
}
40
ANSWER: Exercise
A
B
2
C
D
#include <stdio.h> E
void main(){ q
char letter; The number
//declaration ofof letters
letter is 5 read
int counter=0; //declaration and initialization
scanf(“%c”,&letter); // read the first letter
while ( letter != 'q'){ // loop until 'q' is read
printf(“%c\n”,letter);
++counter; // increment letter counter
scanf(“%c”,&letter); // read next letter
}
printf("The number of letters read is %d\n“,
counter);
}
41
Exercise 3
• Write a program that utilizes looping to
print the numbers from 1 to 10 side-by-
side on the same line with 3 spaces
between each number

42
ANSWER: Exercise 3
#include<stdio.h>

int main()
{
int i=1; //initialize i

//loop while i is less than 11


while(i < 11)
{
printf(“%d ”, i);
++i;
}
return 0; //indicate successful termination
}
0 1 2 3 4 5 6 7 8 9 10

43
Exercise 4
• Finding Error
for ( x = .000001; x <= .0001; x += .000001 )
printf( "%.7f\n", x );

ANSWER:
Floating point numbers should never be used in loops
due to imprecision. This imprecision often causes
infinite loops to occur. To correct this, an integer
variable should be used in the for loop.

44
Exercise 5
What the following program do?
#include<stdio.h>
int main()
{
int x,y,i,j; //declare variables

printf(“Enter two integers in range 1-20:”);


scanf(“%d %d”,&x,&y); //read values for x,y

for(i=1;i<=y;i++){
for(j=1;j<=x;j++)
{
printf(“@”); // display output @
} //end inner for
printf(“\n”);
}
return 0; //indicate successful termination
} 45
ANSWER : Exercise 5

Enter integers in the range 1-20: 3 4


@@@
@@@
@@@
@@@

46
How about this?
...
for(i=0;i<5;i++)
@
{ for(j=0;j<=i;j++) @@
printf(“@”); @@@
printf(“\n”);
@@@@
}
@@@@@
….
Exercise 6

Write a program that sums a sequence of integers. Assume that


the first integer read with scanf specifies the number of
values remaining to be entered. Your program should read only
one value each time scanf is executed. A typical input sequence
might be
5 100 200 300 400 500
where the 5 indicates that the subsequent five values are to be
summed.

48
ANSWER : Exercise 6

49
Q & A!

50

Вам также может понравиться