user10066522
user10066522

Reputation:

How to modify a for loop?

Just a side note, this is homework help, so I'll try my best to create a minimal reproducible example that fits within the community guidelines.

Problem

After a for loop has lopped over all the elements in an array, is there a way to reset the for loop, but this time with the starting value at a different number?

Explanation

Let's suppose you have a simple for loop:

for (int a = 0; a < 5; ++a)
    std::cout << a << " ";

Now let's suppose it finished lopping over the values of an array. No problem there. However, is there a way to reset the for loop so it loops over the array again, but this time, it doesn't start at a = 0, but rather at a = 1? And continue this pattern so that the third iteration with start at a = 2 and so on?

// first loop
for (int a = 0; a < 5; ++a)
    std::cout << a << " ";

// second loop
for (int a = 1; a < 5; ++a)
    std::cout << a << " ";

// third loop
for (int a = 2; a < 5; ++a)
    std::cout << a << " ";

// fourth loop
for (int a = 3; a < 5; ++a)
    std::cout << a << " ";

// fifth loop
for (int a = 4; a < 5; ++a)
    std::cout << a << " ";

So the expected output should be...

0 1 2 3 4 1 2 3 4 2 3 4 3 4 4

And just to be clear, I don't want to create 5 separate for loops, but rather to simulate the effects of five separate for loops (for all I know, it could be an array of 100 integers, and I wouldn't want to create 100 separate for loops).

What I have tried

I was perhaps thinking of creating a for loop inside a for loop, and so far it's looking good...

for (int a = 5; a > 0; --a)
{
  for (int b = 0; b < a; ++b)
  {
    std::cout << b << " ";
  }
}

But, instead of taking away the first number, it takes away the last, so the output looked like this:

0 1 2 3 4 0 1 2 3 0 1 2 0 1 0

Am I on the right track here? What am I missing?

Upvotes: 0

Views: 223

Answers (1)

KamilCuk
KamilCuk

Reputation: 140970

Start the inner loop from the index of the outer loop.

for (int b = 0; b < 5; ++b) {
   for (int a = b; a < 5; ++a) {
       std::cout << a << ' ';
    }
 }

Upvotes: 2

Related Questions