NESTED LOOPS IN C and C++
Loops or cycles are commands whose role is to repeat one or more other commands a certain number of times. Those repeating statements are written in the body of the for loop. It can be any other command, and therefore a new for command.
Let us now look at the next task:
Let us now look at the next task:
Example 1: Print the first 100 natural numbers in 10 rows and 10 columns.
This task can be done without nested loops. See example on Loops in C/C++ examples
However, we will show here how the same example can be done using nested loops.
However, we will show here how the same example can be done using nested loops.
To print a number, we use the printf command:
printf("%2d",number);
in C++ language
cout << number << " ";
To print one line, we use a for loop in which we will mark the control variable with the letter j and this will represent the row number of the column of the matrix to be printed:
for(int j=1; j<10; j++)
{
printf("/n");
{
printf("%2d",number);
}printf("/n");
in C++ language
for(int j=1; j<=10; j++)
{
cout << endl;
{
cout << broj << " ";
}cout << endl;
This will print 1 line. This should now be repeated 10 times, for each row. For that we will use another loop, so that the previous statements are in the body of that loop, ie between the curly brackets. The control variable of the outer loop that we'll label with i will be the line number minus 1, so it changes from 0 to 9.
The number variable should be associated with both j and i as follows:
number = 10 * i + j;
When the first row is printed, i=0, so numbers are printed that only depend on the current column j, so that 1 is printed in the 1st column, 2 in the 2nd column, etc.
In the next row, values that are greater than the values of the previous row by 1*10 are printed, so that we get 11, 12, 13,...
In each next row, the numbers are 10 higher than in the previous one.
The number variable should be associated with both j and i as follows:
number = 10 * i + j;
When the first row is printed, i=0, so numbers are printed that only depend on the current column j, so that 1 is printed in the 1st column, 2 in the 2nd column, etc.
In the next row, values that are greater than the values of the previous row by 1*10 are printed, so that we get 11, 12, 13,...
In each next row, the numbers are 10 higher than in the previous one.
int number;
for(int i=0; i<10; i++)
{
for(int i=0; i<10; i++)
{
for(int j=1; j<=10; j++)
{
printf("/n");
}{
number=10*i+j;
printf("%2d",number);
}printf("%2d",number);
printf("/n");
Or in C++ programming language:
int number;
for(int i=0; i<10; i++)
{
for(int i=0; i<10; i++)
{
for(int j=1; j<=10; j++)
{
cout << endl;
}{
number=10*i+j;
cout << number << " ";
}cout << number << " ";
cout << endl;
More examples in this area can be found on the web page: Nested loops in C/C++ examples
Previous
|< Loops in C/C++ basic |
Next
Arrays in C/C++-basic >| |