1 Replies - 141 Views - Last Post: 25 October 2009 - 09:08 PM

#1 OliveOyl3471   User is offline

  • Everybody's crazy but me!
  • member icon

Reputation: 135
  • View blog
  • Posts: 6,581
  • Joined: 11-July 07

Print a diamond in C++

Posted 04 September 2008 - 03:10 PM

Description: This function allows a user to choose the maximum row size and prints a diamond to the screen. Note that if an even number is entered, the maximum row size will be one less than the number entered.
/* 
 * A function to print a diamond on the console 
 * while allowing the user to choose its size
 * author: OliveOyl 
 */  
  
#include <iostream>  
  
void printDiamond (int num)  
{  
    //print top half of diamond  
    for(int i = 0; i<num; i+=2)//use i+=2 instead of i++ so that the rows will  
    {//follow the format row1: 1 star, row2: 3 stars, etc.  
        for(int j=0; j<num-i; j+=2)//update j by 2 instead of 1 because we use i in our condition 
            std::cout<<" ";  
        for(int k=0; k<=i; k++)  
            std::cout<<"*";  
      std::cout<<std::endl;  
    }  
    if(num%2==0)//check if num is even  
        num-=1; //if num is even, subtract 1 from it so the rows will line up correctly  
                
    num-=2;//subtract 2 from num so that the middle row will only be printed once  
  
    //print bottom half of diamond  
   for(int i=0;i<num;i+=2)  
     {  
        for(int j=0;j<=i+2;j+=2)  
            std::cout<<" ";  
        for(int k=1;k<=num-i;k++)  
            std::cout<<"*";  
     std::cout<<std::endl;  
    }  
}  

/** EXAMPLE USAGE **/  
int main ()  
{  
    int num;
    std::cout<<"Enter a number: n";
    std::cin>>num;
    printDiamond(num);  
    std::system("Pause");
    return EXIT_SUCCESS;  
}


Is This A Good Question/Topic? 0
  • +

Replies To: Print a diamond in C++

#2 Girish Dhobe   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 0
  • Joined: 25-October 09

Re: Print a diamond in C++

Posted 25 October 2009 - 09:08 PM

thanks
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1