Structures and Union in C

Structures and Unions in C


Structure

A structure is a user-defined data type in C that allows combining data items of different types into one unit.

➡️ Structures are commonly used to represent a record.


Defining a Structure

To define a structure:

  • Use the keyword struct

  • Followed by an optional structure tag (name)

  • Then the body containing member definitions

Syntax

struct structure_name { member definition; member definition; ... };

Example

struct student { int rno; char name[50]; int mark; char sex; float height; } S;
  • student → structure name

  • S → structure variable


Important Points

  • Structure members can be:

    • Primitive data types

    • Arrays

    • Pointers

    • Other structures

  • A structure cannot contain an instance of itself

  • But it can contain a pointer to itself

  • We can create:

    • Array of structures

    • Pointer to structure


Accessing Structure Members

Members are accessed using the dot (.) operator

Example

S.mark = 45; S.sex = 'M';

Initializing a Structure

Structures can be initialized like other data types by assigning values to members.

Example 1: Single Structure

struct student { int rno; char name[50]; int mark; } S = {101, "akshay", 45};

Example 2: Array of Structures

struct student { int rno; char name[50]; int mark; } S[2] = {{101,"akshay",45},{102,"devi",47}};

Copying and Comparing Structures

  • Structures can be assigned to another structure of the same type

struct student { int rno; char name[50]; int mark; } S1, S2; S1 = S2; // Valid
  • Structures cannot be compared using relational operators (==, <, etc.)


Union

A union is a special user-defined data type that:

  • Stores different data types

  • Uses the same memory location

  • Only one member holds value at a time

➡️ Memory allocated = size of largest member


Defining a Union

Syntax

union union_name { member definition; member definition; ... };

Accessing Union Members

  • Similar to structures

  • Uses dot (.) operator


Example

#include <stdio.h> union test { int i; char c; } var; int main() { var.i = 65; printf("var.i=%d\n", var.i); printf("var.c=%c", var.c); return 0; }

Output

var.i=65 var.c=A

Similarities Between Structure and Union

  • Both are user-defined data types

  • Used to store different data types in one unit

  • Members can include:

    • Structures

    • Unions

    • Arrays

    • Bit-fields

  • Support operators:

    • =

    • sizeof

  • Assignment allowed only if:

    • Same member types

    • Same structure/union type

  • Can be:

    • Passed to functions by value

    • Returned from functions by value

  • Members accessed using . operator


Differences between structure and union

Feature                        Structure                                                        Union
Memory AllocationAllocates memory for all members separately. Total size = sum of sizes of all members.Allocates memory for only the largest member. All members share the same memory.
Member AccessAll members can store values simultaneously.                        Only one member can store value at a                         time. Writing to one member overwrites others.

Size                    Size = sum of sizes of all members.Size = size of the largest member.

Usage       Used when all members need to be                        stored  and accessed simultaneously.Used to store different data types in the same memory location (efficient memory usage).

InitializationCan initialize multiple members at once.Can initialize only one member at a time.

Assignment Structure variables of the same type can be  assigned to each other.Union variables of the same type can also be assigned to each other.

Access OperatorMembers accessed using . (dot) operator for variables, -> for pointers.Members accessed using . (dot) operator for variables, -> for pointers.

Common Use CasesRecords with multiple fields like student info, employee info, etc.Memory-efficient storage for different data types (e.g., variant types, embedded systems).


We can use a union inside a structure to save memory and use the fields efficiently.

Example:

struct stud { int rno; char name[50]; union { char pan[10]; long int adhar; } ident; } s;

In the above structure stud, you can use either pan or adhar for student identification.

The fields can be accessed as:

s.ident.pan // Access PAN s.ident.adhar // Access Aadhar

Note: Only one field will be used at a time, which helps save memory.


Sample Programs to try

Write a C program to define a structure Book( title, author, price). Write a function to accept and display a book's detail
#include <stdio.h>

// Define structure
struct Book {
    char title[100];
    char author[100];
    float price;
};

// Function to accept book details
void acceptBook(struct Book *b) {
    printf("Enter book title: ");
    getchar(); // to clear the newline from previous input
    fgets(b->title, sizeof(b->title), stdin);

    printf("Enter author name: ");
    fgets(b->author, sizeof(b->author), stdin);

    printf("Enter price: ");
    scanf("%f", &b->price);
}

// Function to display book details
void displayBook(struct Book b) {
    printf("\nBook Details:\n");
    printf("Title : %s", b.title);
    printf("Author: %s", b.author);
    printf("Price : %.2f\n", b.price);
}

int main() {
    struct Book myBook;

    // Accept book details
    acceptBook(&myBook);

    // Display book details
    displayBook(myBook);

    return 0;
}

Read two input each representing points in the Euclidean space, store these in structure variables and add the two point values.
#include <stdio.h>
struct Point
{
int x;
int y;
}p1,p2,p3;
int main()
{
printf("Enter the first point(x1,y1)\n");
scanf("%d,%d",&p1.x,&p1.y);
printf("Enter the second point(x2,y2)\n");
scanf("%d,%d",&p2.x,&p2.y);
p3.x=p1.x+p2.x;
p3.y=p1.y+p2.y;
printf("new point after addition\n");
printf("(%d,%d)\n",p3.x,p3.y);
Read two input each representing points in the Euclidean space, store these in structure variables and find the distance between them.
#include <stdio.h>
#include <math.h>
struct Point
{
int x;
int y;
}p1,p2;
int main()
{ float d;
printf("Enter the first point(x1,y1)\n");
scanf("%d,%d",&p1.x,&p1.y);
printf("Enter the second point(x2,y2)\n");
scanf("%d,%d",&p2.x,&p2.y);
d=(p2.x-p1.x)*(p2.x-p1.x)+(p2.y-p1.y)*(p2.y-p1.y);
d=sqrt(d);
printf("distance between the two points\n");
printf("%f\n",d);

Reading the admission number and name of N students and printing the roll list in the order of name.(university question)

#include <stdio.h>
#include <stdlib.h>
int main()
{
int N,i,j;
struct stud
{
 int adno;
 char name[50];
}s[100],t;
printf("enter no of students..N <100::");
scanf("%d",&N);
printf("Enter Admission no and Name of %d students\n",N);
for(i=0;i<N;i++)
scanf("%d %s",&s[i].adno,s[i].name);
//sorting the list according to name
for(i=0;i<N-1;i++)
for(j=0;j<N-1-i;j++)
 if(strcmp(s[j].name,s[j+1].name)>0)
    {
       t=s[j];
       s[j]=s[j+1];
       s[j+1]=t;
    }
//printing the roll list in the order of name
printf("Name....Admission Number\n");
for( i=0;i<N;i++)
printf("%-20s%5d\n",s[i].name,s[i].adno);
}
A library database maintains following details of the book  (bookid,name,author name,number of copies).Write a program to display the book details in the descending order of the number of copies available(university question)
#include <stdio.h>
struct library
{
  int bookid;
  char name[50];
  char author[50];
  int nc;
}book[100],t;
int main()
{
int n,i,j;
printf("Enter no of books:");
scanf("%d",&n);
printf("Enter the book details.bookid name author number of copies.\n");
for(i=0;i<n;i++)
scanf("%d %s %s %d",&book[i].bookid,book[i].name,book[i].author,&book[i].nc);
//sorting the book details in descending order according to number of copies
for(i=0;i<n-1;i++)
for(j=0;j<n-1-i;j++)
if(book[j].nc<book[j+1].nc)
{
t=book[j];
book[j]=book[j+1];
book[j+1]=t;
}
//printing the booklist
printf("Book-id bookname author number of copies\n");
for( i=0;i<n;i++)
printf("%-8d %-10s%-10s%5d\n",book[i].bookid,book[i].name,book[i].author,book[i].nc);
}
Student data base store rno,name,gender and CGPA of students.Prepare a rank list .Also prepare a list of students with CGPA less than 7( university question).
#include <stdio.h>
struct student
{
  int rno;
  char name[50];
  char gender[10];
  float cgpa;
}stud[100],t;
int main()
{
int n,i,j;
printf("Enter no of students:");
scanf("%d",&n);
printf("Enter the students details rno name gender cgpa \n");
for(i=0;i<n;i++)
scanf("%d %s %s %f",&stud[i].rno,stud[i].name,stud[i].gender,&stud[i].cgpa);
//sorting the stud details in decending order of cgpa
for(i=0;i<n-1;i++)
for(j=0;j<n-1-i;j++)
 if(stud[j].cgpa<stud[j+1].cgpa)
    {
       t=stud[j];
      stud[j]=stud[j+1];
       stud[j+1]=t;
    }
//printing the rank list
printf("rno name gender cgpa\n");
printf("***********************************\n");
for( i=0;i<n;i++)
printf("%-8d %-10s%-10s%5f\n",stud[i].rno,stud[i].name,stud[i].gender,stud[i].cgpa);
//list of students with cgpa less than 7
printf("list of students with cgpa less than 7\n");
for( i=0;i<n;i++)
if(stud[i].cgpa<7)
printf("%-8d %-10s%-10s%5f\n",stud[i].rno,stud[i].name,stud[i].gender,stud[i].cgpa);
}
Declare a structure namely Student to store the details (roll number, name, mark_for_C)of a student. Then, write a program in C to find the average mark obtained by the students in a class for the subject Programming in C (using the field mark_for_C). Use array of structures to store the required data ( university question)
#include <stdio.h>
struct student
{
  int rno;
  char name[50];
  int mark_for_c;
}stud[100];
int main()
{
int n,i,j;
float sum=0,average_mark;
printf("Enter no of students:");
scanf("%d",&n);
printf("Enter the students details rno name mark_for_c \n");
for(i=0;i<n;i++)
scanf("%d %s %d",&stud[i].rno,stud[i].name,&stud[i].mark_for_c);
//Find the average mark_for_c
for(i=0;i<n;i++)
  sum=sum+stud[i].mark_for_c;
average_mark=sum/n;
// Printing the students details and average mark_for_c
for(i=0;i<n;i++)
 printf("%3d %-25s %3d\n",stud[i].rno,stud[i].name,stud[i].mark_for_c);
printf("Average Mark=%10.3f\n",average_mark);
}
Write an easy to read C program to process the marks obtained by n students of a class and prepare their rank list based on the sum of the marks obtained. There are 3 subjects for which examinations are conducted.
struct student
{
int rno;
char name[50];
int m1;
int m2;
int m3;
int tot;
}stud[100],t;
int main()
{
int n,i,j;
printf("Enter no of students:");
scanf("%d",&n);
printf("Enter the students details rno name m1 m2 m3\n");
for(i=0;i<n;i++)
{
scanf("%d%s%d%d %d",&stud[i].rno,stud[i].name,&stud[i].m1,&stud[i].m2,&stud[i].m3);
stud[i].tot=stud[i].m1+stud[i].m2+stud[i].m3;
}
//sorting the stud details in descending order of total mark
for(i=0;i<n-1;i++)
for(j=0;j<n-1-i;j++)
if(stud[j].tot<stud[j+1].tot)
{
t=stud[j];
stud[j]=stud[j+1];
stud[j+1]=t;
}
//printing the rank list
printf("rno name m1 m2 m3 total\n");
printf("***********************************\n");
for( i=0;i<n;i++)
printf("%-4d%-10s%-4d%-4d%-4d%-6d\n",stud[i].rno,stud[i].name,stud[i].m1,stud[i].m2,stud[i].m3,stud[i].tot);
}

Write a C program to : ( university question)
(i) Create a structure containing the fields: Name, Price, Quantity, Total Amount.
(ii) Use separate functions to read and print the data.  
#include <stdio.h>
struct product
{
char name[50];
int price;
int qnty;
int tot;
}prod[100];
void read_data(struct product p[],int n)
{ int i;
printf("enter product details name price and quantity\n");
for(i=0;i<n;i++)
{
scanf("%s%d%d",p[i].name,&p[i].price,&p[i].qnty);
p[i].tot=p[i].qnty*p[i].price;
}
void print_data(struct product p[],int n)
{int i;
printf("name        price   quantity    total\n");
for(i=0;i<n;i++)
{
printf("%-10s%10d%10d%10d\n",p[i].name,p[i].price,p[i].qnty,p[i].tot);
p[i].tot=p[i].qnty*p[i].price;
}

int main()
{
int n,i,j;
printf("Enter no of products:");
scanf("%d",&n);
read_data(prod,n);
print_data(prod,n);
}

An online movie streaming platform wants to sort a list of movies based on user ratings to highlight the top-rated content. Write a C program that:
1. Accepts the names of movies along with their corresponding ratings
(out of 10).
2. Sorts the list in ascending order based on the ratings.
3. Displays the top 5 highest-rated movies from the list.

#include <stdio.h>
#include <string.h>

/* Structure definition */
struct Movie {
    char name[100];
    float rating;
};

/* Function to sort movies in ascending order of ratings */
void sortMovies(struct Movie movies[], int n) {
    int i, j;
    struct Movie temp;

    for (i = 0; i < n - 1; i++) {
        for (j = i + 1; j < n; j++) {
            if (movies[i].rating > movies[j].rating) {
                temp = movies[i];
                movies[i] = movies[j];
                movies[j] = temp;
            }
        }
    }
}

int main() {
    int n, i;

    printf("Enter number of movies: ");
    scanf("%d", &n);

    struct Movie movies[n];

    /* 1. Accept movie names and ratings */
    for (i = 0; i < n; i++) {
        printf("\nEnter details for Movie %d\n", i + 1);

        printf("Movie Name: ");
        scanf(" %[^\n]", movies[i].name);

        printf("Rating (out of 10): ");
        scanf("%f", &movies[i].rating);
    }

    /* 2. Sort movies by rating (ascending order) */
    sortMovies(movies, n);

    /* 3. Display top 5 highest-rated movies */
    printf("\nTop 5 Highest-Rated Movies:\n");
    printf("----------------------------\n");

    int start = (n < 5) ? 0 : n - 5;
    for (i = n - 1; i >= start; i--) {
        printf("Movie: %-20s Rating: %.1f\n",
               movies[i].name, movies[i].rating);
    }

    return 0;
}


C program to declare, initialize an UNION, example of UNION

#include <stdio.h>
// union declaration
typedef union {
char a;
int b;
double c;
} pack;
int main()
{
pack p; //union object/variable declaration
printf("\nOccupied size by union pack: %ld",sizeof(pack));

// assign value to each member one by one other it will replace last value
p.a='A';
printf("\nValue of a:%c",p.a);

p.b=10;
printf("\nValue of b:%d",p.b);
p.c=12345.6790;
printf("\nValue of c:%f",p.c);

// see, what will happen? if u will assign values together
p.a='A';
p.b=10;
p.c=12345.6790;

// here the last value of p.c will be accessed by all members
printf("\nValue of a:%f",p.a);
        printf("\nValue of a:%f",p.b);
         printf("\nValue of a:%f",p.c);
return 0;
}

outputs
Occupied size by union pack: 8
Value of a:A
Value of b:10
Value of c:12345.679000
Value of  a:12345.679000
Value of b:12345.679000
Value of c:12345.679000

A structure with fields hour, minutes and seconds is used to store a time. Create two time objects t1 and t2. Add these two and store these in another time object t3 using a function addtime
t3=addtime(t1,t2) 

#include <stdio.h>
struct Time
{
int h;
int m;
int s;
}t1,t2,t3;
struct Time addtime(struct Time t1,struct Time t2)
{
struct Time t3;
int sa,ma;
t3.s=(t1.s+t2.s)%60;
sa=(t1.s+t2.s)/60;
t3.m=(t1.m+t2.m+sa)%60;
ma=(t1.m+t2.m+sa)/60;
t3.h=(t1.h+t2.h+ma)%60;
return t3;
}
int main()
{

printf("Enter the first time(h:m:s)\n");
scanf("%d:%d:%d",&t1.h,&t1.m,&t1.s);
printf("Enter the second time(h:m:s)\n");
scanf("%d:%d:%d",&t2.h,&t2.m,&t2.s);
t3=addtime(t1,t2);
printf("New time t1+t2\n");
printf("%d:%d:%d\n",t3.h,t3.m,t3.s);
}
C program to demonstrate example of nested structure
#include <stdio.h>
struct student{
char name[30];
int rollNo;
struct dateOfBirth{
int dd;
int mm;
int yy;
}DOB; /*created structure varoable DOB*/
};

int main()
{
struct student std;
printf("Enter name: ");  scanf("%s",std.name);
printf("Enter roll number: "); scanf("%d",&std.rollNo);
printf("Enter Date of Birth [DD MM YY] format: ");
scanf("%d%d%d",&std.DOB.dd,&std.DOB.mm,&std.DOB.yy);
 printf("\nName : %s \nRollNo : %d \nDate of birth : %2d/%2d/%2d\n",std.name,std.rollNo,std.DOB.dd,std.DOB.mm,std.DOB.yy);
return 0;
}


Programs to Try
 
1.Using structure, read and print data of n employees (Name, Employee_Id and Salary)


2.Use structure to read the admission number and name of N students and printing the roll list in the order of name.(university question).

3.Declare a structure namely Student to store the details (roll number, name, mark_for_C) of a student. Then, write a program in C to find the average mark obtained by the students in a class for the subject Programming in C (using the field mark_for_C). Use array of structures to store the required data(university question)

4.Student data base store rno,name,gender and CGPA of students.Prepare a rank list .Also prepare a list of students with CGPA less than 7( university question).

5.A library database maintains following details of the book (bookid,name,author name,number of copies).Write a program to display the book details in the descending order of the number of copies available(university question)

6. Read two input each representing a point in the two dimensional Euclidean space,.store these in structure variables and add the two points.

7.A structure with fileds hour, minutes and seconds is used to store a time. Create two time objects t1 and t2. Add these two and store these in another time object t3 using a function addtime

t3=addtime(t1,t2)

Note that the add function should take two structure variables as arguments and return a structure

8.Create a structure stud with fields rno,name,m1,m2,m3,tot, where m1,m2,m3 mark in three subjects out of 50.Write a program which will read list of 'n' students details (rno,name,m1,m2,m3) and print the following. ( Use separate function if possible)

1.Rank list in the descending order of total mark
2.List of passed students in all subjects ( mark >=25 for pass)
3.List of failed students.( not passed all subjects)
4.Average marks in the three subjects.




Comments

Popular posts from this blog

Programming in C GXEST204 - KTU 2024 scheme syllabus notes pdf ------- Dr Binu V P

Structure of a C Program

Functions in C