
November 29th, 2012, 11:32 PM
|
|
Contributing User
|
|
Join Date: Oct 2012
Posts: 38
Time spent in forums: 6 h 46 m 22 sec
Reputation Power: 1
|
|
|
Star Output Using Recursion
I'm trying to write a program that outputs stars using recursion. I cannot use loops.
For example, if a user inputted the number three, the
program would look like this
*
**
***
**
*
Here is my code
Code:
#include <iostream>
using namespace std;
int starPrinter(int howManyStars, int index)
{
if (index <= howManyStars)
{
cout <<"*";
return starPrinter(howManyStars, ++index);
}
else if (index)
{
cout <<endl;
}
}
int starPrinterBackward(int howManyStars, int index)
{
if (index == howManyStars)
{
cout <<endl;
return starPrinter(howManyStars, --index);
}
else if (index)
{
cout <<"*";
}
}
void starOutput(int height, int index)
{
if (index < height)
{
starPrinter(index,0);
starOutput(height, ++index);
starPrinterBackward(height, --index);
}
}
int main()
{
int height;
cout <<"Enter height" <<endl;
cin >> height;
starOutput(height, 0);
}
I'm pretty sure there's something wrong with my "starPrinterBackward" function, but I can't figure out exactly what. It should be similar to my "starPrinter" function, right? Only that it does things in reverse. What I'm thinking is, the backward function needs to start at one less than the user input and go until it reaches one.
|