C Program to Illustrate the Concept of Unions


This is a C program to illustrate the concept of unions.

Problem Description

This program illustrates the concept of unions.

Problem Solution

1. Define the union.
2. Take the input and store it in the variable using dot operator.
3. Print the output using dot operator and exit.

Program/Source Code

Here is source code of the C program to illustrate the concept of unions. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C program to illustrate the concept of unions
  3.  */
  4. #include <stdio.h>
  6. void main()
  7. {
  8.     union number
  9.     {
  10.         int  n1;
  11.         float n2;
  12.     };
  13.     union number x;
  15.     printf("Enter the value of n1: ");
  16.     scanf("%d", &x.n1);
  17.     printf("Value of n1 = %d", x.n1);
  18.     printf("\nEnter the value of n2: ");
  19.     scanf("%f", &x.n2);
  20.     printf("Value of n2 = %f\n", x.n2);
  21. }
Program Explanation

1. Define the union named number with two variables n1 and n2.
2. Define the union variable x.
3. Take the value of two variables using dot operator(i.e. x.n1, x.n2) as input.
4. Print the values of two variables using dot operator as output.

Note: Join free Sanfoundry classes at Telegram or Youtube
Runtime Test Cases
Enter the value of n1: 10
Value of n1 = 10
Enter the value of n2: 50
Value of n2 = 50.000000

Sanfoundry Global Education & Learning Series – 1000 C Programs.

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

If you wish to look at other example programs on Simple C Programs, go to Simple C Programs. If you wish to look at programming examples on all topics of C, go to C Programming Examples.

Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.