So in the main of my program there is a section where I call on the hailstone function to answer a question in a print statement. Instead of it printing the sequence once, it is printing it twice and I don't know why or how to fix it. Is there a way to fix this and remove the print statement from the function next(n)? Also, I wanted to know if my comments seem okay? I have a hard time writing decent contracts so any tips and critiques on those would be great. But the main thing is getting the hailstone sequence to print once, not twice.
// Program hailstone takes a number and gives a sequence of
// numbers starting with the input(n). The sequence alogrithm
// is (3n+1) then the next number is the previous divided by two.
#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 n;
}
// The function hailstone reads int n and
// prints its entire hailstone sequence.
void hailstone(int n)
{
while(n>1)
{
n = next(n);
}
}
// Parameters: int length, int n
// Uses next function, to calculate the length of the sequence.
int length(int n)
{
int length = 1;
while (n > 1)
{
n = next(n);
++length;
}
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("\nThe length of the sequence is: %i", length(n));
return 0;
}