0

The Code below gives the output of reverse diagonal values in a 2d Array. Output is:

3,5,7

int[,] array2d2 = { 
    {1,2,3},
    {4,5,6},
    {7,8,9} 
};

int i = 0;
while (i <= 2)
{
    for (int j = 2; j >= 0; j--)
    {
        Console.WriteLine(array2d2[i,j]);
        i++;
    }
}

If my understanding is right, the increment operator(i) in the nested for loop, breaks the for loop by moving to the while loop and increment it by 1 and then continue the iteration. It already gave the output I wanted. My question, Is this the right way or my understanding is wrong?
I'm a beginner in C#.

Rafalon
  • 4,450
  • 2
  • 16
  • 30
Depak
  • 147
  • 6
  • 2
    What about simply `for (int j = 2; j >= 0; j--) { Console.WriteLine(array2d2[2-j, j]); }`? – ProgrammingLlama May 17 '21 at 06:34
  • The specific topic of breaking out of a nested loop and the containing loop has been [covered extenseively](https://stackoverflow.com/questions/324831/breaking-out-of-a-nested-loop) and probably doesn't need to be rehashed here. – ProgrammingLlama May 17 '21 at 06:34
  • 2
    The `while` here is totally unnecessary (try to remove it and you'll have the same result) – Rafalon May 17 '21 at 06:38
  • Explanation: when entering the `while`, `i==0`, and when you leave the `for`, `i==3`, so your `while(i<=2)` will always only be entered once. There's no reason to keep a loop when you know for sure it will always only be entered once – Rafalon May 17 '21 at 06:45
  • 1
    That condition in the `while` doesn't break the loop *immediately* when the condition is met. You could say that the code is executed line-by-line, and only when control reaches that while-condition again, is it evaluated and may break out of the loop. The for-statement has to run to completion for that to happen. – Hans Kesting May 17 '21 at 06:56

1 Answers1

1

The while loop is redundant. It only iterates once because the value of i causes its test to fail after the first iteration. Therefore the same result would be given by only using the for loop by itself.

If the while condition caused it to iterate more than once, the for loop would iterate three times on every iteration of the while loop.

Peter Dongan
  • 1,762
  • 12
  • 17