Code Should Explain It self..

``````#include <iostream>

using namespace std;

int main()
{
unsigned int digit;

for( digit = 0; digit < 10; digit++ )
{
/*

I WANT THE OUTPUT TO CARRY ON UNTIL DIGIT == 10 & OUTPUT

*
**
***
****
*****
******
*******
********
*********
**********

*/
}

cin.get();

return 0;
}``````
4
Contributors
8
Replies
9
Views
9 Years
Discussion Span
Last Post by William Hemsworth

Put another loop inside that loop. You want to print (digit+1) asterisks and then a newline.

When you say "digit+1" could i use a switch case with case "1" then print 1 etc etc?

Um, huh? I mean this, basically:

``````for ( int i = 0; i < digit + 1; i++ )
std::cout<<'*';
std::cout<<'\n';``````

I meant something like

``````switch (digit)
{
case 1: cout << "*" << endl; break;
case 2: cout << "**" << endl; break;
}``````

But thanks anyways

Essentially you are extending the triangular number sequence: 1, 3, 6, 10, 15, ... (i.e. each number is the number of asterisks printed so far). Here is the pattern:
http://www.mathematische-basteleien.de/triangularnumber.htm

Using a switch statement would not be very effective if you needed, say, 100 lines (heck even having to make 10 separate cases scares me...if a problem is not fun, then there is a better way to solve it, and writing out 10 switch statements does not sound like fun :)).

In any case, notice that on each successive line, there is 1 more asterisk than on the previous line (this pattern will become more evident if you follow the link I gave you above). If you use a nested loop as Narue suggested (i.e. another for-loop within your existing for-loop), you can print out a number of asterisks equal to the current value of "digit" plus 1.

That is, if digit = 0, your inner for loop will run from 0 to 0, and output 1 asterisk.

If digit = 1, the inner loop would run from 0 to 1, and output 2 asterisks.

If digit = 5, the inner loop would run from 0, 1 , ... , 5, and would output 6 asterisks...

EDIT: and Narue posted again before me...so this kinda becomes redundant

>I meant something like
That works, until you want a bigger triangle:

``````for( digit = 0; digit < 20; digit++ ) {
// Uh-oh. Now you need to add 10 more cases
}``````

>But thanks anyways
For future reference, I despise any variation of "thanks anyway". It has extremely rude connotations.

Ohh I'm so sorry I didn't mean to be rude but thankful is "Thank You" ok?

Try this:

``````#include <iostream>

using namespace std;

int main()
{
unsigned int digit1;
unsigned int digit2;

for( digit1 = 0; digit1 < 10; digit1++ ) {
for( digit2 = 0; digit2 < digit1 + 1; digit2++ ) {
cout << '*';
}
cout << '\n';
}

cin.get();

return 0;
}``````
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.