Computer for SEE and NEB

It is a complete SEE and NEB solution for computer science. It includes Computer Fundamentals, Database (SQL), Programming in C QBASIC, CSS, JavaScript, and PHP for beginners.

Breaking

Post Top Ad

Your Ad Spot

Saturday, October 1, 2022

Structure and Union in C programming

 Structure and Union in C programming


Structure and Union in C programming



Introduction:

C programming language provides the ability to create structures and unions, which are widely used in many applications. These constructs allow the programmer to group related data together and manipulate it efficiently. Structures and unions help in organizing the data in a better way and make it easy to maintain the code. In this article, we will discuss the concepts of structures and unions in C programming in detail.

Structure:

The structure is a collection of heterogeneous data types in a continuous memory location under a common name called structure tag or structure name.
 
Declaring a structure:

Like other variables and arrays, structure variables can also be initialized where they are declared.  The keyword struct is used to declare a structure followed by an identifier, which is also known as the tag name. The general syntax and example of a structure is defined in the following section.
 
 
In the above example, the name of the structure is employee, which contains four members: name[50] as string (collection of 50 characters), age and emp_id as integer, and salary as float..
 
Declaration of structure variables:

In a structure, the individual members can be of any valid data type of ordinary variables, arrays, pointers or even other structures. All the members' names of the structure should be unique. Once the new structure data has been defined, one or more variables can be declared to be of that type. Let us consider, the variables e1, e2, e3 can be declared to be of the type struct employee. The keyword struct is used to declare a structure and its variables or identifiers are declared by structure name separated by a comma as:
 
struct employee e1, e2, e3;
 
Following are the methods for structure declarations
 
 Initialization of structure variables

Structure variables are also declared just like the primary variable declaration. One-to-one relationship will be there between members and their values in structure. The general syntax and initialization process of the structure variable is illustrated as follows:
 
 
Accessing members of the structure

The member of the structure is usually processed individually, as separate entities. members of structure variables can be accessed using the member access operator dot (.) using the form.

Syntax:
structure_variable_name.structure_member
 
Example:
variable. member
Where variable refers to the name of structure type variable, and member refers to the name of a member within a structure.
 
For Example, to print the name of the employee
 printf("The employee's name is%s",emp1.name);
 
How structure elements are stored:
 
 Size of Structure
The elements of structure are always stored in a contiguous memory locations.  We can find the size of a structure by using sizeof operator, we can either use the structure variable name or the structure_name with the struct keyword.
For example: 
sizeof(struct employee)
sizeof(emp1)
sizeof(emp2)
 
Here if emp1 and emp2 are variables of type struct employee, then all the three expressions will give the same result.
 
#include<stdio.h>
#include<conio.h>
void main()
{
struct student
{
char name[20];
int rollno;
float per;
};
struct student stu={"Laxmi",7,76.2};
int s;
s=sizeof(stu);
printf("\nThe size of the structure is %d",s);
getch();
}
 
Array of structure
A collection of similar types of structures placed in a common variable name is called an array of structures.
Syntax:
         struct struct-name
              {
                  datatype var1;
                  datatype var2;
                  - - - - - - - - - -
                  - - - - - - - - - -
                  datatype varN;
                     };
              struct struct-name obj [ size ];
 
 
Structure and Functions

Like any ordinary variable, a structure variable can also be passed to a function. One may either pass individual structure elements or the entire structure at once.
Example:
#include <stdio.h>
#include <string.h>
 struct student
{
         int id;
         char name[20];
         float percentage;
};
 
void func(struct student record);
 
int main()
{
         struct student record;
 
         record.id=10;
         strcpy(record.name, "Ramesh Joshi");
         record.percentage = 76.5;
 
         func(record);
         return 0;
}
 
void func(struct student record)
{
         printf(" Id is: %d \n", record.id);
         printf(" Name is: %s \n", record.name);
         printf(" Percentage is: %f \n", record.percentage);
     }
 
 
Union

Unions are similar to the structure in the sense that they are also used to group together members of different data types.. The syntax used for the definition of a union, declaration of union variables, and for accessing members is similar to that used in structures, but here keyword union is used instead for the struct. The main difference between union and structure is in the way memory is allocated for members. In a structure, each member has its own memory location, whereas declared, the compiler allocated sufficient memory to hold the largest member in the union. Since all members share the same memory location hence we can use only one member at a time. Memory can be saved by using union.

The syntax of the definition of a union is:
union union­­_name{
datatype member1;
datatype member2;
………………………….
};
Like structure variables, the union variables can be declared along with the definition or separately. For example:
union union_name{
datatype member1;
datatype member2;
…………………………
}variable_name;
This can also be declared as:
union union_name variable_name;;
If we have a union variable then all members can be accessed using the dot( .) operator, and if we have a pointer to the union then the members can be accessed using the arrow (->) operator.
/*program for accessing union members*/
#include<stdio.h>
void main()
{
union result {
int marks;
char grade;
float per;
}res;
res.marks =90;
printf("Marks : %c\n", res.marks);
res.grage = 'A';
printf("Grade : %c\n", res.grade);
res.per = 85.5;
printf("percentage : %f\n", res.per);
}

Output
Marks : 90
Grade : A
Percentage : 85.500000

Before the first printf, the value 90 is assigned to the union member marks, so other members grade and per contain garbage value. After first printf, the value 'A' is assigned to the union member grade. Only one member of a union can hold value at a time, don't try to use all the members simultaneously. So a union variable of type result can be treated as either an int variable or char variable. It if the responsibility of the programmer to keep track of member that currently holds the value.

We know that due to sharing of memory, all the members can't hold values simultaneously. So during initialization also one member can be given an initial value, and this privilege is given to the first member. Hence only the first member of a union can be given an initial value. The type of the initialize should match the type of the first member. For example; we can initialize the above union variable as;
union result res = {78};

Syntax:

struct structure_name

{

data_type element1;

data_type element2;

………………….......

……………………….

………………………

data_type elementn;

};

 

Example:

struct employee

{

char name[50];

int age,emp_id;

float salary;

};

 

Method 1:

struct employee

{

char name[50];

int age,emp_id;

float salary;

};

struct employee e1, e2, e3;

 

Method 2:

struct employee

{

char name[50];

int age,emp_id;

float salary;

};e1, e2, e3;

 

Method 3:

struct

{

char name[50];

int age,emp_id;

float salary;

};e1, e2, e3;

 

All of the above methods are the same. Any one of the above methods can be used for variable declaration of structure.

 

Syntax:

struct structure_name

{

data_type element1;

data_type element2;

………………….......

……………………….

………………………

data_type elementn;

};

struct structure_variables = {Elements};

 

Example:

struct employee

{

char name[50];

int age,emp_id;

float salary;

};

struct employee e1 = {“Krishna”, 17, 12, 12000};

struct employee e2 = {“Srijana”, 18, 13, 15000};

struct employee e3 = {“Prakash”, 20, 14, 14500};

 

/*Memory arrangement of structure*/

#include<stdio.h>

#include<conio.h>

void main()

{

struct employee

         {

         int emp_id;

         char name[50];

         float salary;

         };

struct employee e1={100,"Bharat",20000.00};

clrscr();

printf("\n Address of Employee ID = %u",&e1.emp_id);

printf("\n Address of Name = %u",&e1.name);

printf("\n Address of Salary = %u",&e1.salary);

printf("\n Size of structure is %d bytes", sizeof(e1));

getch();

}

 

Output:

Address of Employee ID =  65000 (say)

Address of Name = 65002

Address of salary = 65052

Size of structure is 56 bytes

 

Example:

/* Array of Structures in C example */

#include <stdio.h>

struct Student

{

  char Student_Name[50];

  int C_Marks;

  int DataBase_Marks;

  int CPlus_Marks;

  int English_Marks;

};

int main()

{

  int i;

  struct Student Students[4] =

             {

              {"Suresh", 80, 70, 60, 70},

              {"Sunita", 85, 82, 65, 68},

              {"Mahesh", 75, 70, 89, 82},

              {"Zeba", 70, 65, 69, 92}

              };

    printf(".....Student Details....");

  for(i=0; i<4; i++)

  {

    printf("\n Student Name = %s", Students[i].Student_Name);

    printf("\n First Year Marks = %d", Students[i].C_Marks);

    printf("\n Second Year Marks = %d", Students[i].DataBase_Marks);

    printf("\n First Year Marks = %d", Students[i].CPlus_Marks);

    printf("\n Second Year Marks = %d", Students[i].English_Marks);

  }

  return 0;

}

 

Example:

/*Program to read rollno and name of 10 students by using array of structure*/

#include<stdio.h>

#include<conio.h>

void main()

{

struct student

{

int roll;

char name[20];

};

struct student stu[10];   /* array of structure */

int i;

 

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

{

printf("\nEnter rollno and name of student ");

scanf("%d%s",&stu[i].roll,stu[i].name);

}

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

printf("\n%d %s",stu[i].roll,stu[i].name);

getch();

}

 

 



Conclusion:

In conclusion, structures and unions in c programming are essential concepts in C programming, allowing the programmer to group related data together and manipulate it efficiently. The ability to use structures and unions in C programming enhances the readability, maintainability, and reusability of the code. By using structures and unions, the programmer can create complex data structures with ease and handle them more efficiently.

 


No comments:

Post a Comment

Post Top Ad

Your Ad Spot

Pages