60.8k views
5 votes
Write a function that receives an integer (n) argument and then computes the following based on the value of the integer: While the value of n is greater than 1, replace the integer with half of its value (n/2) if the integer is even. Otherwise, replace the integer with three times its value, plus 1 (3*n + 1). Make provision to count the number of values in (or the length of) the sequence that results. Test your function: If n = 10, the sequence of integers is 5, 16, 8, 4, 2, 1 and so the length is 6. Make a plot of the length of the sequence that occurs as a function of the integers from 2 to 30. For example, when n = 10, the length is 6 while for n = 15, the length is 17.

1 Answer

4 votes

Answer:

#include <iostream>

using namespace std;

int func(int n)//function..

{

if(n>1)

{

if(n%2==0)//checking if the number is even.

{

return n/2;

}

else

{

return (3*n+1);

}

}

}

int main() {

int num;//taking input of the n.

cin>>num;

while(num>1)//looping while the value of num is greater than 1.

{

int a=func(num);//calling function.

cout<<a<<" ";//printing .

num=a;//changing the value of num.

}

return 0;

}

Input:-

10

Output:-

5 16 8 4 2 1

Step-by-step explanation:

I have created the function named func. Then returning the values according to the problem.In the main function taking the input of integer num. Then calling a loop and calling the function till the value of n is greater than 1 and printing all the values returned by the function.

User Adrisons
by
5.2k points