Write a program that prints an oval using the character \'*\'. The user will ent
ID: 672766 • Letter: W
Question
Write a program that prints an oval using the character '*'. The user will enter the
number of '*'s on the middle row and then the number of rows above and below the middle
row. For instance, an oval with 16 '*"s in the middle row and 2 rows above and below looks
like:
************
**************
****************
**************
************
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
// Declare and initialize variables
int middle_row;
int rows;
// Repeatedly prompt for middle row size until valid value is entered
cout << "Enter size of the middle row: ";
cin >> middle_row;
while (middle_row < 3)
{
cout << "Size of the middle row must be at least three." << endl;
cout << "Enter size of the middle row again: ";
cin >> middle_row;
}
// Repeatedly prompt for the number of rows until valid value is entered
cout << "Enter number of rows: ";
cin >> rows;
while (rows < 0 || (middle_row-2*rows) < 2)
{
cout << "Invalid number of rows." << endl;
cout << "Enter number of rows again: ";
cin >> rows;
}
cout << endl;
// Print the oval
return 0;
}
Explanation / Answer
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
// Declare and initialize variables
int middle_row;
int rows;
// Repeatedly prompt for middle row size until valid value is entered
cout << "Enter size of the middle row: ";
cin >> middle_row;
while (middle_row < 3)
{
cout << "Size of the middle row must be at least three." << endl;
cout << "Enter size of the middle row again: ";
cin >> middle_row;
}
// Repeatedly prompt for the number of rows until valid value is entered
cout << "Enter number of rows: ";
cin >> rows;
while (rows < 0 || (middle_row-2*rows) < 2)
{
cout << "Invalid number of rows." << endl;
cout << "Enter number of rows again: ";
cin >> rows;
}
cout << endl;
// Print the oval
for(int i = -rows ; i <= rows ; i++){
int diff = ( i > 0 ? i : -i);
for(int j = 0 ; j < diff; j++ ) cout << " " ;
for(int j = diff; j < middle_row; j++) cout << "*";
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.