[rps-include post=6557]
For loop is generally used for specified arrays or similar array like lists. For enumerates over given way and checks the condition whether it is met or not. Here is For syntax.
for (initialize;condition;increment) { statements }
Initialize
fired one time at the start of for loop and generally used to set some values. Condition is checked in every turn of loop and if condition is met for loop is ended. Increment is run is every turn of loop and generally used to change condition related value. Now the best way to understand is doing it.
#include <stdio.h> int main() { for(int a=1;a<10;a++) { printf("%d\n",a); } return 0; }
This example is similar to the previous while example.
- int a=1; is initializer and defines new variable named a and set its value as 1.
- a++ runs in every loop and increments a value like 2,3,4,5,..,9
- a<10; is checked in every loop if a is lower then 10 if the condition is not met which is where a is 10 the for loop ends.
- { printf(“%d\n”,a); } will print a value in every loop.
Infinite For Loop
There are different ways to implement infinite For loop like below.
for(;;) { printf("Infinite loop"); }
OR
for(;1=2;) { printf("Infinite loop"); }
OR
for(;true;) { printf("Infinite loop"); }
[rps-include post=6557]