The For Loop
Learn how to repeat code execution efficiently
For Loop
Today we will get acquainted with loops in programming. Loops are an important concept that allows you to perform certain actions multiple times or a required number of times.
There are two main types of loops, and one of them is the for loop.
The for loop is one of the most common ways to repeat actions in a program. It allows you to execute certain commands or code blocks repeatedly.
For Loop Syntax
Here is the basic syntax of the for loop:
The for loop includes three main components:
- Initial value: sets the initial value of the counter.
- Continuation condition: determines when the loop will execute.
- Step: determines how the counter changes after each iteration.
For Loop Example
Let's look at an example of a for loop that prints numbers from 1 to 5:
In this example, we declare a variable i and set its initial value to 1. Then we set the loop continuation condition i <= 5, which means the loop will execute while the value of i is not greater than 5. Inside the loop, we output the value of i and increment it by 1 after each iteration. If we run this code, it will output numbers from 1 to 5.
Detailed Execution Explanation
Now let's examine in more detail what happens at each step:
First iteration (first time the loop executes)
Initially, the program declares variable i, which equals 1. Then it checks the condition i <= 5. At this moment i = 1, and the condition is met. After this, the program goes inside the loop and outputs the value of i, which equals 1. Then the increment step i by 1 is executed, and now i = 2. i++ is the same as writing i = i + 1.
Second iteration
This time the program doesn't execute the initial value (where i = 1), but immediately checks the condition i <= 5. In this iteration, i already equals 2, since in the previous iteration it increased by 1. The condition is met, and the program outputs the value of i, which now equals 2. Then i increases by 1, and now i = 3.
Third iteration and so on
The process is similar to the second iteration. The program checks the condition, outputs the value of i, increments it, and continues until i becomes greater than 5. When becomes equal to 6, the condition is no longer met, and the loop terminates.