I've done it with arrays before in java, but I'm having trouble trying to convert it to work with my current code. I'm still new to C++ and am also looking for some critique. My code that works looks like a mess and would like suggestions on how to make it look neater. I'm trying to get into the habit of writing my contracts first then writing the codes. (Which is honestly helping me understand what I'm doing better). I mean, it's not clean. I want to clean it afterward for sure, but I want to try fixing this portion. I would just like some suggestions. I'm going to be working on this some more.
// This program takes a user defined number 'n'
// and runs it through a function that returns
// the number that follows 'n' in hailstone sequence.
// Since there is no number that follows 1 in the sequence,
// this function requires its parameter 'n' to be greater
// than 1.
/* example output
What number shall I start with? 7
The hailstone sequence starting at 7 is:
7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
The length of the sequence is 17.
The largest number in the sequence is 52.
The longest hailstone sequence starting with a number up to 7 has length 17
The longest hailstone sequence starting with a number up to 7 begins with 7
*/
#include <algorithm>
#include <cstdio>
using namespace std;
int main(int argc, char** argv)
{
int n;
// hailLength will keep track of how many
// numbers are produced in the sequence.
int hailLength = 1;
printf("What number shall I start with? ");
scanf("%d", &n);
printf("The hailtone sequence starting at %d is: \n", n);
printf("%i", n);
printf(" ");
// While 'n' is not equal to 1 the function will calculate whether 'n' is even
// then it will divide n/2, otherwise it will compute 3n + 1 if n is odd.
while(n != 1)
{
if(n % 2 == 0)
{
n /= 2;
printf("%i", n);
printf(" ");
}
else
{
n = (3 * n) + 1;
printf("%i", n);
printf(" ");
}
hailLength++;
}
printf("\n");
printf("The length of the sequence is %i.", hailLength);
printf("\n");
// This line will display the largest value in the hailstone sequence.
// This portion is also broken.
int maximum(int n);
{
int k = 0;
int ans = n;
while(k != n)
{
k++;
if(ans < k)
{
ans = k;
}
}
//return ans;
printf("%u", ans);
//printf("%u", k);
printf("\n");
}
//printf("The largest number in the sequence is %i", max(n));
return 0;
}