/*
* 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;
}
Print a diamond in C++
Page 1 of 11 Replies - 141 Views - Last Post: 25 October 2009 - 09:08 PM
#1
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.
Replies To: Print a diamond in C++
Page 1 of 1

New Topic/Question
Reply



MultiQuote



|