-
drawing a diamond
hello i was wondering if anyone could get me started on how to draw a diamond. Its parameters are inclusive to odd numbers.
for example, the size of the diamond (odd, between 1-19)
So if the program asks, "Enter a size of daimond 1-19"
and the user inputs 9, this is what the picture would look like:
( _ means spacing)
*
*_*_*
*_*_*_*_*
*_*_*_*_*_*_*
*_*_*_*_*_*_*_*_*
*_*_*_*_*_*_ *
*_*_*_*_*
*_*_*
*
Any help would be greatly appreciated. Thank you
-
I'm sure there are prettier ways to do it but this gets it done
Code:
#include "stdafx.h"
#include <windows.h>
#include <iostream>
using namespace std;
void Print( int, int );
int main()
{
int nEnd;
cout << "Please enter odd 1-19: " << flush;
cin >> nEnd;
Print( 1, nEnd );
return 0;
}
void Print( int nStart, int nFinish )
{
//only print for odd numbers
if( nStart%2 )
{
//for every odd number go to start (start is a bad name... oh well)
for( int i = 1; i <= nStart;i++ )
{
cout << "* ";
}
cout << endl;
}
//recurse and grow the start
//until its gets to the end
if( nStart < nFinish )
Print( ++nStart, nFinish );
//as we unwind the stack
//only allow even numbers
if( !( nStart%2 ) )
{
//even numbers and j<nStart (start-1) will keep us 2 less than above
for( int j = 1; j < nStart;j++ )
{
cout << "* ";
}
cout << endl;
}
}
-
The picture you gave is a triangle, not a diamond. Anyway, here's some code for outputting various triangles from an earlier assignment I had. The triangles are preset sizes, but you can work off this code if it helps.
Code:
// Triangle printing
//
#include <iostream>
using std::cout;
using std::endl;
int main()
{
for (int a = 1; a <= 8; a++)
{
for (int i = 1; i <= a; i++)
cout << "*";
cout << endl;
}
cout << endl;
for (a = 8; a >= 1; a--)
{
for ( int i = 1; i <= a; i++)
cout << "*";
cout << endl;
}
cout << endl;
for (a = 1; a <= 8; a++)
{
for (int i = 8; i > a; i--)
cout << " ";
for (int j = 1; j <= i; j++)
cout <<"*";
cout << endl;
}
cout << endl;
for (a = 1; a <= 8; a++)
{
for (int i = 1; i < a; i++)
cout << " ";
for (int j = 8; j >= i; j--)
cout <<"*";
cout << endl;
}
cout << endl;
cout << endl;
return 0;
}
-
You know you two are doing this guy no favours...... The purpose of computer science courses isn't to get other people to do it for you.For christs sake... give the guy a few pointers but dont do his homework for him!
-
Well, I thought about that, but the code won't do the job he posted. It would have to be modified to print his diagram. Maybe it was too much though...
-
Excellent point. From now on just hints.