7.0k views
2 votes
Write a function "hailstone"that takes an int "n2"and prints the hailstone sequence. Hailstone Numbers:This sequence takes the name hailstone as the numbers generated bounce up and down. To generate the sequence, follow these rules:a.If the number isodd multiply it by 3 and add 1 b.If the number is even, divide by two.c.Repeat until you reach number 1.Sample Inputs & Outputsn2= 3-> 10, 5, 16, 8, 4, 2, 1 n2 =6-> 3, 10, 5, 16, 8, 4, 2, 1 n2 =7-> 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1

User Tanique
by
8.1k points

1 Answer

4 votes

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.

Write a function "hailstone"that takes an int "n2"and prints the-example-1
User Carmello
by
7.1k points