C++ Structures and Unions Practice Questions with Solutions

Structures and unions are user-defined data types in C++ that allow you to group multiple variables under a single name. They are widely used to organize related data and make programs easier to manage.

Although structures and unions appear similar, they differ in how memory is allocated.

Structure

A structure allocates separate memory for every data member.

Example:

struct Student
{
    int rollNumber;
    string name;
    float marks;
};

Union

A union allocates shared memory for all data members. Only one member can store a value at a time.

Example:

union Data
{
    int integerValue;
    float decimalValue;
    char character;
};

Structures are commonly used in:

  • Student Management Systems
  • Employee Records
  • Banking Applications
  • Library Management Systems
  • Hospital Management Systems
  • Inventory Systems

Unions are commonly used in:

  • Memory Optimization
  • Embedded Systems
  • Hardware Programming
  • Device Drivers

In this chapter, you’ll practice solving structure- and union-based C++ problems with complete explanations.

Each question includes:

  • Problem Statement
  • Complete C++ Solution
  • Sample Input
  • Sample Output
  • Explanation
  • Concepts Covered

Let’s begin. C++ Structures and Unions practice questions with solutions help to understand the concepts.


1. C++ Program to Store and Display Student Information Using Structure

Problem Statement

Write a C++ program to store and display student information using a structure.

C++ Solution

#include <iostream>
using namespace std;

struct Student
{
    int rollNumber;
    string name;
    float marks;
};

int main()
{
    Student student;

    cout << "Enter Roll Number: ";
    cin >> student.rollNumber;

    cin.ignore();

    cout << "Enter Name: ";
    getline(cin, student.name);

    cout << "Enter Marks: ";
    cin >> student.marks;

    cout << "\nStudent Details\n";
    cout << "Roll Number: " << student.rollNumber << endl;
    cout << "Name: " << student.name << endl;
    cout << "Marks: " << student.marks;

    return 0;
}

Sample Input

Enter Roll Number: 101
Enter Name: Rahul Sharma
Enter Marks: 92.5

Sample Output

Student Details
Roll Number: 101
Name: Rahul Sharma
Marks: 92.5

Explanation

The structure groups multiple variables into a single data type named Student.

Concepts Covered

  • Structure
  • User-defined Data Type
  • Data Members

2. C++ Program to Store Employee Information Using Structure

Problem Statement

Write a C++ program to store employee information using a structure.

C++ Solution

#include <iostream>
using namespace std;

struct Employee
{
    int employeeId;
    string employeeName;
    float salary;
};

int main()
{
    Employee employee;

    cout << "Enter Employee ID: ";
    cin >> employee.employeeId;

    cin.ignore();

    cout << "Enter Employee Name: ";
    getline(cin, employee.employeeName);

    cout << "Enter Salary: ";
    cin >> employee.salary;

    cout << "\nEmployee Details\n";

    cout << "ID: " << employee.employeeId << endl;
    cout << "Name: " << employee.employeeName << endl;
    cout << "Salary: " << employee.salary;

    return 0;
}

Sample Input

Enter Employee ID: 205
Enter Employee Name: Amit Kumar
Enter Salary: 45000

Sample Output

Employee Details
ID: 205
Name: Amit Kumar
Salary: 45000

Explanation

The structure stores all employee-related information in one variable.

Concepts Covered

  • Structure Variables
  • Input
  • Output

3. C++ Program to Find the Average Marks of Three Students Using Structure

Problem Statement

Write a C++ program to calculate the average marks of three students using structures.

C++ Solution

#include <iostream>
using namespace std;

struct Student
{
    string name;
    float marks;
};

int main()
{
    Student students[3];

    float total = 0;

    for (int i = 0; i < 3; i++)
    {
        cout << "Enter Name: ";
        cin >> students[i].name;

        cout << "Enter Marks: ";
        cin >> students[i].marks;

        total += students[i].marks;
    }

    cout << "\nAverage Marks = "
         << total / 3;

    return 0;
}

Sample Input

Rahul
85

Amit
90

Riya
95

Sample Output

Average Marks = 90

Explanation

The program stores multiple student records inside an array of structures.

Concepts Covered

  • Array of Structures
  • Average Calculation
  • Loop

4. C++ Program to Demonstrate a Union

Problem Statement

Write a C++ program to demonstrate how a union works.

C++ Solution

#include <iostream>
using namespace std;

union Data
{
    int integerValue;
    float decimalValue;
};

int main()
{
    Data value;

    value.integerValue = 25;

    cout << "Integer = "
         << value.integerValue << endl;

    value.decimalValue = 15.75;

    cout << "Decimal = "
         << value.decimalValue;

    return 0;
}

Sample Output

Integer = 25
Decimal = 15.75

Explanation

Both variables share the same memory location. Assigning one value replaces the previous value stored in the union.

Concepts Covered

  • Union
  • Shared Memory
  • Memory Optimization

5. C++ Program to Compare Structure and Union Size

Problem Statement

Write a C++ program to compare the memory size of a structure and a union.

C++ Solution

#include <iostream>
using namespace std;

struct Student
{
    int rollNumber;
    float marks;
    char grade;
};

union Data
{
    int rollNumber;
    float marks;
    char grade;
};

int main()
{
    cout << "Structure Size = "
         << sizeof(Student) << endl;

    cout << "Union Size = "
         << sizeof(Data);

    return 0;
}

Sample Output

Structure Size = 12
Union Size = 4

Note: Output may vary depending on the compiler and system architecture.

Explanation

A structure allocates memory for every member, whereas a union allocates memory only for its largest member.

Concepts Covered

  • sizeof()
  • Structure Memory
  • Union Memory
  • Memory Management

6. C++ Program to Demonstrate a Nested Structure

Problem Statement

Write a C++ program to demonstrate a nested structure by storing student and address details.

C++ Solution

#include <iostream>
using namespace std;

struct Address
{
    string city;
    string state;
};

struct Student
{
    int rollNumber;
    string name;
    Address address;
};

int main()
{
    Student student;

    cout << "Enter Roll Number: ";
    cin >> student.rollNumber;

    cin.ignore();

    cout << "Enter Name: ";
    getline(cin, student.name);

    cout << "Enter City: ";
    getline(cin, student.address.city);

    cout << "Enter State: ";
    getline(cin, student.address.state);

    cout << "\nStudent Details\n";
    cout << "Roll Number: " << student.rollNumber << endl;
    cout << "Name: " << student.name << endl;
    cout << "City: " << student.address.city << endl;
    cout << "State: " << student.address.state;

    return 0;
}

Sample Input

Enter Roll Number: 101
Enter Name: Rahul
Enter City: Delhi
Enter State: Delhi

Sample Output

Student Details
Roll Number: 101
Name: Rahul
City: Delhi
State: Delhi

Explanation

A structure can contain another structure as one of its members. This is called a nested structure.

Concepts Covered

  • Nested Structure
  • Structure within Structure
  • User-defined Data Types

7. C++ Program to Store Multiple Student Records Using an Array of Structures

Problem Statement

Write a C++ program to store and display information for multiple students using an array of structures.

C++ Solution

#include <iostream>
using namespace std;

struct Student
{
    int rollNumber;
    string name;
};

int main()
{
    Student students[3];

    for (int i = 0; i < 3; i++)
    {
        cout << "Enter Roll Number: ";
        cin >> students[i].rollNumber;

        cout << "Enter Name: ";
        cin >> students[i].name;
    }

    cout << "\nStudent Records\n";

    for (int i = 0; i < 3; i++)
    {
        cout << students[i].rollNumber
             << " "
             << students[i].name << endl;
    }

    return 0;
}

Sample Input

101 Rahul
102 Amit
103 Priya

Sample Output

101 Rahul
102 Amit
103 Priya

Explanation

An array of structures allows you to store multiple records of the same type.

Concepts Covered

  • Array of Structures
  • Loops
  • Multiple Records

8. C++ Program to Pass a Structure to a Function

Problem Statement

Write a C++ program to pass a structure as an argument to a function.

C++ Solution

#include <iostream>
using namespace std;

struct Student
{
    int rollNumber;
    string name;
};

void display(Student student)
{
    cout << "\nStudent Details\n";
    cout << "Roll Number: " << student.rollNumber << endl;
    cout << "Name: " << student.name;
}

int main()
{
    Student student;

    cout << "Enter Roll Number: ";
    cin >> student.rollNumber;

    cout << "Enter Name: ";
    cin >> student.name;

    display(student);

    return 0;
}

Sample Input

Enter Roll Number: 101
Enter Name: Rahul

Sample Output

Student Details
Roll Number: 101
Name: Rahul

Explanation

The complete structure object is passed to the function, making it easy to process grouped data.

Concepts Covered

  • Function Arguments
  • Structures
  • User-defined Types

9. C++ Program to Return a Structure from a Function

Problem Statement

Write a C++ program to return a structure from a function.

C++ Solution

#include <iostream>
using namespace std;

struct Student
{
    int rollNumber;
    string name;
};

Student getStudent()
{
    Student student;

    student.rollNumber = 101;
    student.name = "Rahul";

    return student;
}

int main()
{
    Student student = getStudent();

    cout << "Roll Number: " << student.rollNumber << endl;
    cout << "Name: " << student.name;

    return 0;
}

Sample Output

Roll Number: 101
Name: Rahul

Explanation

Functions can return complete structure objects just like they return integers or floating-point values.

Concepts Covered

  • Returning Structures
  • Function Return Type
  • Structure Objects

10. C++ Program to Store Information Using Multiple Structure Objects

Problem Statement

Write a C++ program to create multiple objects of a structure and display their information.

C++ Solution

#include <iostream>
using namespace std;

struct Student
{
    int rollNumber;
    string name;
};

int main()
{
    Student student1;
    Student student2;

    student1.rollNumber = 101;
    student1.name = "Rahul";

    student2.rollNumber = 102;
    student2.name = "Priya";

    cout << "Student 1\n";
    cout << student1.rollNumber << " "
         << student1.name << endl;

    cout << "\nStudent 2\n";
    cout << student2.rollNumber << " "
         << student2.name;

    return 0;
}

Sample Output

Student 1
101 Rahul

Student 2
102 Priya

Explanation

A structure can have multiple objects, with each object maintaining its own set of data members.

Concepts Covered

  • Multiple Structure Objects
  • Object Initialization
  • Data Storage

11. C++ Program to Calculate Total Salary Using Structure

Problem Statement

Write a C++ program to calculate the total salary of an employee by adding the basic salary, HRA, and DA using a structure.

C++ Solution

#include <iostream>
using namespace std;

struct Employee
{
    string name;
    float basicSalary;
    float hra;
    float da;
};

int main()
{
    Employee employee;

    cout << "Enter Employee Name: ";
    cin >> employee.name;

    cout << "Enter Basic Salary: ";
    cin >> employee.basicSalary;

    cout << "Enter HRA: ";
    cin >> employee.hra;

    cout << "Enter DA: ";
    cin >> employee.da;

    float totalSalary =
        employee.basicSalary +
        employee.hra +
        employee.da;

    cout << "\nTotal Salary = "
         << totalSalary;

    return 0;
}

Sample Input

Enter Employee Name: Rahul
Enter Basic Salary: 30000
Enter HRA: 5000
Enter DA: 4000

Sample Output

Total Salary = 39000

Explanation

The employee details are stored in a structure, and the total salary is calculated by adding all salary components.

Concepts Covered

  • Structure
  • Arithmetic Operations
  • Employee Records

12. C++ Program to Find the Student with the Highest Marks Using Structure

Problem Statement

Write a C++ program to find the student who scored the highest marks using structures.

C++ Solution

#include <iostream>
using namespace std;

struct Student
{
    string name;
    float marks;
};

int main()
{
    Student students[3];

    for (int i = 0; i < 3; i++)
    {
        cout << "Enter Name: ";
        cin >> students[i].name;

        cout << "Enter Marks: ";
        cin >> students[i].marks;
    }

    Student topper = students[0];

    for (int i = 1; i < 3; i++)
    {
        if (students[i].marks > topper.marks)
        {
            topper = students[i];
        }
    }

    cout << "\nTopper = "
         << topper.name << endl;

    cout << "Marks = "
         << topper.marks;

    return 0;
}

Sample Input

Rahul
82

Amit
91

Priya
88

Sample Output

Topper = Amit
Marks = 91

Explanation

The program stores student records in an array of structures and compares marks to identify the topper.

Concepts Covered

  • Array of Structures
  • Maximum Value
  • Record Comparison

13. C++ Program to Demonstrate Structure Initialization

Problem Statement

Write a C++ program to initialize a structure during declaration.

C++ Solution

#include <iostream>
using namespace std;

struct Student
{
    int rollNumber;
    string name;
    float marks;
};

int main()
{
    Student student = {101, "Rahul", 95.5};

    cout << "Roll Number: "
         << student.rollNumber << endl;

    cout << "Name: "
         << student.name << endl;

    cout << "Marks: "
         << student.marks;

    return 0;
}

Sample Output

Roll Number: 101
Name: Rahul
Marks: 95.5

Explanation

Structure members can be initialized directly at the time of object creation.

Concepts Covered

  • Structure Initialization
  • Object Declaration
  • Member Initialization

14. C++ Program to Access Structure Members Using a Pointer

Problem Statement

Write a C++ program to access structure members using a pointer.

C++ Solution

#include <iostream>
using namespace std;

struct Student
{
    int rollNumber;
    string name;
};

int main()
{
    Student student = {101, "Rahul"};

    Student *ptr = &student;

    cout << "Roll Number: "
         << ptr->rollNumber << endl;

    cout << "Name: "
         << ptr->name;

    return 0;
}

Sample Output

Roll Number: 101
Name: Rahul

Explanation

The arrow operator (->) is used to access structure members through a pointer.

Concepts Covered

  • Pointer to Structure
  • Arrow Operator (->)
  • Memory Address

15. C++ Program to Compare Structure and Union Memory Usage

Problem Statement

Write a C++ program to compare the memory allocation of a structure and a union.

C++ Solution

#include <iostream>
using namespace std;

struct StructureExample
{
    int id;
    float salary;
    char grade;
};

union UnionExample
{
    int id;
    float salary;
    char grade;
};

int main()
{
    cout << "Size of Structure = "
         << sizeof(StructureExample) << endl;

    cout << "Size of Union = "
         << sizeof(UnionExample);

    return 0;
}

Sample Output

Size of Structure = 12
Size of Union = 4

Note: The output may vary depending on the compiler and system architecture.

Explanation

A structure allocates separate memory for each member, whereas a union allocates memory equal to its largest member.

Concepts Covered

  • Structure
  • Union
  • Memory Allocation
  • sizeof() Operator

Chapter Summary

In this chapter, you learned how structures and unions help organize and manage related data in C++. Structures allocate separate memory for each data member, making them ideal for storing records such as students, employees, and products. Unions, on the other hand, share memory among all members, making them useful when memory optimization is required. You also practiced nested structures, arrays of structures, passing structures to functions, returning structures from functions, structure pointers, and comparing the memory usage of structures and unions.


Key Takeaways

  • Structures are user-defined data types used to group related variables.
  • Unions store multiple data members in the same memory location.
  • Every structure member has its own memory allocation.
  • Arrays of structures are useful for managing multiple records.
  • Nested structures improve code organization.
  • Structures can be passed to and returned from functions.
  • The arrow operator (->) is used with pointers to structures.
  • Structures are widely used in real-world applications such as banking systems, student management systems, inventory software, and hospital management systems.
  • Unions are commonly used in embedded systems and memory-constrained applications.
  • Understanding structures is essential before learning classes and object-oriented programming (OOP).

Frequently Asked Questions (FAQs)

1. What is a structure in C++?

A structure is a user-defined data type that groups multiple variables of different data types under a single name.


2. What is a union in C++?

A union is a user-defined data type in which all members share the same memory location.


3. What is the main difference between a structure and a union?

A structure allocates separate memory for every member, while a union shares one memory block among all members.


4. Can a structure contain another structure?

Yes. This is called a nested structure.


5. Can structures be passed to functions?

Yes. Structures can be passed to functions by value or by reference.


6. What is the arrow (->) operator?

The arrow operator is used to access structure members through a pointer.


7. Where are structures used in real-world applications?

Structures are commonly used in student management systems, employee databases, banking software, inventory management, hospital systems, and many other business applications.


8. Why are unions used?

Unions are primarily used to save memory when only one data member needs to be stored at a time, making them useful in embedded systems and low-level programming.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top