A simple for loop explained in the following program written in C language.
C tutorials >> For loop in C >> C programming courses
C programming language : for loop explained
Source Code :
#include int main() { int i; for(i=1;i<5;i++) { printf("i=%d\n",i); } }
The first statement #include is a header file required to use the library functions in C. If you don’t understand this at this level then just think you need to write this line to learn a C program.
int main() is the main function body, you need to write it in most C programs. In the main function body i variable is declared by the statement int i. The main function is like the following :
int main()
{
}
In the for loop there is 3 parts :
for(initialisation ; checking a condition** ; increment or decremment) { For loop body; }
**Condition is checked to determine – when the loop will end, otherwise a loop will run forever. There must be a decisive factor to end the loop otherwise the loop will run indefinitely and shall not stop. So always be careful about this. You need to terminate a loop after some time.
In the above example variable i is initialized with value 1. Then i < 5 condition is checked, so initially i=1 and it is less than 5 so the printf statement executes and value of i is printed.
Output: i=1
After that i is incremented by 1 by the statement i++, and then i becomes 2 and again i will be checked whether i < 5 or not ? Now i=2 and i<5 so the output will be
Output:
i=1
i=2
Again i is incremented by 1 by the statement i++, and then i becomes 3 and again i will be checked whether i < 5 or not ? Now i=3 and i<5 so the output will be
Output:
i=1
i=2
i=3
Again i is incremented by 1 by the statement i++, and then i becomes 4 and the output will be :
i=1
i=2
i=3
i=4
The Loop Terminates Now : Again i is incremented by 1 by the statement i++, and then i becomes 5 and again i< 5 condition is checked , but 5 is not less than 5, so i<5 becomes false and loop terminates and the program ends.
A video tutorial in YouTube on C For Loop:
About the author : Mr Choudhury teaches C C++ Java PHP etc programming language and you can learn from your home too.