int hailstonelength(int n)
{
int length = 0;
while (n >= 1)
{
length++;
if (n % 2 == 0)
n = n / 2;
if (n % 2 == 1)
n = n * 3 + 1;
}
return n;
}
int main()
{
int n = 21;
int result = hailstonelength(n);
cout << result << "steps were necessary for" << n << ".\n";
}
//DESIRED OUTPUT: 7 STEPS WERE NECESSARY FOR 21
#include <iostream> // <=== add
usingnamespace std; // <=== add
int hailstonelength(int n)
{
int length = 0;
while (n > 1) // <=== did you mean > rather than >=
{
length++;
if (n % 2 == 0) n = n / 2;
else n = n * 3 + 1; // <=== use else; you have already changed n
}
return length; // <=== return length
}
int main()
{
int n = 21;
int result = hailstonelength(n);
cout << result << " steps were necessary for " << n << ".\n"; // <=== added some spaces (minor)
}