pages

Monday, April 27, 2020

C Programming slip 13

Slip13 
Q1. Write a C program to accept the value of n and display sum of all odd numbers
 up to n. [15 Marks]
#include <stdio.h>
int main()
{
    int i, n, sum=0;
    /* Input range to find sum of odd numbers */
    printf("Enter upper limit: ");
    scanf("%d", &n);
    /* Find the sum of all odd number */
    for(i=1; i<=n; i+=2)
    {
        sum += i;
    }
    printf("Sum of odd numbers = %d", sum);
    return 0;
}
Q2. Write a program to accept a decimal number and convert it to binary, octal and
 hexadecimal number. [25 Marks]

#include<stdio.h> // include stdio.h library

 int main(void)
{
    int num, choice,oct=0, base;
    int  bin = 0;    
    int i = 0, rem;
    char hex_arr[50];
         printf("Enter a number: ");
        scanf("%d", &num);
        

    while(1)
    {
        printf("Select conversion: \n\n");
        printf("1. Decimal to binary. \n");
        printf("2. Decimal to octal. \n");
        printf("3. Decimal to hexadecimal. \n");              
        printf("4. Exit. \n");
        
        printf("\nEnter your choice: ");
        scanf("%d", &choice);
        
        switch(choice)
        {
            case 1:
                base = 2;
               while(num != 0)
          {
        rem = num % 2;  // get the remainder 
        bin = rem * (long long)pow(10, i++) + bin;  
        num /= 2;  // get the quotient
     }       
    
    printf("%lld", bin);  

                break;
            case 2:
                base = 8;
while(num != 0)
    {
        rem = num % 8;  // get the last digit
        oct = rem * (long long)pow(10, i++) + oct;  
        num /= 8;  // get the quotient
    }
    
    printf("0o");
    
    printf("%lld", oct);  

                break;              
            case 3:
                base = 16;
while(num != 0)
    {
        rem = num % 16;  // get the right most digit
        
        if (rem < 10)
        {
            hex_arr[i++] = 48 + rem;
        }
        else
        {
            hex_arr[i++] = 55 + rem;
        }
        
        num /= 16;  // get the quotient
    }
    
    printf("0x");
    
    for(int j = i - 1; j >= 0 ; j--)  // print the hex_arr in reverse order
    {
        printf("%c", hex_arr[j]);
    }    

                break;
            case 4:
                printf("Exiting ...");
                exit(1);
            default:
                printf("Invalid choice.\n\n");
                continue;
        }
        

    }        
    
} 


No comments:

Post a Comment