Thread: designing algorithms

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    budding software engineer luigi40's Avatar
    Join Date
    Jun 2004
    Location
    South Coast UK
    Posts
    61

    designing algorithms

    this code below has been copied and annotated from the C++ section,

    Code:
    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();
    			}
    			
    	}
    	
    }
    this program prints a diamond shape, my question is how does one work out the these 2 loops

    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();
    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 <= outer * 2 - (t * 2 + 1); star++)//7, 5, 3, 1
    or is there a method to this ?

    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?
    Last edited by luigi40; 11-22-2005 at 02:14 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sorting algorithms, worst-case input
    By Leftos in forum C++ Programming
    Replies: 17
    Last Post: 06-15-2009, 01:33 PM
  2. Replies: 5
    Last Post: 04-26-2007, 08:50 AM
  3. page replacement algorithms?
    By Extrovert in forum C++ Programming
    Replies: 1
    Last Post: 08-19-2005, 12:53 AM
  4. relative strength of encryption algorithms (blowfish, des, rinjdael...)
    By duck-billed platypus in forum A Brief History of Cprogramming.com
    Replies: 3
    Last Post: 12-30-2001, 04:20 PM