Module: (Java) Loops. 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:
 

#include <iostream>
using namespace std;
main()
{
 int i,N; // i – loop variable, N - the maximum number for which we calculate the square
 cin>> N; // input N from the keyboard
 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 << "Kvadrat chisla "<<i<<" raven " <<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 (i ++) 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 with N=0 (test #4) the program doesn't output anything, because the i<=N condition is immediately false the first time the loop is executed (1<=0 is a false condition), so the loop body is not executed at all once!