this code below has been copied and annotated from the C++ section,
this program prints a diamond shape, my question is how does one work out the these 2 loopsCode:using System; class Test { static void Main(string[] args) { int t, space, star; int outer=5;//set final value of control variable //top of diamond - outer loop for (t = 1; t <= outer; t++)//control variable t active while { //less than or equal to outer for (space = outer; space >= t; space--)//set control variable Console.Write(' ');//space to outer value //while space is greater/or equal to t print space for (star = 1; star <= (t * 2 - 1); star++) Console.Write('*'); Console.WriteLine(); } //bottom of diamond for (t = 1; t <= outer - 1; t++) { for (space = 1; space <= t + 1; space++)//while control variable Console.Write(' ');//space is less than or equal to outer //control var t + 1 print space for (star = 1; star <= outer * 2 - (t * 2 + 1); star++)//7, 5, 3, 1 Console.Write('*'); Console.WriteLine(); } } }
previous to seeing this code i had written down a simple flowchart depicting all different stages for each line, as well writing out the sequence of numbers for stars and spaces. is it purely a maths calculation to work out the line...Code:for (star = 1; star <= (t * 2 - 1); star++) Console.Write('*'); Console.WriteLine(); for (star = 1; star <= outer * 2 - (t * 2 + 1); star++)//7, 5, 3, 1 Console.Write('*'); Console.WriteLine();
or is there a method to this ?Code:for (star = 1; star <= outer * 2 - (t * 2 + 1); star++)//7, 5, 3, 1
i would have taken forever to get to this without seeing this code, i guess some people are quick problem solvers or they have solved many similar problems
what are your thoughts?



LinkBack URL
About LinkBacks


