//*** //Assignment 1 //Program preforms the entire hailstone sequence //starting
ID: 3541593 • Letter: #
Question
//***
//Assignment 1
//Program preforms the entire hailstone sequence
//starting at n, all on one line, with the numbers
//separated by spaces; (2) the length of the
//hailstone sequence that starts with n; (3) the
//largest number in the hailstone sequence that
//starts with n; and (4) how many of the numbers in
//that hailstone sequence are even.
#include <cstdlib>
#include <iostream>
using namespace std;
int Hailstone(int n)
{
if(n % 2 == 0)
{
n /= 2;//number is even
}
else
{
n = 3 * n + 1; //number is odd
}
return n;//returns the value
}
void sequence(int n)
{
cout << n << " ";
if(n!=1)
{
n= Hailstone(n);
cout<< n <<" ";
sequence(n);
}
}
//calculates the length of the Hailstone Sequence
int lengthHail(int num)
{
int count = 1;
while(num != 1)
{
num = Hailstone(num);
count++;//adds one to count everytime a calculation is done
}
return count;
}
//calculates the largest number in the sequence
int largest(int n)
{
static int maxInt =0;
int temp;
if(n==1) return n;
if(maxInt< (temp=Hailstone(n)))
maxInt =temp;
if(temp !=1)
largest(temp);
return maxInt;
}
//calculates the number of even numbers in the
//sequence
int numOfeven(int n)
{
static int count = 0;
int temp=0;
if(n%2==0)
++count;
if(n==1)
return count;
else
{
temp=Hailstone(n);
return numOfeven(temp);
}
}
//asks for user input and displays hailstone sequence
//length of the sequence, how many of the numbers are
//even and the largest number in the sequence
int main(int argc, char *argv[])
{
int n=0;
cout << "What number shall I start with?";
cin >> n;
cout << "The hailstone sequence starting at " << n << " is " <<" ";
sequence(n);
cout << " ";
cout << "The length of the sequence is "<< lengthHail(n)<<"."<<" ";
cout << numOfeven(n) << " of the numbers are even."<<" ";
cout << "The largest number in the sequence is " << largest(n) << "." <<" ";
return EXIT_SUCCESS;
}
] This is my hailstone sequence. The problem I'm having is when I compile the sequence output is doubling the numbers; for example: if the hailstone sequence is starting at 7, the sequence is 7 22 22 11 11 34 34 17 17 52 52..... I do not know it is outputting two of each numbers in the sequence. Can someone please tell me what I'm doing wrong
Explanation / Answer
see here pastebin.com/tjA76e6T
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.