I need to write a function that calculates and returns the length of the hailstone sequence previously calculated in the functions that are already there. Everything I've tried gives me an infinite loop of "22"s. Arrays are NOT allowed. Everything has to be done with loops and only one loop per function.
I have mostly tried using the previous functions with length++; added to them. But I am just clueless as to what to do.
#include <cstdio>
using namespace std;
// The function next(n)takes an integer value n and
// returns the number that follows n in a hailstone sequence.
// For example: next(7) = 22 and next(22) = 11.
int next(int n)
{
if (n > 1)
{
if ((n % 2) == 0 )
{
n = n / 2;
}
else
{
n = 3 * n + 1;
}
printf("%i ",n);
}
return 0;
}
// The function hailstone reads int n and
// prints its entire hailstone sequence.
void hailstone(int n)
{
while(n>1)
{
next(n);
}
}
int length(int n)
{
int length = 1;
return length;
}
int main()
{
int n;
printf("What number shall I start with?");
scanf("%i", &n);
printf("The hailstone sequence starting at %i is: ", n);
hailstone(n);
printf("The length of the sequence is: %i", length(n));
return 0;
}