J. Doe J. Doe - 1 month ago 15
C++ Question

Code complete, but creates an infinite loop?

I am trying to print a pattern like this below, I have the code running with no errors but it generates an infinite loop and I am not certain why;

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


Any guidance or help would be great! Thanks

#include <iostream>
#include <string>
using namespace std;

// function member
void star(int amountStars, char starShape);

// function
void star(int amountStars, char starShape)
{
int i;
string shape = "*";
for (i = 0; i < starShape; i++)
// loop to increment through
cout << shape;

cout << endl;

if (starShape == amountStars)
// if * is equal to the amount of stars (30)
return; //**************
star(amountStars, ++starShape); // increase * by one ***********

for (i = 0; i < starShape; i++)
cout << shape;
cout << endl;


}
int main()
{
int amountStars = 30; // variable to store the amount of stars

star(amountStars, '*'); // function print for the amount of stars and the shape

return 0;
}//end main

Answer

Your star() function is calling itself on the line with the comment "increase * by one", which means it is a recursive function. But the termination condition is broken

You intialise the starShape parameter, which is of type char, with a literal '*' which has an ASCII value of 42. But rather than using this as the symbol, you actually use the local string variable shape to do the printing. And you treat starShape as a counter, which you try to use to end the loop. But it starts at 42 and only goes up from there, so it will never be equal to the value of 30 that you pass in.

The simplest (but not best) way to fix this is to change starShape to an int and pass in 0 from main.

#include <iostream>
#include <string>
using namespace std;

// function member
void star(int amountStars, char starShape);

// function
void star(int amountStars, char starShape)
{
    int i;
    string shape = "*"; 
    for (i = 0; i < starShape; i++)
        // loop to increment through 
        cout << shape;

    cout << endl;

    if (starShape == amountStars)
        // if * is equal to the amount of stars (30)
        return; //**************
    star(amountStars, ++starShape); // increase * by one ***********

    for (i = 0; i < starShape; i++)
        cout << shape;
        cout << endl;


}
int main()
{
    int amountStars = 30; // variable to store the amount of stars

    star(amountStars, 0); // function print for the amount of stars and the shape

    return 0;
}//end main

Then go and read up on recursive functions and termination conditions. :)

Comments