Answer the question
In order to leave comments, you need to log in
How to rewrite a nested for loop with a single while loop?
Greetings!
There is a code snippet in C:
for(int j = 1; j < 3; j++)
for(int i = 1; i < j+1; i++)
printf("%d ", i);
Answer the question
In order to leave comments, you need to log in
Well, in general, it comes to your mind correctly, but the option with two cycles, given initially, looks more understandable or something, more readable. Well, only the counters can be renamed (usually i, j, k are used in nested loops in this order - the reverse order is confusing).
int i = 1, j = 1;
do {
std::cout << j;
if (++j > i) {
j = 1;
i++;
}
} while (i < 3);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question