C PROGRAM ON DATA TYPE AND UNION

C Program to Find the Ranges of Data Types

/*
 * C Program to Print the Range of Datatypes
 */
#include <stdio.h>
#define SIZE(x) sizeof(x)*8
 
void signed_one(int);
void unsigned_one(int);
 
void main()
{
    printf("range of int");
    signed_one(SIZE(int));
 
    printf("\nrange of unsigned int");
    unsigned_one(SIZE(unsigned int));
 
    printf("\n\nrange of char");
    signed_one(SIZE(char));
 
    printf("\nrange of unsigned char");
    unsigned_one(SIZE(unsigned char));
 
    printf("\n\nrange of short");
    signed_one(SIZE(short));
 
    printf("\nrange of unsigned short");
    unsigned_one(SIZE(unsigned short));
}
 
/* RETURNS THE RANGE SIGNED*/
void signed_one(int count)
{
    int min, max, pro;
    pro = 1;
    while (count != 1)
    {
        pro = pro << 1;
        count--;
    }
    min = ~pro;
    min = min + 1;
    max = pro - 1;
    printf("\n%d to %d", min, max);
}
 
/* RETURNS THE RANGE UNSIGNED */
void unsigned_one(int count)
{
    unsigned int min, max, pro = 1;
 
    while (count != 0)
    {
        pro = pro << 1;
        count--;
    }
    min = 0;
    max = pro - 1;
    printf("\n%d to %d", min, max);
}

 

Run Time Testcases

The output range for the fundamental data types of int, char, and short is shown below.

range of int

-2147483648 to 2147483647

range of unsigned int

0 to -1

 

range of char

-128 to 127

range of unsigned char

0 to 255

 

range of short

-32768 to 32767

range of unsigned short

0 to 65535

C Program to Illustrate the Concept of Unions

*
 * C program to illustrate the concept of unions using dot operator
 */
 
#include<stdio.h>
int main()
{
#include <stdio.h>
//scope of union -> main function 
void main()
{
    union number
    {
        int  n1;
        float n2;
    };
    //initializing union number variable by using union keyword and tag name
    union number x;
 
    printf("Enter the value of n1: ");
    scanf("%d", &x.n1); //access using dot product
    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);
}

 

Runtime Test Cases

 

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

/*
 * C program to find the size of a union
 */
#include <stdio.h>
 
void main()
{
    union sample
    {
        int   m;
        float n;
        char  ch;
    };
    union sample u;
 
    printf("The size of union = %d\n", sizeof(u));
    /*  initialization */
    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);
}

 

Runtime Test Cases

 

The size of union = 4

25 0.000000

1045220557 0.200000

1045220464 0.199999