For Statement
The lagi statement is used to loop through a range of values, specifying initialization, condition, and update.
Syntax
lagi(initialization; condition; update;) Basic For Loop
A simple for loop that iterates from 0 to 4:
purna i;
lagi(i = 0; i < 5; i = i + 1;) {
bhana(i);
}
:) Output: 0 1 2 3 4For Loop for Calculations
A for loop that calculates the sum of numbers from 1 to 10:
purna i;
purna sum;
sum = 0;
lagi(i = 1; i <= 10; i = i + 1;) {
sum = sum + i;
}
bhana("Sum of numbers from 1 to 10: ");
bhana(sum);
:) Output: Sum of numbers from 1 to 10: 55Nested For Loops
You can nest for loops to work with multi-dimensional data:
purna i;
purna j;
lagi(i = 1; i <= 3; i = i + 1;) {
lagi(j = 1; j <= 3; j = j + 1;) {
bhana("i = ");
bhana(i);
bhana(", j = ");
bhana(j);
bhana("\n");
}
}Important Notes
- The variable used in the for loop must be declared before the loop.
- The initialization, condition, and update parts are separated by semicolons.
- The update part must end with a semicolon.
- The for loop is equivalent to a while loop with initialization before the loop and update at the end of each iteration.
Next Steps
Now that you understand for statements in Lipi, you can learn more about: