Answer:
Here is the C program
#include<iostream> //for input output functions
using namespace std; //to identify objects like cin cout
int Hailstone(int n2); //function declaration of function Hailstone
int main() { // start of main() function body
int num; // stores number entered by user
cout<<"Enter a number: "; // prompts user to enter a number
cin>>num; // reads the input number
while(num!=1) { // loop continues until the value of num becomes 1
num = Hailstone(num); // calls hailstone method and passes num to it
cout<<num<<"\\"; } } // prints the hailstone sequence
int Hailstone(int n2) { //function takes int n2 and prints hailstone sequence
if(n2 % 2 == 0) { // if the number is even
return n2 /=2; } // divide the n2 by 2 if n2 value is even
else { // if n2 is odd
return n2 = (3 * n2) + 1; } } // multiply n2 by 3 and add 1 if n2 is odd
Step-by-step explanation:
The function Hailstone() takes as parameter an integer which is int type and is named is n2. This function prints the hailstone sequence. The function has an if statement that checks if the number n2 input by the user is even or odd. If the value of n2 is even which is found out by taking modulus of n2 by 2 and if the result is 0 this means that n2 is completely divisible by 2 and n2 is an even number. So if this condition evaluates to true then n2 is divided by 2. If the condition evaluates to false and the value of n2 is odd then n2 is multiplied by 3 and 1 is added.
In the main() function the user is prompted to enter a number and the Hailstone() function is called which keeps repeating until the value of n2 reaches 1.