Triangle recursion

I am making a program that outputs * in the form of a triangle. I need it to do the triangle right way up and then downwards. For example if it is 5 it looks like this

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

*****
****
***
**
*
My program is as follows but I can't seem to get it to print out like that

#include <stdio.h>
#include <iostream>

using namespace std;



void printStars(int n)
{

if (n == 1)
{
cout << "*" << endl;
}
else
{
cout << "*" << endl;
printStars(n -1);
}
}
int main (void)
{
{
printStars(5);

}
return 0;
}
Your problems look like homework ;)
You have to do it this way: 1->2->3->4->5->4->3->2->1

Also this code I didn't test, but with this system you can reach your target.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <stdio.h>
#include <iostream>

using namespace std;

void printStars(int n, int &target)
{
  // print n stars in a line
  for(int i=0; i<n; i++)
  {
    cout << "*";
  }
  cout << endl;
  
  // add 1 to n
  n++;
  
  if(n <= target)
  {
    // call function recursiv
    printStars(n, target);
  }
  else
  {
    // if you don't need a free line erase this else-block
    cout << endl;
  }  
  
  // print n stars in a line for the second part
  for(int i=0; i<n; i++)
  {
    cout << "*";
  }
  cout << endl; 
}

int main (void)
{
  // print up to 5 stars starting with 1 star
  printStars(1,5);
  return 0;
}
Great thank you I will go and try that! It is homework for a class I never should have got myself into haha, I'm not the greatest with computers.
Topic archived. No new replies allowed.