Friday, November 28, 2014

C Unions pro



C Program to Compute the Sum of Digits in a given Integer

 
#include 
#include
void main()
{
    long num, temp, digit, sum = 0;
    printf("Enter the number \n");
    scanf("%ld", &num);
    temp = num;
    while (num > 0)
    {
        digit = num % 10;
        sum  = sum + digit;
        num /= 10;
    }
    printf("Given number = %ld\n", temp);
    printf("Sum of the digits %ld = %ld\n", temp, sum);
    getch();
}
 
Output
 
Enter the number
300
Given number = 300
Sum of the digits 300 = 3
 

C Program to Illustrate the Concept of Unions

 
#include 
#include
void main()
{
    union number
    {
        int  n1;
        float n2;
        clrscr();
    };
    union number x;
    printf("Enter the value of n1: ");
    scanf("%d", &x.n1);
    printf("Value of n1 = %d", x.n1);
    printf("\nEnter the value of n2: ");
    scanf("%f", &x.n2);
    printf("Value of n2 = %f\n", x.n2);
    getch();
}
 
Output

Enter the value of n1: 10
Value of n1 = 10
Enter the value of n2: 50
Value of n2 = 50.000000

C Program to Find the Size of a Union

#include 
#include
void main()
{
    union sample
    {
        int   m;
        float n;
        char  ch;
           clrscr();
    };
    union sample u;
    printf("The size of union = %d\n", sizeof(u));
    u.m = 25;
    printf("%d %f %c\n", u.m, u.n, u.ch);
    u.n = 0.2;
    printf("%d %f %c\n", u.m, u.n, u.ch);
    u.ch = 'p';
    printf("%d %f %c\n", u.m, u.n, u.ch);
    getch();
}
 
Output
 
The size of union = 4
25 0.000000 
1045220557 0.200000
1045220464 0.199999

C Program to Convert Binary to Octal

#include 
#include 
int main()
{
    long int binarynum, octalnum = 0, j = 1, remainder;
    clrscr();
    printf("Enter the value for  binary number: ");
    scanf("%ld", &binarynum);
    while (binarynum != 0)
    {
        remainder = binarynum % 10;
        octalnum = octalnum + remainder * j;
        j = j * 2;
        binarynum = binarynum / 10;
    }
    printf("Equivalent octal value: %lo", octalnum);
    return 0;
}
 
Output
        
Enter the value for binary number: 10101
Equivalent octal value: 25

No comments:

Post a Comment