lanef
September 30th, 2009, 12:06 AM
Hi,
I'm embarassed to ask this but I've gotta. I came across an example in an algorithms book and for the life of me I can't figure out how they got the answer.
Problem: Draw an isoceles triangle using asterisks (afaik this is the only requirement) using nested loops.
Final output: (I don't know if this was given before hand or not, it's just all thrown together in the book, I guess maybe they had to give the expected final image first (I'm shortening it but the song remains the same).
---*--
--***- Where - represents a blank and * makes the triangle visible
-*****
Solution: (written in c-esque)
main()
{
constant N = 3;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N * 2; j++)
{
if (j < N-i || j > N+i) print (' '); // print a blank
else print ('*'); // print a star
}
print('\n');
}
}// end main()
Questions:
How did they know to set N at 3? Is that just the number of rows?
Why isn't there a row with two asterisks in it? And another with four asterisks in it?
How did they know to set the conditional for the inner loop at N * 2? Is that just the number of columns?
How did they know to always leave the first column blank?
How did they know how many rows and columns make an isoceles triangle (unless they were given the image as part of the requirements)?
How did they know to compare j to be less than N-i OR greater than N+i?
Thank you for your time and patience and if you will help explain this to me I'd really appreciate it.
Be Well,
lanef
I'm embarassed to ask this but I've gotta. I came across an example in an algorithms book and for the life of me I can't figure out how they got the answer.
Problem: Draw an isoceles triangle using asterisks (afaik this is the only requirement) using nested loops.
Final output: (I don't know if this was given before hand or not, it's just all thrown together in the book, I guess maybe they had to give the expected final image first (I'm shortening it but the song remains the same).
---*--
--***- Where - represents a blank and * makes the triangle visible
-*****
Solution: (written in c-esque)
main()
{
constant N = 3;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N * 2; j++)
{
if (j < N-i || j > N+i) print (' '); // print a blank
else print ('*'); // print a star
}
print('\n');
}
}// end main()
Questions:
How did they know to set N at 3? Is that just the number of rows?
Why isn't there a row with two asterisks in it? And another with four asterisks in it?
How did they know to set the conditional for the inner loop at N * 2? Is that just the number of columns?
How did they know to always leave the first column blank?
How did they know how many rows and columns make an isoceles triangle (unless they were given the image as part of the requirements)?
How did they know to compare j to be less than N-i OR greater than N+i?
Thank you for your time and patience and if you will help explain this to me I'd really appreciate it.
Be Well,
lanef