0

Explain this pyramid code(Dumb it down)!!!!!11

static void DrawPyramid(int n) { for (int i = 1; i <= n; i++) { for (int j = i; j <= n; j++) { Console.Write(" "); } for (int k = 1; k <= 2 * i - 1; k++) { Console.Write("*" + " "); } Console.WriteLine(); } }

5th Feb 2017, 5:45 AM
Christopher
2 Answers
+ 2
static void DrawPyramid(int n) // here n decides how large the pyramid is { for (int i = 1; i <= n; i++) // this for loop ask if i is smaller or equal to n example: if n is 6 it would ask 1<=6 since this is true it continues to the next command and increments i by 1 { for (int j = i; j <= n; j++) // this asks if j which is equal i is smaller or equal to n example: i=j 1=j 1<=6 is true therefore it goes to the next command { Console.Write(" "); //since the second loop went trough it will execute this command which just does a double space if you want you can replace the double space with "//" or "12" to more easily understand what it does. And this concludes the loop since the curly bracket } ends it and it goes back to the beginning of the second loop meaning for (int j = i; j <= n; j++) and this will continue this command until it reaches the number 6. so the first line of the output if you replaced it with "12" would look like this 121212121212 after it is written 6 times it will reach its and it will continues to the next part } for (int k = 1; k <= 2 * i - 1; k++) //this asks if k is smaller the 2 multiplied by i minus 1 so 1<=2*1 - 0 which would result in 1<=2 since this is true wit will continue to the next command { Console.Write("*" + " "); //This will produce a * and an empty space if you replace it with "1" it would output *1. Since the program hasn't skipped to the next line the output would be added after the fist output so it would look like this: 1212121212*1 } Console.WriteLine(); // This just makes it go to the next line in output and ends the loop. After the loop is ended it goes back to the beginning meaning for (int i = 1; i <= n; i++) but this time i=2 since it was incremented so 2<=6 so the loop starts again until it reaches its end. } } https://code.sololearn.com/cLvcfuwNJ8gg/#cs here is the code so you can see the example of the "12" and "1" so you might imagine it easier. Hope that helps.
7th Feb 2017, 11:42 AM
Saơo Jovanović
0
TBH i still don't understand it for some reason, i'm having a problem processing how for loops work in general so please help
10th Jul 2020, 5:05 PM
Yousif Alsewaidi
Yousif Alsewaidi - avatar