For Loop

Loop executes the same block of code again and again until the given condition is true. We use for loop to iterate when we know the number of iterations.


for(statement-1; statement-2; statement-3)
{
      ...
}

Statement-1 – assign value to a variable.
Statement-2 – check condition.
Statement-3 – change the value of variable.

forLoop.c
#include <stdio.h>
  
int main() {
  int i;
    
  for (i = 0; i < 5; i++) {
    printf("My name is Kiara\n");
  }
      
  return 0;
}

In this Example:

  • Statement-1 shows i=0.
  • Statement-2 checks condition, i is less than 5(true), move inside loop and print name.
  • Statement-3 will increment i, now i=1. Statement-2 checks condition, i is less than 5(true), move inside loop and print name.
  • Statement-3 will increment i, now i=2. Statement-2 will check the condition if i is less than 5(true), move inside loop and print name.
  • Statement-3 will increment i, now i=3. Statement-2 will check condition again, i is less than 5(true), move inside loop and print name.
  • Statement-3 will increment i, now i=4. Statement-2 checks the condition and if i is less than 5(true), move inside loop and print name.
  • Statement-3 will increment i, now i=5. Statement-2 checks the condition, if i is less than 5(false), loop will terminate and control moves to next line.

forLoop.c
#include <stdio.h>

int main(){
  int i;
  for(i=0; i<5; i++){
    printf("%d", i);
  }
  return 0;
}

Nested Loops:

Nested loops are loops within loops. When we have a nested loops then, when outer loop runs one-time, inner loops complete its all iterations. After that control moves to the outer loop. Again, the outer loop runs a second time and inner loop completes its all iterations. This process will continue until the outer loop completes its all iterations.

forLoop.c
#include <stdio.h>
  
int main() {
      
  for (int i = 1; i <= 2; ++i) {
    printf("Outer loop\n", i);  
        
    for (int j = 1; j <= 3; ++j) {
      printf(" Inner loop\n", j);  
    }
  }
      
  return 0;
}

Infinite for loop:

If you put the double semicolon inside paranthesis, it will become infinite for loop.
// infinite for loop
for(;;){
  // code
}