Explain 'for' loop with proper example.
Answers
Answer:Basic syntax to use ‘for’ loop is:
for (variable initialization; condition to control loop; iteration of variable) {
statement 1;
statement 2;
..
..
}
In the pseudo code above :
Variable initialization is the initialization of counter of loop.
Condition is any logical condition that controls the number of times the loop statements are executed.
Iteration is the increment/decrement of counter.
It is noted that when ‘for’ loop execution starts, first variable initialization is done, then condition is checked before execution of statements; if and only if condition is TRUE, statements are executed; after all statements are executed, iteration of counter of loop is done either increment or decrement.
Here is a basic C program covering usage of ‘for’ loop in several cases:
#include <stdio.h>
int main () {
int i = 0, k = 0;
float j = 0;
int loop_count = 5;
printf("Case1:\n");
for (i=0; i < loop_count; i++) {
printf("%d\n",i);
}
printf("Case2:\n");
for (j=5.5; j > 0; j--) {
printf("%f\n",j);
}
printf("Case3:\n");
for (i=2; (i < 5 && i >=2); i++) {
printf("%d\n",i);
}
printf("Case4:\n");
for (i=0; (i != 5); i++) {
printf("%d\n",i);
}
printf("Case5:\n");
/* Blank loop */
for (i=0; i < loop_count; i++) ;
printf("Case6:\n");
for (i=0, k=0; (i < 5 && k < 3); i++, k++) {
printf("%d\n",i);
}
printf("Case7:\n");
i=5;
for (; 0; i++) {
printf("%d\n",i);
}
return 0;
}
Explanation:
A loop is used for executing a block of statements relatedly until a particular condition is satisfied.
EXAMPLE
When you are displaying number 1 to 100 you may want to set the value of the variable to 1 and display it in 100 times increasing its value in each loop iteration
HOPE IT HELPS U .................
✌✌