Sign in to follow this  
phil67rpg

triangle question

Recommended Posts

I am brushing up on my c++ by reading a book and doing exercises. My problem is that I am able to print out:
X
XX
XXX
XXXX
XXXXX

but I want to print out:
X
XXX
XXXXX
XXXXXXX

here is the code I am using
int main()
{
	for(int i=1; i<=5; i++)
	{
		for(int j=1; j <= i; j++)
		{
		cout << "X"; 
		}
		
		cout << endl;
	}
	cout << endl;
	system("pause");

	return 0; 
}
I know this is very simple but I need a little hint.
I have also googled this but I cant find a simple answer.

Share this post


Link to post
Share on other sites

You need to print out the correct number of spaces before you start printing out X's. Since it's an exercise I won't straight out give you the answer, but here's a hint: its got something to do with the row number you are printing and the total number of rows there are. Another hint: you are going to need to have 2 loops inside the "each row" loop.

 

Make sure that the number of rows to print out occurs exactly once in the code as well (have a local variable numrows inside main which you initialise with the number of rows you want to print).

Share this post


Link to post
Share on other sites

At the moment you're incrementing by one each loop but the pattern adds two Xs each time.

 

One possible solution below the fold.

 

[spoiler]

int main()
{
    int times_to_loop = 10;
    int longest_line = times_to_loop * 2;

    for(int i = 0, j = 1; i < times_to_loop; i++, j += 2)
    {
        int padding = (longest_line - j) / 2;
        cout << string(padding, ' ') << string(j, 'x') << endl;
    }

    system("pause");
    return 0;
}

[/spoiler]

 

Edit #2: Corrected the example to meet the triangle requirement which I missed.

Edited by Indifferent

Share this post


Link to post
Share on other sites

wow this programming stuff sure is challenging, is there a certain way of thinking about programming

There are lots of ways smile.png

Personally i tend to break things down into as small pieces as possible.

the triangle should look like this: (- is a space)

----X
---XXX
--XXXXX
-XXXXXXX
XXXXXXXXX

so the first row (row 0) has 4 spaces and 1 X
second row has 3 spaces and 3 X
third row has 2 spaces and 5 X
fifth row(row 4) has 0 spaces and 9 X
etc.

We got a pattern here, what is the pattern ? (If you can describe the pattern it becomes trivial to write an application that prints it)

Share this post


Link to post
Share on other sites

Well the more you practice the better you get. Also, with a program such as the one you asked about it helps to think about what steps you need to do to perform the task step by step, perhaps writing them down, before you even start typing things in to the computer.

 

Is the book you are using the Stroustrup one (The C++ Programming Language)? The exercise looks familiar. Be warned that book is very dense, advanced and isn't really a great way to learn the language, it's more useful as a reference, IMHO. If I recall correctly one of the first programs he knocks together is a full recursive descent calculator with variables, all in about 50 lines of code... not a good beginning program... which he then goes on to describe as a "toy program" ;)

Share this post


Link to post
Share on other sites

It's also good to think of different ways to do the task as well, and weigh up the elegance/ease of understanding the code for each method.

 

Here's another method I thought up, bet no-one else thought of it:

 

print 1 X

print 2 X's

print 3 X's

...

print N X's (row N)

print N-1 X's

print N-2 X's

...

print 2 X's

print 1 X

 

Turn monitor 90 degrees counterclockwise (or angle head suitably).

 

This only works since X's look similar when viewed at a 90 degree angle.

Share this post


Link to post
Share on other sites

Well the more you practice the better you get. Also, with a program such as the one you asked about it helps to think about what steps you need to do to perform the task step by step, perhaps writing them down, before you even start typing things in to the computer.

well thanks for all the input, I will try flowcharting or pseudo code my program.

Share this post


Link to post
Share on other sites


Personally i tend to break things down into as small pieces as possible.

so do I, and yes I will ponder the pattern.


Here is some more hints (i might help too much now):

lets say totalrows = 5

row 0 then has 4 (5-(0+1)) spaces and 1 (0*2 + 1) X //notice where the 0 is
row 1 has 3 (5-(1+1)) spaces and 3 (1*2 +1) X // here that 0 is 1
row 2 has 2 (5-(2+1)) spaces and 5 (2*2 +1) X // and here it is 2
row 3 has 1 (5-(3+1)) spaces and 7 (3*2 +1) X // and 3


Thus: each row has:
totalrows - (rownumber + 1) spaces
and
rownumber * 2 + 1 X:s

so if you replace (number of spaces) and (number of X) in this code with the appropriate expression (see above) you'll have a solution.
int rows = 5;
for (int i=0;i<rows;i++) {
    //now i is the row number and rows is the total number of rows in the triangle
    for (int j=0;j<(number of spaces);j++) std::cout << " "; // print spaces
    for (int j=0;j<(number of X);j++) std::cout << "X"; // print X:s
std::cout << std::endl; //linebreak
}

Share this post


Link to post
Share on other sites

Eww, flowcharts sad.png

Pseudo code is ok, probably overkill for something as simple as this.

 

Simon Forsman posted what kind of thought processes you should be going through while I was writing my reply (although you need to think about how to generalise the algorithm so it prints out a triangle of any desired height, not just height 5 - which involves some basic algebra).

 

EDIT: Which I see he did while I was posting this reply ;)

Edited by Paradigm Shifter

Share this post


Link to post
Share on other sites

You should have been able to solve it when you realised you needed to print out spaces at the beginning of all the lines except the last line, maybe with a bit of "oh, I need to print out rownum * 2 - 1 X's instead of rownum X's" as well.

 

You never said what book it was, if it is the Stroustrup one I'd look at finding an easier book to start off with...

Edited by Paradigm Shifter

Share this post


Link to post
Share on other sites

Hmm, I noticed you base the calculations on the number of X's to be printed on the last line rather than the total numbers of rows to print out... I definitely wouldn't think of it like that, since it is impossible to print out an even number of X's on a row, so that raises the possibility of giving the algorithm incorrect data. The only constant you should think in terms of is how many rows you want to print.

 

Bonus credit questions:

 

Make it parse the command line for how many rows to print out (using arguments passed in to main). Extra fun, don't parse anything just use the number of arguments given on the command line as the number of rows to print (so don't use argv, use argc only ;)).

 

Make a function which prints a row given 2 arguments: total number of rows to print and current row. Use that instead in your loop.

 

Split the above function up into 2 parts, one which prints the spaces, another which prints the X's. Call the 2 new functions from the row print function.

 

Print just the outline of the triangle (i.e. spaces between the X's, but not on the last row)

 

Print Pascal's triangle instead of X's, make sure it is nicely formatted - you need to work out the width of the largest number you will be printing to achieve that. (EDIT: That's quite advanced though and there are loads of different ways to do it, includgin a way which doesn't store the values for the whole of the triangle anywhere, but calculates it per row on the fly [you'll need to look at the last row first of all to see how long the biggest number is then though])

Edited by Paradigm Shifter

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this