Write a C program that asks for an integer n and then comput

Write a C program that asks for an integer (n) and then computes the following based on the value of the integer: n should be greater than 1. If n is even replace the integer with half of its value (n/2) If n is odd replace the integer with three times its value plus 1(3n+l) The value of n gets replaced with a new value. New n should be checked again whether it is odd or even. This process continues until n

Solution

#include <stdio.h>
void main()
{
    //declare variables
    int n,cnt=0;
  
    //prompt user for n
    printf(\"Enter value of n: \");
    scanf(\"%d\",&n);
  
    //check if n>1
    if(n>1)
    {
        do{
        //check if n is even  
        if(n%2==0)
        {
            //if yes,increment count and divide by 2
            cnt++;
            n=n/2;
            printf(\"%d\\t\",n);
        }
        //check if n is odd
        else
        {
            cnt++;
            n=3*n+1;
            printf(\"%d\\t\",n);
        }
        //continue this until n<=1
}while(n>1);
    }
    //print no of sequence
    printf(\"\ Count: %d\",cnt);

}

Sample Output:

Enter value of n: 10                                                                                                                                            

5       16      8       4       2       1                                                                                                                       

Count: 6

 Write a C program that asks for an integer (n) and then computes the following based on the value of the integer: n should be greater than 1. If n is even repl

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site