C For Loops

Loops can execute a block of code if a specified condition is reached.


Loops are useful because they speed up programming, lower mistake rates, and improve readability.


Use the for loop when you are certain of the number of times you want to loop through a piece of code.



for (statement 1 ; statement 2 ; statement 3 ;) }
// code block
}


Statement 1 is executed (one time) before the execution of the code block. Statement 2 defines the condition for executing the code block. Statement 3 is executed (every time) after the code block has been executed.

Code:


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


Output

1

Explanation

Before the loop begins, statement 1 sets a variable (int i = 0).


Statement 2 specifies the prerequisites for the loop's operation (i must be less than 5). The loop will repeat itself if the condition is true and come to an end if it is false.

br

With each iteration of the loop's code block, statement 3 increases the value by one(i++).







© Copyright 2022 Advanced PLC. All rights reserved.