Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

This is supposed to be done in C programming language. Write a program that asks

ID: 3800400 • Letter: T

Question

This is supposed to be done in C programming language. Write a program that asks the user to enter a number greater than 1 and then counts the number of steps it takes to reduce the number to 1 according to the following rules:

If the number is even, divide it by 2

If the number is odd, multiply it by 3 and add 1

Use a recursive function (a function that calls itself) to calculate the number of steps needed to reach 1.

Hint: When writing a recursive function, start with the base case that doesn’t call itself. In this case, that would be when the number has been reduced to 1.

Example:

Enter a number greater than 1: 7

It took 16 steps to reduce 7 to 1

Explanation / Answer

#include <stdio.h>
int check(int num, int count )

{   
count = count + 1;
if (num <2)

return count;

else if (num %2 ==0)

return check(num/2, count+1);

else

return check(3* num +1, count+1);

}
int main(void) {
int n;
int result;
printf("Enter a number greater than 1: ");
scanf("%d", &n);
result = check(n,0);
printf("It took %d steps to reduce %d to 1 ", result, n);
return 0;
}

Output:

sh-4.2$ gcc -o main *.c                                                                                                                                                                                                                                                

sh-4.2$ main                                                                                                                                                                                                                                                           

Enter a number greater than 1: 7                                                                                                                                                                                                                                       

It took 33 steps to reduce 7 to 1

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote