drawing a triangle

Hey! I'm trying to make a program that would draw a triangle. Heres what i got allready:

1
2
3
4
5
6
7
8
9
10
11
12
13
int chars;
cout<<"Enter a number: ";
cin>>chars;

int i,spcnum = chars;
for(i = 0;i != chars; i++,spcnum = spcnum--){
       string currentobj(i, '*');
       
       
       string spc(spcnum, ' ');
       cout<<spc<<currentobj<<endl;
       
       } 


If the user types 5, it draws this:

1
2
3
4
5
*
**
***
****
*****


It should draw this:

1
2
3
4
   *
  ***
 *****
*******


Any ideas?
You need an other variable to keep the number of stars, initialize it with one and increment it by two each iteration
i did it,now it draws

1
2
3
4
*
***
*****
*******
Add the spaces before the stars
i know i meant it draws this:

1
2
3
4
    *
    ***
    *****
    *******
What is your code now?
1
2
3
4
5
6
7
8
9
10
11
12
cout<<"Enter a number: ";
cin>>chars;
chars++;
int i,spcnum = chars;
for(i = 1;i != chars; i++,spcnum = chars - i){
       string currentobj(i, '*');
       
       
       string spc(spcnum, ' ');
       cout<<spc<<currentobj<<endl;
       
       } 


now draws even weirder bull$H17, wth?
Your loop should look like this:
1
2
3
4
5
6
7
for(int i = 0,spcnum = chars, stars=1; i < chars; i++,spcnum--, stars+=2){
       string currentobj(stars, '*');

       string spc(spcnum, ' ');
       cout<<spc<<currentobj<<endl;

       }

So the problem was not in the spaces but in the counter witch counts the stars.

Weird :(]

Well, thanks bazzy, you helped me once again lol :D

EDIT: what does += does?
Last edited on
x += y is the same as x = x + y
now it get it, ty

OFFTOPIC: what is the function to generate a random number or a random letter?

something like:

int a = random(100);

so it would generate a random number between 0 and 100
Last edited on
rand()%101 To get "more random" numbers, call srand(time(0)) at the beginning of your program:
http://www.cplusplus.com/reference/clibrary/cstdlib/rand/
Topic archived. No new replies allowed.