R
R
Roman Nazarkin2016-10-16 20:29:26
C++ / C#
Roman Nazarkin, 2016-10-16 20:29:26

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);

There is a task to rewrite this fragment using only one while loop. I'd like to see different solutions. So far, all that comes to mind is to add conditions to the loop and, at a certain moment, set one of the variables to zero and start counting / output from the beginning.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Bogachev, 2016-10-16
@sfi0zy

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);

PS: actually, you can still mess around with goto , but this is already too much ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question