I am working on a lab for a C++ course. My current code gives me most but not all points available for this lab. I can't quite seem to get the code to print correctly. I've tried many possible ways of printing the code. On my closest attempts, the printed output seems to be missing a new line at the end of the last row. I would be most appreciative for any suggestions.
The assignment stated the following:
Hailstone sequence
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 2 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.
The output format can be achieved as follows: print(n, end='\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 program below works but the auto-grader just wants me to have the exact match to what they have which has having a new line at the last number.
#include <iostream>
using namespace std;
int main() {
int n;
int counter = 1;
cin >> n;
cout << n << "\t";
while ( n >1) {
if ( n%2 == 0) {
n = n /2;
cout << n << "\t";
}
else {
n = 3 * n + 1;
cout << n << "\t";
}
counter++;
if ( counter % 10 ==0) {
cout << endl;
}
}
return 0;
}
Here is the auto grader telling what I need to fix:
I really don't understand, how it could be done?
Well I tried adding the "\t"
new tab but it give me an error of not being a new line at every 10 number, so I changed the program back to endl:
cout << n << "\t";
so I really don't understand why the auto grader is so finicky.
Note that all the numbers are separated by whitespace – the difference is just which whitespace is separating them.
You're printing "number and tab" as one unit, then occasionally adding a linebreak.
This make every line end with "number, tab, linebreak", and the last one with "number, tab".
Instead print number, separator, number, separator, number, ...
Finish the whole thing off with a linebreak after the loop.
Something like this:
int main() {
int counter = 1;
int n;
cin >> n;
// Print the first number
cout << n;
while (n > 1) {
// Select a separator.
if (counter % 10 == 0) {
cout << endl;
}
else {
cout << '\t';
}
// Determine the next number.
if (n % 2 == 0) {
n = n / 2;
}
else {
n = 3 * n + 1;
}
// Print the number.
cout << n;
counter++;
}
cout << '\n';
}
You can also shorten the loop a bit:
while (n > 1) {
n = n % 2 == 0 ? n / 2 : 3 * n + 1;
char separator = counter % 10 == 0 ? '\n' : '\t';
cout << separator << n;
counter++;
}