You are on page 1of 40

Subject : COMP6047

ALGORITHM AND PROGRAMMING


Year : 2019

Program Control: Repetition


Learning Outcomes
At the end of this session, student will be able to:
• Demonstrate usage of repetition/looping control operation in C
programming language (LO2 & LO3)

COMP6047 - Algorithm and Programming 2


Sub Topics
Program Control - Repetition:
– Repetition Definition
– For
– While
– Do-While
– Repetition Operation
– Break vs Continue
– Program Examples
– Exercise

COMP6047 - Algorithm and Programming 3


Repetition Definition
 One or more instruction repeated for certain amount of time

 Number of repetition can be predefined (hard-coded in program)


or defined later at run time

 Repetition/looping operation:
– for
– while
– do-while

COMP6047 - Algorithm and Programming 4


Repetition: FOR
• Syntax:

for(exp1; exp2; exp3) statement;


or:
for(exp1; exp2; exp3){
statement1;
statement2;
…….
}

exp1 : initialization
exp2 : conditional
exp3 : increment or decrement
exp1, exp2 and exp3 are optional

COMP6047 - Algorithm and Programming 5


Repetition: FOR
• exp1 and exp3 can consist of several expression separated with comma

• Example:
void reverse(char ss[])
{
int c,i,j;
for(i=0, j=strlen(ss)-1; i<j; i++, j--){
c=ss[i];
ss[i]=ss[j];
ss[j]=c;
}
}

COMP6047 - Algorithm and Programming 6


Repetition: FOR
 Flow Chart of FOR Statement

exp1

exp3

statements

true
exp2

false

COMP6047 - Algorithm and Programming 7


Repetition: FOR
• Example:
for (x=1; x <= 10; x++) printf(“%d\n”, x);

x=1

True
x <= 10 printf(”%d\n”,x) x++

False

COMP6047 - Algorithm and Programming 8


Repetition: FOR
• Example:
– Program to print out numbers from 1 to 10
#include<stdio.h>
int main()
{
int x;
for( x = 1 ; x <= 10 ; x++ ) printf( "%d\n", x );
return(0);
}

#include<stdio.h>
– int main()
Program
{
to print out numbers from 10 to 1
int x;
for( x = 10 ; x >= 1 ; x-- ) printf( "%d\n", x);
return(0);
}

COMP6047 - Algorithm and Programming 9


Repetition: FOR
• Example:
Calculating average of monthly expenses:
Week Expenses
1 Rp. 32.000,-
2 Rp. 29.000,-
3 Rp. 33.000,-
4 Rp. 24.000,-
• Algorithm :
1. Create and empty total
2. Read from keyboard and save to data
3. Add data to total
4. Repeat 2 and 3 four times
5. Average = total / 4

COMP6047 - Algorithm and Programming 10


Repetition: FOR
• Example: (Calculating average of monthly expenses)
/*----------------------------------*/
/* Program Averaging */
/*----------------------------------*/
#include<stdio.h>
int main()
{
float data, total, average;
int x;
total = 0.0;
for( x = 1; x <= 4; x++) {
printf(“ Data week-%d :”,x);
scanf(“%f”,&data);
total = total + data;
}
average = total / 4;
printf(“Average = Rp %8.2f\n”,average);
return(0);
}
COMP6047 - Algorithm and Programming 11
Repetition: FOR
• Infinite Loop
Loop with no stop condition can use “for-loop” by
removing all parameters (exp1, exp2, exp3). To
end the loop use break.

• Nested Loop
Loop in a loop. The repetition operation will start
from the inner side loop.

COMP6047 - Algorithm and Programming 12


Repetition: FOR
C int x, y;
for (x=1;x<=5;x++)
for (y=5; y>=1; y--)
printf(”%d %d ”,x,y);
C++

NESTED LOOP

Output :
for (int x=1;x<=5;x++)
1 5 1 4 1 3 .. 2 5 2 4 .. 5 1
for (int y=5; y>=1; y--)
printf(”%d %d ”,x,y);

COMP6047 - Algorithm and Programming 13


Repetition: FOR
• Example: (Truth Table)
/*-----------------------------------
Program: the truth table;
------------------------------------*/
#include <stdio.h>
int main()
{
int P,Q;
printf(“==============================\n”);
printf(“P Q P or Q P and Q Not P P xor Q\n”);
printf(“==============================\n”);
for(P=1; P>=0; P--)
for(Q = 1; Q>=0; Q--)
printf(“%4d %4d %4d %4d %4d %4d\n”, P, Q, P||Q, P&&Q, !P, P^Q
);
printf(“==============================\n”);
}

COMP6047 - Algorithm and Programming 14


Repetition: WHILE
• Syntax :
while (exp) statements;
or:
while(exp){
statement1;
Example :
statement2; int counter = 1;
….. while ( counter <= 10 ) {
} printf( "%d\n", counter );
++counter;
}

COMP6047 - Algorithm and Programming 15


Repetition: WHILE
 Flow Chart of WHILE Statement

statements

condition
true

false

COMP6047 - Algorithm and Programming 16


Repetition: WHILE
while (exp) statements;

• exp is Boolean expression. It will result in true (not zero) or


false (equal to zero).
• Statement will be executed while the exp is not equal to zero.
• exp evaluation is done before the statements executed.

COMP6047 - Algorithm and Programming 17


Repetition: WHILE
• Example :

while(product <= 1000) product = 2*product;

True
product <= 1000 product=2*product;

False

COMP6047 - Algorithm and Programming 18


Repetition: WHILE
These code are analogous

#include<stdio.h> #include<stdio.h>
void main() { void main() {
int x; int x = 1;
for( x = 1 ; x <= 10 ; x++ ) while (x<=10) {
printf( "%d\n", x ); printf( "%d\n", x );
} x++;
}
}

COMP6047 - Algorithm and Programming 19


Repetition: DO-WHILE
• Syntax : Example :
int counter=0;
do{ do {
< statements >; printf( "%d ", counter );
} while(exp); ++counter;
} while (counter <= 10);

• Keep executing while exp is true


• exp evaluation done after executing the statement(s)

COMP6047 - Algorithm and Programming 20


Repetition: DO-WHILE
 Flow Chart of DO-WHILE Statement

statements

true
condition

false

COMP6047 - Algorithm and Programming 21


Repetition: DO-WHILE
• Example:
do{
printf(”%d\n”,counter);
} while(++counter <=10);

printf(”%d\n”,counter);

Tru
++counter <=10 e

False

COMP6047 - Algorithm and Programming 22


Repetition Operation
• In while operation, statement block of statements may never
be executed at all if exp value is false
• In do-while on the other hand statement block of statements
will be executed min once

• To end the repetition, can be done through several ways:


– Sentinel
– Question, should the repetition continue?

COMP6047 - Algorithm and Programming 23


Repetition Operation
• Example: (Question)
#include <stdio.h>
int main()
{
int width, height, area; char repeat;
printf(”Continue ? (Y/N) :”);
scanf(”%c”,&repeat);
while((toupper(repeat)) == ’Y’) {
printf(” Width : ”);
scanf(”%d”,&width);
printf(” Height : ”);
scanf(”%d”,&height);
area = width*height;
printf(” Area = %d\n\n”,area);
printf(”Continue ?(Y/N):”);
scanf(”%c”,&repeat);
}
return(0);
}
COMP6047 - Algorithm and Programming 24
Repetition Operation
• Example: (Sentinel)
As sentinel, used 0 for width or height
#include <stdio.h>
int main()
{
int width, height, area;
do{
printf(” Width : ”);
scanf(”%d”,&width);
printf(” Height : ”);
scanf(”%d”,&height);
area = width*height;
printf(” Area = %d\n\n”,area);
} while((width != 0) && (height !=
0));
return(0);
}
COMP6047 - Algorithm and Programming 25
Repetition Operation
#include<stdio.h>
int main() {
int x = 1;
while (x<=10) { Break is to force finish
printf( "%d\n", x );
x++;
the loop
break;
}
return 0;
} end the loop

COMP6047 - Algorithm and Programming 26


Break vs Continue
• break:
– ending loop (for, while and do-while)
– end the switch operation

• continue:
skip all the rest of statements (subsequent to the skip
statement) inside a repetition, and continue normally to the next
loop

COMP6047 - Algorithm and Programming 27


Break vs Continue
• Example using continue:
#include <stdio.h>
int main() {
int x;
for(x=1; x<=10; x++) {
if (x == 5) continue;
printf("%d ", x);
}
return 0;
}
Output : 1 2 3 4 6 7 8 9 10

COMP6047 - Algorithm and Programming 28


Break vs Continue
• Example using break:
#include <stdio.h>
int main() {
int x;
for(x=1; x<=10; x++) {
if (x == 5) break;
printf("%d ", x);
}
return 0;
}
Output : 1 2 3 4

COMP6047 - Algorithm and Programming 29


Example Labeling
• Example using labeling:
#include <stdio.h>
int main() {
int x;
for(x=1; x<=10; x++) {
if (x == 5) goto exit;
printf("%d ", x);
}
exit:
return 0;
}
Output : 1 2 3 4

COMP6047 - Algorithm and Programming 30


Exercise
1. Given the following code:
for (i=k; i < n; i++) printf(”Binus\n”);
a. If k < n how many times the statement executed?
b. If k = n how many times the statement executed?
c. If k > n how many times the statement executed?
2. Given the following code:
for (i=k; i >= n; i--) printf(”Binus\n”);
a. If k < n how many times the statement executed?
b. If k = n how many times the statement executed?
c. If k > n how many times the statement executed?

COMP6047 - Algorithm and Programming 31


Exercise
3. If p = statement and e = expression, rewrite the following for
loop to while loop.
a. for(; e ;) p;
b. for(; ; e) p;

4. Compare and contrast the following codes:


for (i=0, j=1; i<8; i++, j++) printf("%d + %d = %d\n", i, j, i+j);

for (i=0, j=1; i<8; ++i, ++j); printf("%d + %d = %d\n", i, j,


i+j);
Also describe their output!

COMP6047 - Algorithm and Programming 32


Exercise
5. #include <stdio.h>
int main()
{
int x,y;
for(x=1;x<=3;x++)
for (y=3;y>=1;y--) What are their output ?
printf("%d %d ",x,y);
return 0;
}

#include <stdio.h>
int main()
{
int x,y;
for(x=1;x<=3;x++); watch for the semicolon
for (y=3;y>=1;y--)
printf("%d %d
",x,y);
return 0;
}
COMP6047 - Algorithm and Programming 33
Exercise
6.
#include <stdio.h>
int main() What are their output ?
{
int x,y; watch for the semicolon
for(x=1;x<=3;x++)
for (y=3;y>=1;y--);
printf("%d %d ",x,y);
return 0;
}

#include <stdio.h>
int main()
{
int x,y;
for(x=1;x<=3;x++); watch for the
for (y=3;y>=1;y--); semicolon
printf("%d %d ",x,y);
return 0;
} COMP6047 - Algorithm and Programming 34
Exercise
7. Explain the output:
#include<stdio.h>

int main() {
int score = 0, total= 0;
while(score < 10) {
total += score;
printf(”\nScore =%d, Total =%d”, score++,
total);
}
return 0;
}

COMP6047 - Algorithm and Programming 35


Exercise
8. Explain the output:
#include<stdio.h>

int main() {
long number, tmp, x=1;
printf(”\nInput number:”); scanf(”%d”, &number);
tmp=number;
while(number>= 1) x*=number--;
printf(”\n%ld ! = %ld”,tmp, x);

return 0;
}

COMP6047 - Algorithm and Programming 36


Exercise
9. Create a program using C to display odd numbers from 11 to 188, using :
– for
– while
– do-while

10. Given: 1 is Monday, 2 - Tuesday, 3 – Wednesday , and so on. Using C,


create a program to show the value of each day in a week using n - input
from keyboard. Example:
N=3
1 2 3
N=7
2 2 3 4 5 6 7
N = 10
1 2 3 4 5 6 7 1 2 3

COMP6047 - Algorithm and Programming 37


Summary
 Repetition is a condition which is one or more instruction
repeated for certain amount of time

 3 types of repetition/looping in C:
– for
– while
– do-while

COMP6047 - Algorithm and Programming 38


References
• Paul Deitel & Harvey Deitel. (2016). C how to program : with an
introduction to C++. 08. Pearson Education. Hoboken. ISBN:
9780133976892. Chapter 3 & 4
• Doing the Same Thing Over and Over: http://aelinik.free.fr/c/
ch07.htm

COMP6047 - Algorithm and Programming 39


END

COMP6047 - Algorithm and Programming 40

You might also like