Module: cycles. Loop with parameter (for)


Problem

10/17

Header of the for loop - repeating N -times

Theory Click to read/hide

All programs with a for loop that we have written so far cannot be called universal. Because we set the number of repetitions of the loop body ourselves. 
But what if the number of repetitions depends on some other value? For example, the user himself wants to set the number of repetitions of the cycle.
What to do in this case?
Everything is very simple. Instead of numeric start and end values, we can use any variables that can be calculated or set by the user.

For example, we need to display the squares of numbers from 1 to n, where the value of the variable n is entered from the keyboard by the user.
The program will look like this:
 

var i, n :integer; // i – loop variable, n - the maximum number for which we calculate the square
begin
 read(n); // input n from the keyboard
 for i := 1 to n do // loop: for all i from 1 to n - variable i will sequentially take values ​​from 1 to n
  writeln('Kvadrat chisla ', i, ' raven ', i * i); // Outputting the square of a number in a specific format and moving to a new line
end.

When entering the loop, the statement i := 1 is executed, and then the variable i is incremented by one (to) with each step. The loop is executed while the condition i <= n is true. In the body of the loop, the only output statement prints the number itself and its square on the screen according to the specified format.
For squaring or other low exponents, it's better to use multiplication.

Run the program and see the result of its work with different values ​​of the variable n.

Problem

Run the program for execution, see the result of its work with different values ​​of the variable n
Analyze the output in the program test result window

Note that for n=0 (test #4) the program doesn't output anything because 1 is immediately greater than 0, so the loop body is never executed!