Hello, I'm working on a Pyramid Problem. I got it working, but it took a huge amount of time. How should I tackle a problem like this in the future. I don't think it should have taken me 4 hours but I had the most horrible time getting the formatting correct.

Here's my finished code. My initial thinking was to find the total number of spaces needed for a set number of lines, divide it by half and then add one to align the X's correctly but I got hung up on calculating numspaces. I figured it out experimentally but the process took a lot of rebuilding and time and I know there's gotta be a better way. What I don't understand is why I needed to multiply the number of lines by 2 and add 2 to get it aligning correctly. The way I figured it out was by doing a for loop adding up num_x for several varying number of lines and figuring out the conversion for lines to space. Any helps much appreciated.

#include <iostream>
#include <iomanip>
using namespace std;

int main(int argc, char* argv)
{

int numlines=20;
int numspaces=numlines*2+2;
int num_x=1;

for(int row=0; row<numlines; row++)
{
	for (int j=0; j<((numspaces - num_x+1)/2); j++)
		cout << " ";
	for (int i=0; i<(num_x); i++)
		cout << "X";
	num_x+=2;
	cout << endl;
}
	
	system("PAUSE");
return 0;
}

Draw the the pattern on paper. Analyze the numbers you need:
1) for each given line number
2) how many leading spaces
3) how many characters
4) how many trailing spaces
Look for a numerical pattern that can be programmed.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.