Skip to main content

Structures and Unions

A structure is a user-defined data type available in C that allows to combining data items of different kinds. Structures are used to represent a record.
Defining a structure: To define a structure, you must use the struct keyword followed by an optional struct tag followed by the body of the struct. The struct statement defines a new data type, with more than one member. The format of the struct statement is as follows:
struct [structure name]
{
member definition;
member definition;
...
member definition;
};
Eg:
struct student
{
int rno;
char name[50];
int mark;
char sex;
float height;
} S;
Here S is a structure variable.
Structure member can be any valid data type(primitive, arrays) including other structures and pointers. A structure may not, for obvious reasons, contain instances of itself but may contain pointers to instances of itself.
We can also create array of structures or pointer to a struct.
Accessing the members of a structure:
The members of a structure can be accessed using the structure variable with .(dot) operator.The dot operator selects a particular member from the structure.
Eg:
S.mark=45
S.sex=’M’
Initializing Structure
A structure can be initialized in much the same way as any other data type. This consist of assigning some constants to the members of structure.
Eg:
struct student
{
int rno;
char name[50];
int mark;
} S={101,”akshay”,45};
struct student
{
int rno;
char name[50];
int mark;
} S[2]={{101,”akshay”,45},{102,”devi”,47}};

Copying and Comparing Structures
A structure can be assigned to another structure of the same type. But we cannot compare two structure variables.
Eg:
struct student
{
int rno;
char name[50];
int mark;
} S1,S2;
S1=S2;
Union
A union is a special data type available in C that allows storing different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple purposes.The amount of storage allocated to a union is sufficient to hold its largest member.
Defining a Union: To define a union, you must use the union statement in the same way as you did while defining a structure. The union statement defines a new data type with more than one member for your program. The format of the union statement is as follows:
union [union name]
{
member definition;
member definition;
...
member definition;
};
Defining and accessing the members of a union is similar to structure.
Eg:
#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;
}
var.i=65
var.c=A
Similarities between Structure and Union
Both are user-defined data types used to store data of different types as a single unit.
Their members can be objects of any type, including other structures and unions or arrays. A member can also consist of a bit field.
Both structures and unions support only assignment = and sizeof operators. The two structures or unions in the assignment must have the same members and member types.
A structure or a union can be passed by value to functions and returned by value by functions. The argument must have the same type as the function parameter. A structure or union is passed by value just like a scalar variable as a corresponding parameter.

‘.’ operator is used for accessing members.

Differences between structure and union
We can use an union inside a structure and save the memory and use the field efficiently
structure 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 of the students for identification and can be accessed like
s.ident.pan  or s.ident.adhar.
Only one item will be used at a time and hence we can save memory.

Sample Programs to try
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);
}

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

KTU Mandatory C programs for Laboratory and Solutions

LIST OF LAB EXPERIMENTS 1. Familiarization of Hardware Components of a Computer 2. Familiarization of Linux environment – Programming in C with Linux 3. Familiarization of console I/O and operators in C     i) Display “Hello World”     ii) Read two numbers, add them and display their sum     iii) Read the radius of a circle, calculate its area and display it 4. Evaluate the arithmetic expression ((a -b / c * d + e) * (f +g))   and display its solution. Read the values of the variables from the user through console 5. Read 3 integer values, find the largest among them. 6. Read a Natural Number and check whether the number is prime or not 7. Read a Natural Number and check whether the number is Armstrong or not 8. Read n integers, store them in an array and find their sum and average 9. Read n integers, store them in an array and search for an element in the    array using an algorithm for Linear Search 10.Read n integers, store them in an array and sort the elements in t

PROGRAMMING IN C KTU EST 102 THEORY AND LAB NOTES

PROGRAMMING IN C  KTU  EST 102  THEORY AND LAB   COMMON FOR ALL BRANCHES About Me Syllabus Theory Syllabus Lab Model Question Paper EST 102 Programmin in C University Question Papers  and evaluation scheme   EST 102 Programming in C  Introduction( Lab) Introduction to C programming Linux History and GNU How to create a bootable ubuntu USB stick Installing  Linux Install Linux within  Windows Virtual Box and WSL Linux Basic Features and Architecture Basic Linux Commands Beginning C Programming Compiling C programs using gcc in Linux Debugging C program using gdb Module 1: Basics of computer hardware and software          Module-1 Reading Material Basics of Computer Architecture Hardware and Software System Software and Application Software  Programming Languages ( High level, Low level and Machine Language) and Translators ( Compiler, Interpreter, Assembler) Algorithm, Flowcharts and Pseudo code Program Development Structured Programming Basics of hardware ( video) Know about Motherboar