|
-
September 30th, 2009, 07:36 AM
#2
Re: figures from nested loops question, not a homework
 Originally Posted by lanef
How did they know to set N at 3? Is that just the number of rows?
Yes, this is just the number of rows - you could also input it from program user or change it in the code to any valid(non-negative) int value.
 Originally Posted by lanef
Why isn't there a row with two asterisks in it? And another with four asterisks in it?
The outer loop is responsible of iterating over the rows while the inner loop iterates over the columns.
According to the if statement inside the inner loop -
For i == 0, the inner loop will print '*' only for j == N
For i == 1, the inner loop will print '*' for j == N-1, j == N, j == N+1
For i == 2, the inner loop will print '*' for j == N-2, j == N-1, j == N, j == N+1, j = N+2
And so on...
This is because of the if statement condition that requires the j value to be in between N-i and N+i. Since i increases by 1 on each row, the range of asterisks {N-i to N+i} increases by 2 on each row. Since in the 1st row the number of asterisks is 1, in the 2nd it will be 3, in the 3rd it will be 5 and so on.
 Originally Posted by lanef
How did they know to set the conditional for the inner loop at N * 2? Is that just the number of columns?
If you want to print a pyramid of height N where the number of asterisks on level k (level 0 would be the top of the pyramid), is equal to the number of asterisks on level k-1 plus 2 asterisks, the number of columns needed is twice the number of rows. This is simple math.
 Originally Posted by lanef
How did they know to always leave the first column blank?
Actually you could do without leaving it blank by running the inner loop from start index 1 and not 0 (see change marked in red):
Code:
main()
{
constant N = 3;
for (int i = 0; i < N; i++)
{
for (int j = 1; j < N * 2; j++)
{
if (j < N-i || j > N+i) print (' '); // print a blank
else print ('*'); // print a star
}
print('\n');
}
}
 Originally Posted by lanef
How did they know how many rows and columns make an isoceles triangle (unless they were given the image as part of the requirements)?
Refer to my answer to your 3rd question.
 Originally Posted by lanef
How did they know to compare j to be less than N-i OR greater than N+i?
Refer to my answer to your 2nd question.
Regards,
Zachm
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|