If we want to execute some part of the code multiple times, we can use cyclic structures.
There are three types of cycles:
They can be replaced by each other, but their purposes are slightly different.
Cycle for() can be used to iterate over some structure or do smth for fixed amount of times.
The skeleton: for(init val; condition; change),
where
Examples:
for (int i = 0; i < 10; i++)
printf("Name\n");
int a[10];
for (int i = 0; i < 10; i++)
printf("%d ", a[i]);
Cycle while() is a simplified for(), that contains only condition
int i = 0;
while (i < 10) {
printf("Name\n");
i++;
}
is the same as
for (int i = 0; i < 10; i++) {
printf("Name\n");
}
Sometimes it can be useful and simplify your code.
For example, we can count a sum of digits in a number:
int n, sum = 0;
scanf("%d", &n);
while (n != 0) {
sum += n % 10;
n /= 10;
}
Cycle do {} while() is the same as while(), but its body will be executed at least time.
So, if we write while():
int i = 10;
while (i < 10) {
printf("Name\n");
i++;
}
nothing will be printed, but if rewritten with do {} while():
int i = 10;
do {
printf("Name\n");
i++;
}
while (i < 10);
the cycle executes 1 time, though the condition is false.
Comments
Thankyou very much , it helped me a lot .i hope that in future you will help us in the same manner
Leave a comment