C PROGRAMING: A Beginner’s Course | CHAPTER 8 Structure, Unions and Enumerated Data types

Immanuel Training Institute proudly presents free software courses

To get certificate Contact: iits.certificate@gmail.com


CHAPTER 1   Introduction and structure of C program

CHAPTER 2   Data types, Constants, Variables and I/O Statements

CHAPTER 3   Operators and Expressions

CHAPTER 4   Control Statements

CHAPTER 5   Arrays

CHAPTER 6   String Manipulations

CHAPTER 7   Functions

CHAPTER 8   Structure, Unions and Enumerated Data types  

CHAPTER 9   Pointers                

CHAPTER 8

STRUCTURES, UNIONS & ENUMERATED

STRUCTURES

A structure is a user defined data type. A structure creates a data type that can be used to group items of possibly different types into a single type. Structures help to organize data, particularly in large programmers, because they allow a group of related variables to be treated as a single unit.

Syntax

Structure definition

struct  struct_name

{

       data_type  member1_varible_name;

data_type  member2_varible_name;

       data_type  member3_varible_name;

       .

       .

       .

data_type  memberN_varible_name;

} struct_varibable1;-----------------> Structure declaration

Structure declaration:

     struct  struct_name  struct_variable2;

*The key word of "struct" introduces a structure declaration, which is a list of declarations enclosed in braces. The variables declared within the structure declaration are called its members.

            *A structure declaration that is not followed by a list of variables reserves no storage space, it merely describes the template. In other words, the STRUCTURE is only defined, not declared.

Example

struct  employee

{

               char name[27];

               char addr[20];

               float salary;

}emp1;

struct employee emp2;

-        emp1, emp2 are the structure variables

-        employee is a used defined data type(structure)

-        name, addr, salary are the members of the structure

-        accessing structure member,  emp1.name, emp1.addr, emp1.salary,   emp2.name, emp2.addr, emp2.salary

ARRAYS OF STRUCTURES:-

            We use structures to describe the format of a number of related variables. In such cases, we may declare an array of structures, each element of the array representing a structure variable.

Syntax

struct  struct_name  struct_variable_name[N];

-        ‘N’ is the size of an array

Example

struct employee emp[10];

-        accessing structure member,  emp[i].name, emp[i].addr, emp[i].salary,   where i=1-10;

STRUCTURES WITHIN STRUCTURES:-

            Structures within structures mean nesting of structures. Nesting of structures is permitted in C. Let us consider the following structure defined to store information about the salary of employees.

struct salary

{

     char name;

     char dept;

     struct

     {

                 int phone_bill;

                 int house_rent;

                 int travel_bill;

     }allowance;

       }emp;

-        accessing structure member,  emp.name, emp.dept, emp.allowance.phone_bill, emp.allowance.house_rent,  emp.allowance.travel_bill

STRUCTURES AND FUNCTION

Structure as function argument:

            C supports the passing of structure values as arguments to functions. There are three methods by which the values of a structure can be transferred from one function to another.

1.     Passing each item of the structure as a function argument. It is similar to passing normal values as arguments. Although it is easy to implement, we don’t use this approach because if the size of a structure is a bit larger, then our life becomes miserable.

2.     Pass the whole structure as a value.

3.     We can also Pass the address of the structure (pass by reference).

UNIONS

A union is a user defined 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. A unions definition, declaration & accessing a member is similar to as a structure. The only difference is allocating a memory location, in structure allocates separate space for each of the members.

Example

union course

{

            int major;

            int minor[10];

}course1;

ENUMERATION

Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain.

Definition:

enum enum_name{const1, const2, ....... };

Declaration:

            enum enum_name enum_variable_num;

Example:

enum week{sunday, monday, tuesday, wednesday, thursday, friday, saturday};

            enum week day;

-        Now the value of sunday=0, monday=1, Tuesday=2 , Wednesday=3, Thursday=4, Friday=5, Saturday=6

enum week{Sunday=11, monday, tuesday, wednesday, thursday, friday, saturday};           

-        Now the value of sunday=11, monday=12, Tuesday=13 , Wednesday=14, Thursday=15, Friday=16, Saturday=17

enum week{Sunday=11, monday, tuesday, Wednesday=20, thursday, friday, saturday};      

-        Now the value of sunday=11, monday=12, Tuesday=13 , Wednesday=20, Thursday=21, Friday=22, Saturday=23

EXAMPLE PROGRAMS

1.     Structure example program

#include<stdio.h>

#include<conio.h>

struct date

{

int day;

float month;

int year;

};

void main()

{

struct date d1,d2;

clrscr();

printf("Enter the date(DD/MM/YYYY):");

scanf("%d%f%d",&d1.day,&d1.month,&d1.year);

d2=d1;

printf("\nToday's date is %d/%.0f/%d",d2.day,d2.month,d2.year);

printf("The size of the structure is %d",sizeof(d2));

getch();

}

2.     Structure example program

#include<stdio.h>

#include<conio.h>

#include<string.h>

struct employee

{

char name[10];

int age;

float sal;

}emp1;

void main()

{

struct employee emp2={"xxx",20,5000};

struct employee emp3;

clrscr();

strcpy(emp3.name,"yyy");

emp3.age=22;

emp3.sal=6000;

printf("Enter the employee 1 details(name,age,salary):");

scanf("%s%d%f",emp1.name,&emp1.age,&emp1.sal);

printf("\nEmployee 1 details:");

printf("\nName    :  %s",emp1.name);

printf("\nAge     :  %d",emp1.age);

printf("\nSalary  :  %f",emp1.sal);

printf("\n\nEmployee 2 details:");

printf("\nName    :  %s",emp2.name);

printf("\nAge     :  %d",emp2.age);

printf("\nSalary  :  %f",emp2.sal);

printf("\n\nEmployee 3 details:");

printf("\nName    :  %s",emp3.name);

printf("\nAge     :  %d",emp3.age);

printf("\nSalary  :  %f",emp3.sal);

getch();

}

3.     Structure example program

#include<stdio.h>

#include<conio.h>

struct student

{

int m1,m2,m3;

float avg;

}stu;

void main()

{

int tot;

clrscr();

printf("Enter the marks:");

scanf("%d%d%d",&stu.m1,&stu.m2,&stu.m3);

tot=stu.m1+stu.m2+stu.m3;

stu.avg=tot/3;

printf("\nMark list:");

printf("\nM1 :           %d",stu.m1);

printf("\nM2 :           %d",stu.m2);

printf("\nM3 :           %d",stu.m3);

printf("\nTotal          :           %d",tot);

printf("\nAvg            :           %f",stu.avg);

getch();

}

4.     Structure inside structure example program

#include<stdio.h>

#include<conio.h>

struct date

{

int m,d,y;

};

struct time

{

int min,sec,ho;

};

struct d_and_time

{

struct date sd;

struct time st;

}sd_t;

void main()

{

clrscr();

printf("Enter the date(mm/dd/yyyy):");

scanf("%d%d%d",&sd_t.sd.m,&sd_t.sd.d,&sd_t.sd.y);

printf("Enter the time(minutes:seconds:hours):");

scanf("%d%d%d",&sd_t.st.min,&sd_t.st.sec,&sd_t.st.ho);

printf("\nThis is what you have entred:");

printf("\nDate           :  %d/%d/%d",sd_t.sd.m,sd_t.sd.d,sd_t.sd.y);

printf("\nTime  :  %d:%d:%d",sd_t.st.min,sd_t.st.sec,sd_t.st.ho);

printf("\n\n****End of Nested struture*****");

getch();

}

5.     Array of Structure example program

#include<stdio.h>

#include<conio.h>

struct stu

{

char name[10];

int m1,m2,m3;

int tot;

float avg;

}s[10];

void main()

{

int n,i;

clrscr();

printf("Enter the no. of students:");

scanf("%d",&n);

          for(i=1;i<=n;i++)

          {

                      printf("Enter the student[%d] details",i);

                      printf("(Name/marks):\n");

                      scanf("%s%d%d%d",s[i].name,&s[i].m1,&s[i].m2,&s[i].m3);

                      s[i].tot=s[i].m1+s[i].m2+s[i].m3;

                      s[i].avg=s[i].tot/3;

          }

printf("\nSTUDENT DETAILS:\n");

printf("----------------\n");

          for(i=1;i<=n;i++)

          {

                      printf("\nStudent[%d] details:",i);

                      printf("\nName : %s",s[i].name);

                      printf("\nM1   : %d",s[i].m1);

                      printf("\nM2   : %d",s[i].m2);

                      printf("\nM3   : %d",s[i].m3);

                      printf("\nTotal: %d",s[i].tot);

                      printf("\nAvg  : %f",s[i].avg);

          }

getch();

}

6.     Structure and union example program

#include<stdio.h>

#include<conio.h>

union size

{

int a;

float b;

char c;

}s1;

struct size1

{

int a;

float b;

char c;

}s2;

void main()

{

clrscr();

printf("\nThe size of integer variable is %d",sizeof(s1.a));

printf("\nThe size of float variable is %d",sizeof(s1.b));

printf("\nThe size of character variable is %d",sizeof(s1.c));

printf("\nThe size of union variable is %d",sizeof(s1));

printf("\nThe size of structure variable is %d",sizeof(s2));

getch();

}

7.     Structure and enum example program:

#include<stdio.h>

#include<conio.h>

enum dept

{

assembly=100,

manufacturing,

accounts,

stores

};

struct employee

{

char name[10];

int age;

float sal;

enum dept d1;

};

void main()

{

struct employee emp;

clrscr();

printf("Enter the employee name,age,salary&department:");

scanf("%s%d%f%s",emp.name,&emp.age,&emp.sal,emp.d1);

printf("\nEMPLOYEE DETAILS:\n");

printf("\nName              : %s",emp.name);

printf("\nAge        : %d",emp.age);

printf("\nSalary     : %d",emp.sal);

printf("\nDepartment : %d",emp.d1);

getch();

}

8.     Enum example program

#include<stdio.h>

enum week{Mon=10, Tue, Wed, Thur, Fri=10, Sat=16, Sun};

enum day{Mond, Tues, Wedn, Thurs, Frid=18, Satu=11, Sund};

int main()

{

      clrscr();

printf("The value of enum week: %d\t%d\t%d\t%d\t%d\t%d\t%d\n\n",Mon , Tue, Wed, Thur, Fri, Sat, Sun);

printf("The default value of enum day: %d\t%d\t%d\t%d\t%d\t%d\t%d",Mond , Tues, Wedn, Thurs, Frid, Satu, Sund);

            getch();

      }

9.     Structure as a function arugument

#include<stdio.h>

#include<conio.h>

struct student

{

int no;

char name[10];

int m1,m2,m3;

};

int tot;

float avg;

void main()

{

struct student std;

clrscr();

printf("Enter the no:");

scanf("%d",&std.no);

printf("Enter the name:");

scanf("%s",std.name);

printf("Enter the marks:");

scanf("%d%d%d",&std.m1,&std.m2,&std.m3);

cal(std.m1,std.m2,std.m3);

display(std);

getch();

}

cal(int x,int y,int z)

{

tot=x+y+z;

avg=tot/3;

}

display(struct student s1)

{

printf("\nSTUDENT DETAILS:\n");

printf("----------------\n");

printf("\nName   :%s",s1.name);

printf("\nNo     :%d",s1.no);

printf("\nM1     :%d",s1.m1);

printf("\nM2     :%d",s1.m2);

printf("\nM3     :%d",s1.m3);

printf("\nTotal  :%d",tot);

printf("\nAverage:%f",avg);

}

Contact Form

Name

Email *

Message *