This is a nested loop, k goes from 1 to i, as you can see in line 13 i goes from 1 to 7. Each time i iterates the loop inside (line 14) is executed and k goes from 1 to i's value at that particular loop.
Thank you so much, what I am confused is that it is k++, right, k from 1 to 2, from 2 to 3, how can it be from 1 to 12? that's k+11...., then 12 to 123?
#include <iostream>
int main()
{
for(int i = 1; i <= 7; i++)
{
std::cout << "i = " << i << " k = ";
for (int k = 1; k <= i; k++)
{
std::cout << k << '-';
}
std::cout << " j = ";
for (int j = 7 - i; j >= 1; j--)
{
std::cout << j << '-';
}
std::cout << '\n';
}
return 0;
}
i = 1 k = 1- j = 6-5-4-3-2-1-
i = 2 k = 1-2- j = 5-4-3-2-1-
i = 3 k = 1-2-3- j = 4-3-2-1-
i = 4 k = 1-2-3-4- j = 3-2-1-
i = 5 k = 1-2-3-4-5- j = 2-1-
i = 6 k = 1-2-3-4-5-6- j = 1-
i = 7 k = 1-2-3-4-5-6-7- j =
Program ended with exit code: 0
In the first for loop (i), the number goes on from 1 to 2, i=1 changed to i=2, just one action.
for(int i = 1; i <= 2; i++), why doesn't this loop output i=1, then i=12...
but for the second for loop (k), why the previous existing old number are kept (two actions), instead of going from 1 to 2, it goes from 1, to 1-2-, what happens in the (k) loop when (i ) goes from 1 to 2?
@Kevin S
The best way to explain this is for you to use a pencil and paper and follow the recipe line by line.
If you compare the layout of the program in my version to that in the original you can see straight away mine is clearer. Also by putting in the additional separator characters what appear to be the number 12 is actually two separate numbers 1 and then 2. Both of these are tricks used to deliberately obscure a very simple nested loop arrangement.
I can fully understand the combination of 1 and 2 to make them appearing like 12.
The place where I don't understand is why in the k loop (second loop), it keeps adding up, 1, then 1+2, but the first loop jumps from 1 to 2 (without 1 this time).