Module: (C++) Loops. Loop with parameter (for)


Problem

10/17

Header of the for loop - repeating N -times

Theory Click to read/hide

Repeat N times

All programs with a for loop that we have written so far cannot be called universal. Because we set ourselves the number of repetitions of the loop body. 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:
  #include <iostream> using namespace std; main() { int i,N; // i – loop variable, N - the maximum number for which we calculate the square cin>> N; for ( i = 1; i <= N; i ++) // loop: for all i from 1 to N. Variable i will sequentially take values ​​from 1 to N { cout << "Square number "<<i<<" is" <<i*i<<"\n"; // Outputting the square of a number in a specific format and moving to a new line } } When entering the loop, the statement i = 1 is executed, and then the variable i is incremented by one with each step (i ++). 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.

Note that when N=0 (test #4) the program does not output anything, because the condition i <= N is immediately false the first time the loop is executed ( 1<=0 is a false condition), so the body of the loop is never executed!