Nested for loop c# [closed]

for (var x = 1; x < 5; x++)
{
   if (x == 4) x = 5;
   Console.Write("{0} ",x);
   for (var y = 1; y < 4; y++)
       Console.Write("{0} ", y < 3 ? x + y : 3 * (x + 1));
   Console.WriteLine();      
}

EXPLANATION:

required output is:

1 2 3 6
2 3 4 9
3 4 5 12
5 6 7 18 

So here are four rows and four columns
first column in each row is 1,2,3,5, so outer loop in x goes from 1 to 4, and first statement changes the last value of 4 to a 5.
The 2nd & 3rd columns are always just the first column incremented by one, then by one again, and finally, last 4th column is 3 times 1 + the first column. So inner loop in y just goes 1, 2, 3, and, for 2nd and 3rd column, prints the first column plus the y value (1, 2) for 2nd and 3rd column and three times 1 plus the first column for the last (4th) column.

So each row is, effectively
x, x+1, x+2, 3*(x+1)

and each row starts with x one greater than the row before it, except we skip row 4

The expression y < 3 ? x + y : 3 * (x + 1) is a ternary which has three parts, a Boolean condition, followed by a question mark (?), the value to generate when the Boolean is true, followed by a colon (:) and then the value to generate when the Boolean is false. So it reads like this:

if y is less than 3, output x+y, else output 3 times (x+1)

Another simpler option (which only uses one loop), might be:

for (var x = 2; x < 7; x++)
{
   if (x == 5) continue; // skip row 4
   Console.WriteLine("{0} {1} {2} {3} ",x-1, x, x+1, 3*x);            
}

Browse More Popular Posts

Leave a Comment