0% found this document useful (0 votes)
8 views17 pages

PIC Exp.7

The document outlines an experiment on using structures and unions in C programming, aimed at managing employee data. It includes definitions, examples, and a detailed C program that allows functionalities such as adding, displaying, updating, and deleting employee records, as well as calculating total salaries. The program utilizes structures for common attributes and unions for role-specific data, emphasizing memory efficiency.

Uploaded by

scytherxrayan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views17 pages

PIC Exp.7

The document outlines an experiment on using structures and unions in C programming, aimed at managing employee data. It includes definitions, examples, and a detailed C program that allows functionalities such as adding, displaying, updating, and deleting employee records, as well as calculating total salaries. The program utilizes structures for common attributes and unions for role-specific data, emphasizing memory efficiency.

Uploaded by

scytherxrayan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

K. J.

Somaiya School of Engineering, Mumbai-77

(Somaiya Vidyavihar University)

Department of Science and Humanities

Course Name: Programming in C Semester: II

Date of
DIV/ Batch No: P2-3
Performance:

Student Name: Shivang Makwana Roll No: 16015124014

Experiment No: 7
Title: Structures and unions

Aim and Objective of the Experiment:

Write a program in C to demonstrate use of structures and unions.

COs to be achieved:

CO4: Design modular programs using functions and the use of structure and union.

Theory:

Introduction to Structures

A structure is a user-defined data type in C that groups variables of different types under a single
name. Structures are used when you need to store multiple related pieces of data, such as
information about a student, employee, or product, where each field might have a different data
type (e.g., integers, floats, and characters).

Example: A structure could be defined to store a student's name, age, and grade.

Declaring and Defining a Structure

To declare and define a structure in C, you first use the struct keyword, followed by a structure
name, and the members enclosed within curly braces {}. Each member can be of a different data
type.

Programming in C Semester: II Academic Year: 2024-25


K. J. Somaiya School of Engineering, Mumbai-77

(Somaiya Vidyavihar University)

Department of Science and Humanities

Syntax:

struct structure_name {

data_type member1;

data_type member2;

// more members

};

Example:

struct Student {

char name[50];

int age;

float grade;

};

This defines a structure Student with three members: a string for the name, an integer for the age,
and a float for the grade.

Structure Initialization

Structures can be initialized at the time of declaration or later by assigning values to their members
individually. If initialization during declaration, values for the members are assigned in the same
order as their declaration.

Syntax for initialization:

struct structure_name variable_name = {value1, value2, ...};

Programming in C Semester: II Academic Year: 2024-25


K. J. Somaiya School of Engineering, Mumbai-77

(Somaiya Vidyavihar University)

Department of Science and Humanities

Example:

struct Student student1 = {"John", 20, 85.5};

Alternatively, individual members can be initialized after declaration:

student1.age = 21;

strcpy(student1.name, "Alice");

student1.grade = 90.0;

Accessing and Displaying Structure Members

Structure members can be accessed using the dot (.) operator. The member values can be printed or
manipulated as required.

Syntax:

variable_name.member_name

Example:

printf("Name: %s\n", student1.name);

printf("Age: %d\n", student1.age);

printf("Grade: %.2f\n", student1.grade);

If a structure is pointed to by a pointer, the arrow (->) operator is used to access members.

Programming in C Semester: II Academic Year: 2024-25


K. J. Somaiya School of Engineering, Mumbai-77

(Somaiya Vidyavihar University)

Department of Science and Humanities

Example:

struct Student *ptr = &student1;

printf("Name: %s\n", ptr->name);

Array of Structures

An array of structures is used when you want to store multiple instances of a structure. Each
element of the array is a structure.

Syntax: struct structure_name array_name[size];

Example:

struct Student students[3];

students[0].age = 20;

strcpy(students[0].name, "Alice");

students[0].grade = 90.0;

To loop through an array of structures, you can use a for loop:

for (int i = 0; i < 3; i++) {

printf("Name: %s, Age: %d, Grade: %.2f\n", students[i].name, students[i].age,


students[i].grade);

Introduction to Unions

Programming in C Semester: II Academic Year: 2024-25


K. J. Somaiya School of Engineering, Mumbai-77

(Somaiya Vidyavihar University)

Department of Science and Humanities

A union is a user-defined data type similar to a structure, but with one key difference: all members
of a union share the same memory location. This means that at any given time, only one member of
the union can hold a value, making it more memory efficient when you don't need to store multiple
values simultaneously.

Syntax:

union union_name {

data_type member1;

data_type member2;

// more members

};

Example:

union Data {

int i;

float f;

char str[20];

};

In the above example, the Data union can store an integer, a float, or a string, but only one of these
at a time. The memory allocated for all the members of the union is the size of the largest member.

Accessing Members of a Union

Just like structures, union members are accessed using the dot (.) operator. However, because all
members share the same memory space, modifying one member will overwrite the other members'

Programming in C Semester: II Academic Year: 2024-25


K. J. Somaiya School of Engineering, Mumbai-77

(Somaiya Vidyavihar University)

Department of Science and Humanities

values.

Example:

union Data data;

data.i = 10; // Valid

data.f = 3.14; // Overwrites 'i'

data.str = "Hello"; // Overwrites 'f'

Problem Statements:

Design a C program to manage employee data using structures and unions. The program should
allow the following functionalities:

1. Employee Data Input:

o Each employee should have the following common attributes:

▪ Employee ID (integer)

▪ Name (string)

▪ Age (integer)

▪ Department (string)

▪ Basic Salary (float)

Programming in C Semester: II Academic Year: 2024-25


K. J. Somaiya School of Engineering, Mumbai-77

(Somaiya Vidyavihar University)

Department of Science and Humanities

o Depending on the employee's role, additional attributes should be stored:

▪ For Sales Employees:

▪ Commission (float)

▪ Sales Target (float)

▪ For Technical Employees:

▪ Project Name (string)

▪ Project Allowance (float)

o Use a union to store role-specific data efficiently.

2. Employee Data Display:

o Display all employee details, including role-specific information, in a formatted


manner.

3. Calculate Total Salary:

o For each employee, calculate the total salary based on their role:

▪ For Sales Employees: Total Salary = Basic Salary + Commission

▪ For Technical Employees: Total Salary = Basic Salary + Project Allowance

4. Search Employee by ID:

o Allow the user to search for an employee by their Employee ID and display their
details.

5. Update Employee Data:

o Allow the user to update specific details of an employee (e.g., name, age,
department, or role-specific data).

Programming in C Semester: II Academic Year: 2024-25


K. J. Somaiya School of Engineering, Mumbai-77

(Somaiya Vidyavihar University)

Department of Science and Humanities

6. Delete Employee Data:

o Allow the user to delete an employee's record by their Employee ID.

Requirements:

1. Use a structure to represent an employee with common attributes.

2. Use a union to store role-specific attributes (either for sales or technical employees).

3. Use an enum to differentiate between employee roles (e.g., SALES, TECHNICAL).

4. Implement dynamic memory allocation to store employee records.

5. Provide a menu-driven interface for the user to perform the above operations.

Code :

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

// Define a structure for employee details

struct Employee {

int id;

char name[50];

int age;

char department[30];

float basic_salary;

Programming in C Semester: II Academic Year: 2024-25


K. J. Somaiya School of Engineering, Mumbai-77

(Somaiya Vidyavihar University)

Department of Science and Humanities

char role[20]; // "Sales" or "Technical"

float extra; // Commission (for Sales) or Project Allowance (for Technical)

};

// Global array to store employees

struct Employee employees[100]; // Can store up to 100 employees

int num_employees = 0; // Counter for number of employees

// Function to add an employee

void addEmployee() {

printf("\nEnter Employee ID: ");

scanf("%d", &employees[num_employees].id);

printf("Enter Name: ");

scanf(" %[^\n]", employees[num_employees].name);

printf("Enter Age: ");

scanf("%d", &employees[num_employees].age);

printf("Enter Department: ");

scanf(" %[^\n]", employees[num_employees].department);

printf("Enter Basic Salary: ");

scanf("%f", &employees[num_employees].basic_salary);

printf("Enter Role (Sales/Technical): ");

scanf(" %[^\n]", employees[num_employees].role);

Programming in C Semester: II Academic Year: 2024-25


K. J. Somaiya School of Engineering, Mumbai-77

(Somaiya Vidyavihar University)

Department of Science and Humanities

if (strcmp(employees[num_employees].role, "Sales") == 0) {

printf("Enter Commission: ");

} else {

printf("Enter Project Allowance: ");

scanf("%f", &employees[num_employees].extra);

num_employees++;

printf("Employee added successfully!\n");

// Function to display all employees

void displayEmployees() {

if (num_employees == 0) {

printf("\nNo employees to display.\n");

return;

printf("\nEmployee List:\n");

for (int i = 0; i < num_employees; i++) {

printf("\nID: %d\n", employees[i].id);

printf("Name: %s\n", employees[i].name);

Programming in C Semester: II Academic Year: 2024-25


K. J. Somaiya School of Engineering, Mumbai-77

(Somaiya Vidyavihar University)

Department of Science and Humanities

printf("Age: %d\n", employees[i].age);

printf("Department: %s\n", employees[i].department);

printf("Basic Salary: %.2f\n", employees[i].basic_salary);

printf("Role: %s\n", employees[i].role);

if (strcmp(employees[i].role, "Sales") == 0) {

printf("Commission: %.2f\n", employees[i].extra);

} else {

printf("Project Allowance: %.2f\n", employees[i].extra);

// Function to calculate total salary

void calculateTotalSalary() {

float total = 0;

for (int i = 0; i < num_employees; i++) {

total += employees[i].basic_salary + employees[i].extra;

printf("\nTotal Salary of All Employees: %.2f\n", total);

// Function to search for an employee by ID

Programming in C Semester: II Academic Year: 2024-25


K. J. Somaiya School of Engineering, Mumbai-77

(Somaiya Vidyavihar University)

Department of Science and Humanities

void searchEmployee() {

int search_id;

printf("\nEnter Employee ID to search: ");

scanf("%d", &search_id);

for (int i = 0; i < num_employees; i++) {

if (employees[i].id == search_id) {

printf("\nEmployee Found:\n");

printf("ID: %d, Name: %s, Role: %s\n", employees[i].id, employees[i].name,


employees[i].role);

return;

printf("\nEmployee not found.\n");

// Function to update an employee's details

void updateEmployee() {

int update_id;

printf("\nEnter Employee ID to update: ");

scanf("%d", &update_id);

for (int i = 0; i < num_employees; i++) {

Programming in C Semester: II Academic Year: 2024-25


K. J. Somaiya School of Engineering, Mumbai-77

(Somaiya Vidyavihar University)

Department of Science and Humanities

if (employees[i].id == update_id) {

printf("\nEnter New Name: ");

scanf(" %[^\n]", employees[i].name);

printf("Enter New Age: ");

scanf("%d", &employees[i].age);

printf("Enter New Department: ");

scanf(" %[^\n]", employees[i].department);

printf("Enter New Basic Salary: ");

scanf("%f", &employees[i].basic_salary);

printf("Employee details updated!\n");

return;

printf("\nEmployee not found.\n");

// Function to delete an employee

void deleteEmployee() {

int delete_id;

printf("\nEnter Employee ID to delete: ");

scanf("%d", &delete_id);

for (int i = 0; i < num_employees; i++) {

Programming in C Semester: II Academic Year: 2024-25


K. J. Somaiya School of Engineering, Mumbai-77

(Somaiya Vidyavihar University)

Department of Science and Humanities

if (employees[i].id == delete_id) {

for (int j = i; j < num_employees - 1; j++) {

employees[j] = employees[j + 1]; // Shift elements left

num_employees--;

printf("Employee deleted successfully!\n");

return;

printf("\nEmployee not found.\n");

// Function to show the menu

void showMenu() {

int choice;

do {

printf("\nEmployee Management System\n");

printf("1. Add Employee\n");

printf("2. Display All Employees\n");

printf("3. Calculate Total Salary\n");

printf("4. Search Employee by ID\n");

printf("5. Update Employee\n");

printf("6. Delete Employee\n");

Programming in C Semester: II Academic Year: 2024-25


K. J. Somaiya School of Engineering, Mumbai-77

(Somaiya Vidyavihar University)

Department of Science and Humanities

printf("7. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1: addEmployee(); break;

case 2: displayEmployees(); break;

case 3: calculateTotalSalary(); break;

case 4: searchEmployee(); break;

case 5: updateEmployee(); break;

case 6: deleteEmployee(); break;

case 7: printf("Exiting the program.\n"); break;

default: printf("Invalid choice! Try again.\n");

} while (choice != 7);

// Main function

int main() {

showMenu();

return 0;

Programming in C Semester: II Academic Year: 2024-25


K. J. Somaiya School of Engineering, Mumbai-77

(Somaiya Vidyavihar University)

Department of Science and Humanities

Output:

Post Lab Subjective/Objective type Questions:

1. What is the difference between a structure and a union in C?

ANSWER:

1. Structure: Allocates separate memory for each member, allowing simultaneous access.

2. Union : Allocates shared memory, so only one member holds valid data at a time.

Programming in C Semester: II Academic Year: 2024-25


K. J. Somaiya School of Engineering, Mumbai-77

(Somaiya Vidyavihar University)

Department of Science and Humanities

Conclusion:

This experiment explored structures and unions in C for efficient data management. Structures
stored multiple attributes, while unions optimized memory. We implemented key functionalities,
reinforcing concepts like data abstraction, memory management, and modular programming.

Signature of faculty in-charge with Date:

Programming in C Semester: II Academic Year: 2024-25

You might also like