This is a code file that creates a Christmas tree pattern. I am writing the code
ID: 3626345 • Letter: T
Question
This is a code file that creates a Christmas tree pattern. I am writing the code in Visual Studio 2008 Express. I am getting the correct tree pattern based on the number of lines the user inputs (between 1 and 30). However, I still need to display the line number for each line of the tree in the DOS window. I have experiented using setw(), but then the output tree pattern would look crazy. I am wondering how I can display the line number for each line of the tree without messing up the tree.
#include
#include
using namespace std;
int main()
{
int i,j,s;
int lines;
char response = 'Y';
do//Begin outer loop.
{
do//Loop to get correct input.
{
cout << "Enter number of lines for tree (between 1 and 30): ";
cin >> lines;
}while(lines < 1 || lines > 30);
cout << endl << endl;
for (i = 1; i <= lines; i++)
{
for (j = 1; j <= lines - i; j++)
{
cout << " ";
}
for (s = 1; s <= (i * 2) - 1; s++)
{
cout << "*";
}
cout << endl;
}
cout << " Keep going?: ";//can create multiple trees.
cin >> response;
}while (response == 'Y' || response == 'y');//End outer loop.
return 0;
}
Explanation / Answer
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
int i,j,s;
int lines;
char response = 'Y';
do//Begin outer loop.
{
do//Loop to get correct input.
{
cout << "Enter number of lines for tree (between 1 and 30): ";
cin >> lines;
}while(lines < 1 || lines > 30);
cout << endl << endl;
for (i = 1; i <= lines; i++)
{
cout << i <<" ";
for (j = 1; j <= lines - i; j++)
{
cout << " ";
}
for (s = 1; s <= (i * 2) - 1; s++)
{
cout << "*";
}
cout << endl;
}
cout << " Keep going?: ";//can create multiple trees.
cin >> response;
}while (response == 'Y' || response == 'y');//End outer loop.
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.