Hailstone sequence

I am having difficulties with this lab so so if anyone can help, it would be greatly appreciated.

Given a positive integer n, the following rules will always create a sequence that ends with 1, called the hailstone sequence:

If n is even, divide it by two
If n is odd, multiply it by 3 and add 1 (i.e. 3n +1)
Continue until n is 1
Write a program that reads an integer as input and prints the hailstone sequence starting with the integer entered. Format the output so that ten integers, each separated by a tab character (\t), are printed per line. End the last line of output with a new line (endl).

The output format can be achieved as follows:
cout << n << "\t";

Ex: If the input is:

25

The output is:

25 76 38 19 58 29 88 44 22 11
34 17 52 26 13 40 20 10 5 16
8 4 2 1

My code so far is:

#include <iostream>
using namespace std;

int main() {

/* Type your code here. */
int n, count =0;
cin >> n;
while(n >1){
cout << n << "\t";
if(n% 2 ==0)
n /= 2;
else(n=(3*n) +1);
cout << n << "\t";
++count;
cout << endl;

}
if(count % 10==0){
cout << endl;
}
cout << n << "\t";
cout << endl;


return 0;
}
Last edited on
I think it has to do with where I’m putting my Endls and the code”cout << n << “\t;”
Please USE CODE TAGS for readability.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
using namespace std;

int main()
{
   int n, count = 1;         // count = 1 as it should reflect the number of outputs
   cin >> n;
   cout << n << "\t";        // Output your first number BEFORE starting the loop
   while( n > 1 )            // ...
   {
      if ( n% 2 == 0 )
         n /= 2;
      else
         n = 3 * n + 1;      // Remove excessive bracketing; it's hard to read

      cout << n << "\t";
      ++count;
      // cout << endl;       // NO. Test before forcing a line break

      if ( count % 10 == 0 ) // Test for line breaks WITHIN your main loop
      {
         cout << endl;      
      }
   }

   // cout << n << "\t";     // NO. n was already output in the loop.   
   cout << endl;
   // return 0;              // Not necessary
}
Last edited on
Perhaps:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

int main() {
	int n {};
	std::cin >> n;

	for (size_t count {1}; n > 1; ++count) {
		std::cout << n << '\t';

		if (count % 10 == 0)
			std::cout << '\n';

		if (n % 2 == 0)
			n /= 2;
		else
			n = (3 * n) + 1;
	}

	std::cout << n << '\n';
}



25
25      76      38      19      58      29      88      44      22      11
34      17      52      26      13      40      20      10      5       16
8       4       2       1

Thanks for your help! I am truly grateful your both of your efforts.
Topic archived. No new replies allowed.