This is the assignment:
5.23) Write a program that prints the following diamond shape. You may use output statements that print a single asterisk (*), a single blank or a single newline. Maximize your use of repetition (with nested for statements) and minimize the number of output statements.
That's how i did it:
- Code: Select all
#include <iostream>
using namespace std;
int main()
{
int blanks_less = 4;
int blanks_plus = 1;
int astrks_less = 7;
int astrks_plus = 1;
for (int y = 1; y <= 9; y++)
{
if (y <= 4)
{
for (int x = 1; x <= blanks_less; x++)
cout << ' ';
blanks_less--;
for (int a = 1; a <= astrks_plus; a++)
cout << '*';
astrks_plus += 2;
cout << endl;
}
if (y == 5)
{
for (int a = 1; a <= 9; a++)
cout <<'*';
cout << endl;
}
if (y >= 6)
{
for (int x = 1; x <= blanks_plus; x++)
cout << ' ';
blanks_plus++;
for (int a = 1; a <= astrks_less; a++)
cout << '*';
astrks_less -= 2;
cout << endl;
}
}
char wait;
cin >> wait;
}
Then the next assignment:
5.24) Modify Exercise 5.23 to read an odd number in the range 1 to 19 to specify the number of rows in the diamond, then display a diamond of the appropriate size.
And i did it like this:
- Code: Select all
#include <iostream>
using namespace std;
int main()
{
int rows;
cout << "Enter the number of rows: ";
cin >> rows;
int blanks_less = rows - static_cast<int>(ceil(rows/2.0));
int blanks_plus = 1;
int astrks_less = rows - 2;
int astrks_plus = 1;
for (int y = 1; y <= rows; y++)
{
if (y <= static_cast<int>(floor(rows/2.0)))
{
for (int x = 1; x <= blanks_less; x++)
cout << ' ';
blanks_less--;
for (int a = 1; a <= astrks_plus; a++)
cout << '*';
astrks_plus += 2;
cout << endl;
}
if (y == static_cast<int>(ceil(rows/2.0)))
{
for (int a = 1; a <= rows; a++)
cout <<'*';
cout << endl;
}
if (y >= static_cast<int>(ceil(rows/2.0) + 1.0))
{
for (int x = 1; x <= blanks_plus; x++)
cout << ' ';
blanks_plus++;
for (int a = 1; a <= astrks_less; a++)
cout << '*';
astrks_less -= 2;
cout << endl;
}
}
char wait;
cin >> wait;
}
What you guys think about it? I mean, it did what it was supposed to do, but is it ugly? I mean, could i have made it cleaner, simpler? Thanks in advance.
