Diamond

This is a discussion on Diamond within the C++ Programming forums, part of the General Programming Boards category; Hi there! I wrote this program as my self teaching exercise, to print a diamond pattern. It works fine, but ...

  1. #1
    Registered User
    Join Date
    Sep 2002
    Posts
    8

    Question Diamond

    Hi there!

    I wrote this program as my self teaching exercise, to print a diamond pattern. It works fine, but I've got a feeling that there must be a better way to do this, and to optimise the code. Could someone show me, please? Many thanks in anticipation.

    Code:
    //print diamond using *
    #include <iostream.h>
    #include <conio.h>
    
    int main()
    {
    	int t, b, s, n;
    
    	do
    	{
    		clrscr();
    		cout << "Enter integer number: ";
    		cin >> n;
    		n += 1;
    		n /= 2;
    
    		//top of diamond or pyramid
    		for (t = 1; t <= n; t++)
    		{
    			for (b = n; b >= t; b--)
    				cout << " ";
    				for (s = 1; s <= (t * 2 - 1); s++)
    					cout << "*";
    			cout << endl;
    		}
    		//bottom of diamond
    		for (t = 1; t <= n - 1; t++)
    		{
    			for (b = 1; b <= t + 1; b++)
    				cout << " ";
    				for (s = 1; s <= n * 2 - (t * 2 + 1); s++)
    					cout << "*";
    			cout << endl;
    		}
    		cout << "Any key again, Esc to quit.";
    	} while (getch()!=27);
    	return 0;
    }

  2. #2
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    n += 1; can be written as n++;

    And your inner for loops have a weird hiearchy:
    Code:
    for (b = n; b >= t; b--)
       cout << " ";
       for (s = 1; s <= (t * 2 - 1); s++)
          cout << "*";
    Both for-loops should be on the same level.

    Except for those, the program looks fine.
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Simple Blackjack Program
    By saber1357 in forum C Programming
    Replies: 1
    Last Post: 03-28-2009, 04:19 PM
  2. Bitwise Unwanted Output
    By pobri19 in forum C++ Programming
    Replies: 4
    Last Post: 09-15-2008, 05:07 AM
  3. Diamond loopy
    By swgh in forum C++ Programming
    Replies: 2
    Last Post: 09-24-2007, 10:10 AM
  4. Red Diamond - Little bit of a preview
    By MidnightlyCoder in forum Game Programming
    Replies: 6
    Last Post: 05-19-2006, 11:00 AM
  5. making a diamond using functions
    By Nikisha in forum C++ Programming
    Replies: 4
    Last Post: 03-30-2003, 09:05 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21