CAN YOU FIND THE ERRORS?

Write your answer here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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 
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>        // <=== add
using namespace 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)
}

Topic archived. No new replies allowed.