C program to compare the structure variables


In C programming language, a structure is a collection of different datatype variables, which are grouped together under a single name.

Declaration and initialization of structures

The general form of a structure declaration is as follows −

datatype member1;
struct tagname{
   datatype member2;
   datatype member n;
};

Here,

  • struct is a keyword.
  • tagname specifies the name of structure.
  • member1, member2 specifies the data items that make up structure.

For example,

struct book{
   int pages;
   char author [30];
   float price;
};

Structure variables

There are three methods of declaring structure variables, which are as follows −

First method

struct book{
   int pages;
   char author[30];
   float price;
}b;

Second method

struct{
   int pages;
   char author[30];
   float price;
}b;

Third method

struct book{
   int pages;
   char author[30];
   float price;
};
struct book b;

Initialization and accessing of structures

The link between a member and a structure variable is established by using a member operator (or) a dot operator.

Initialization can be done in the following methods −

First method

struct book{
   int pages;
   char author[30];
   float price;
} b = {100, “balu”, 325.75};

Second method

struct book{
   int pages;
   char author[30];
   float price;
};
struct book b = {100, “balu”, 325.75};

Third method by using a member operator

struct book{
   int pages;
   char author[30];
   float price;
} ;
struct book b;
b. pages = 100;
strcpy (b.author, “balu”);
b.price = 325.75;

Example

Following is the C program for the comparison of structure variables −

 Live Demo

struct class{
   int number;
   char name[20];
   float marks;
};
main(){
   int x;
   struct class student1 = {001,"Hari",172.50};
   struct class student2 = {002,"Bobby", 167.00};
   struct class student3;
   student3 = student2;
   x = ((student3.number == student2.number) &&
   (student3.marks == student2.marks)) ? 1 : 0;
   if(x == 1){
      printf("
student2 and student3 are same

");       printf("%d %s %f
", student3.number,       student3.name,       student3.marks);    }    else    printf("
student2 and student3 are different

"); }

Output

When the above program is executed, it produces the following output −

student2 and student3 are same
2 Bobby 167.000000

Updated on: 26-Mar-2021

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements