Topic-16: for loop

Defination:

A for loop is a control flow statement in programming languages that allows code to be executed repeatedly for a specific number of times. It provides a concise way to iterate over a sequence or perform a set of operations a predetermined number of times.

The basic structure of a for loop in most programming languages is as follows:

for (initialization; condition; increment/decrement) {
// code to be executed repeatedly
}

In this structure:

  • Initialization: This part is executed once before the loop starts. It typically initializes a loop control variable or variables.
  • Condition: This is the condition that is evaluated before each iteration of the loop. If the condition evaluates to true, the loop continues; if it evaluates to false, the loop terminates.
  • Increment/Decrement: This part is executed after each iteration of the loop. It usually increments or decrements the loop control variable.
  • Loop Body: This is the block of code inside the curly braces {} that gets executed repeatedly as long as the condition evaluates to true.

The for loop is especially useful when you know in advance how many times you need to execute a block of code or when iterating over elements of an array, list, or other sequence.

For example, in a loop that prints numbers from 1 to 10:

for (int i = 1; i <= 10; i++) { print(i); }


Leave a Comment

Your email address will not be published. Required fields are marked *