Professional Documents
Culture Documents
Repetition/looping operation:
– for
– while
– do-while
exp1 : initialization
exp2 : conditional
exp3 : increment or decrement
exp1, exp2 and exp3 are optional
• 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;
}
}
exp1
exp3
statements
true
exp2
false
x=1
True
x <= 10 printf(”%d\n”,x) x++
False
#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);
}
• Nested Loop
Loop in a loop. The repetition operation will start
from the inner side loop.
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);
statements
condition
true
false
True
product <= 1000 product=2*product;
False
#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++;
}
}
statements
true
condition
false
printf(”%d\n”,counter);
Tru
++counter <=10 e
False
• continue:
skip all the rest of statements (subsequent to the skip
statement) inside a repetition, and continue normally to the next
loop
#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;
}
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;
}
3 types of repetition/looping in C:
– for
– while
– do-while