Hello , i was doing an exercise in book which asked to draw a diamond shape by displaying '*' using nested for loops. It took me quite a while to come up with a way to reverse the pyramid , and complete this exercise. So i was hoping some one can take a look at this code and let me know what they would have done different. Thanks. Again sorry for posting on multiple forums i just value responses i get and hopefully learn something. Thanks.

//draws a diamond shape ex
/* 

     *
    ***
   *****
    ***
	 *
*/


#include "stdafx.h"
#include <iostream>


using namespace std;

int main(){

	int nRow, nColumn, nDiamond = 8, nCenter, nColumnSize;
	
	nCenter = nDiamond / 2;

	for ( nRow = 0; nRow <= nDiamond; nRow++ ){

		nColumnSize = nRow <= nCenter ? nRow + nCenter : nColumnSize - (nCenter / nCenter);

		for ( nColumn = 0; nColumn <= nColumnSize; nColumn++ ){ 

			//checking if we at center 
			if ( nRow <= nCenter ) {

				if ( nCenter - nRow > nColumn ) 
					cout << ' ';
				else
					cout << '*';
			//reversing 
			}else if ( nRow - nCenter > nColumn )
					cout << ' ';
			else
					cout << '*';
		}// end columns

		cout << endl;

	} //end rows

	return 0;
}

Your code if not particularly efficient, since you do a lot of checking to see if you're in the centre, both vertically and horizontally. In fact this is all determined right from the beginning by the dimensions of the diamond that you want to print. So, you can just use some nested for loops, without any if statements, like this

#include <iostream>

int main()
{
    /* Get the target size */
    const int size = 7;

    /* the middle is half this (makes all diamonds and odd number in width/height */
    const int centre = size/2;

    /* Print out the top half */
    for(int i = 0; i < centre; i++){
        for(int j = 0; j < centre - i; j++)   std::cout << ' ';
        for(int j = 0; j < 2*i + 1; j++)      std::cout << '*';
        for(int j = 0; j < centre - i; j++)   std::cout << ' ';
        std::cout << std::endl;
    }

    /* Print out the bottom half */
    for(int i = centre; i >= 0; i--){
        for(int j = 0; j < centre - i; j++)   std::cout << ' ';
        for(int j = 0; j < 2*i + 1; j++)      std::cout << '*';
        for(int j = 0; j < centre - i; j++)   std::cout << ' ';
        std::cout << std::endl;
    }

    return 0;
}

In general, I try to avoid having if statements inside deeply nested loops, since it can really affect the speed that the program runs at. Not to important in this case, but always worth practising :)

This article has been dead for over six months. Start a new discussion instead.