Home > Software engineering >  How to understand the logic of this question?
How to understand the logic of this question?

Time:09-01

Task:

Scan 2 numbers outerNumber and innerNumber. Iterate from [0, outerNumber). Inside that loop, iterate from [0, innerNumber). In the inner iteration print the sum of both the iterators.

Note:

[x, y] means all numbers from x to y including both x and y.
[x, y) means all numbers from x to y excluding y.
(x, y] means all numbers from x to y excluding x.
(x, y) means all numbers from x to y excluding both x and y.
Sample Input:
3 5
Expected Output:
0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
Explanation:
outerIterator=0, innerIterator=0 → 0 0 = 0
outerIterator=0, innerIterator=1 → 0 1 = 1
outerIterator=0, innerIterator=2 → 0 2 = 2
outerIterator=0, innerIterator=3 → 0 3 = 3
outerIterator=0, innerIterator=4 → 0 4 = 4
outerIterator=1, innerIterator=0 → 1 0 = 1
outerIterator=1, innerIterator=1 → 1 1 = 2
outerIterator=1, innerIterator=2 → 1 2 = 3
outerIterator=1, innerIterator=3 → 1 3 = 4
outerIterator=1, innerIterator=4 → 1 4 = 5
outerIterator=2, innerIterator=0 → 2 0 = 2
outerIterator=2, innerIterator=1 → 2 1 = 3
outerIterator=2, innerIterator=2 → 2 2 = 4
outerIterator=2, innerIterator=3 → 2 3 = 5
outerIterator=2, innerIterator=4 → 2 4 = 6//

This is problem statement of the code and below that explanantion is given, but still I didn't understand how the output is coming.

I would be keen to learn how zeros, 1 and 2 are coming 5 times in Outeriterator and same in InnerIterator

CodePudding user response:

Simply, it's nested loop with both outer and inner numbers as the range for both loops. You can implement it easily as:

for(out = 0; out < outerNumber; out  ){
  for(in = 0; in < innerNumber; in  ){
    printf("%d ",out   in);
  }
  printf("\n");
}

CodePudding user response:

Outer is [0,3), so 0,1,2 is the amount of iterations.

Inner is [0,5), so 0,1,2,3,4 iterations.

Each value from outer requires you to run all the inner values once, so the first time for outer = 0 you will have 0,1,2,3,4 because 0 [0,5) is 0 0, 0 1, 0 2, 0 3, 0 4.

For outer = 1 you will do the same but add 1 instead of 0.

For outer = 2, same thing 2 0,2 1,2 2,2 3,2 4.

In code should be something close to this:

for (i = 0 ; i<3 ; i  ){

    for (x = 0; x<5; x  ){

        printf i x;
    }

}

Best of luck to you

  • Related