Here, we shall look at an introduction to for loops in C. (For posts on while loops, pls see here. For posts on C Programming, pls see here.)
We shall look at certain basic aspects of loop, and look at an example program.




















Above, we looked at certain important aspects of loops, and looked at one example program.
In order to design a loop, we need to consider two things –
– How many times the loop should run?
– What task is to be performed each time the loop runs?
In order to control the number of times the loop runs, we use a loop counter or a loop control variable.
– This variable is initialized once. (Remember that initialization of the loop counter is done only once. )
– Prior to each iteration, we check a condition. Only if this loop condition is true, will we enter the loop. (In case it is false, we will terminate the loop.)
– Once the condition is true, and we are within the loop, we execute whatever statements are there within the loop body. Once we have executed all the statements within the loop body, we update the loop counter.
– That is, after each iteration of the loop, we will update the loop counter. After updating the loop counter, we will check the loop condition again.
– If the loop condition is true, we will enter the loop (and execute the statements within it).
If it is not true, we will terminate the loop. (Don’t run the loop any more.)
– In this way, the loop keeps running until the loop condition becomes false.
– In a for loop in C, the initialization, loop counter, and updation is written very compactly in a single line.
Here is a simple program and output:
<stdio.h>int main(){ for (int i = 1; i <= 5; i++) { printf("Hello\n"); } printf("Thank you!"); return 0;}
Output: HelloHelloHelloHelloHelloThank you!
Leave a comment