drawing a rhombus
Dec 11, 2015 at 9:10am UTC
I have drawn a rhombus but i think this program is a little bit complicated. Can I have other methods to make it simple? Also, I found that there were some problem when the number of line is an even number. Does a rhombus have an even number line?
Here is my code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
// This program is about drawing a rhombus.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int number;
cout << "Enter a positive integer number: " ;
cin >> number;
if (number >= 5 && number <= 20)
{
int i = 1;
for (int k = 0; k < (number / 2); k++)
{
for (int j = 1; j <= (number / 2) - k; j++)
{
cout << " " ;
}
for (int j = 1; j <= i + k; j++)
{
cout << "*" ;
}
i = i + 1;
cout << endl;
}
if (i - 1 == number / 2)
{
for (int j = 1; j <= number; j++)
{
cout << "*" ;
}
cout << endl;
}
for (int k = 1; k <= (number / 2); k++)
{
for (int j = 1; j <= k; j++)
{
cout << " " ;
}
for (int j = 1; j <= number - (2 * k); j++)
{
cout << "*" ;
}
cout << endl;
}
}
else
cout << "The number is excluded" << endl;
return 0;
}
Last edited on Dec 11, 2015 at 9:11am UTC
Dec 11, 2015 at 1:13pm UTC
Start with a function that prints a character N times. That way you can get rid of all the inner loops:
1 2 3 4 5 6
void repeatChars(char ch, int times)
{
for (int i=0; i<times; ++i) {
cout << ch;
}
}
Then recognize that the bottom half can be printed exactly the same as the top half, just with the loop iterator going down instead of up:
1 2 3 4 5 6 7 8 9 10 11 12 13
if (number >= 5 && number <= 20) {
for (int k = 0; k < (number / 2); k++) {
repeatChars(' ' , number/2 - k);
repeatChars('*' , 2*k+1);
cout << endl;
}
for (int k = number/2; k >= 0; --k) {
repeatChars(' ' , number/2 - k);
repeatChars('*' , 2*k+1);
cout << endl;
}
}
Now notice that what's inside the loops is identical. So write another function that does that part (maybe call it printLine and use it.
Topic archived. No new replies allowed.