Problem Solving using C Language

0 of 77 lessons complete (0%)

Structures

Structures

Arrays allow to define type of variables that can hold several data items of the same kind. Similarly structure is another user defined data type available in C that allows to combine data items of different kinds.

Structures are used to represent a record. Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book-

  • Title
  • Author
  • Subject
  • Book ID

Defining a Structure

struct structure_name {
    data_type member1;
    data_type member2;
    ...
    data_type member;
};
  • struct: The keyword used to define a structure.
  • structure_name: The name of the structure, used to declare variables of this type later.
  • member1, member2, ..., memberN: The variables (members) inside the structure. These members can be of different data types like int, float, char, etc.
struct Books 
{ 	char title[50]; 
	char author[50]; 
	char subject[100]; 
	int book_id; 
} book; 

Structure Variables

struct Person 
{ 
	// code 
}; 

int main() 
{ 
	struct Person person1, person2, p[20]; 
	return 0; 
} 
Another way to define Structure Variables


struct Person 
{ 
	// code 
} person1, person2, p[20]; 

Example

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

struct Person {
  char name[50];
  int citNo;
  float salary;
} person1;

int main() 
{

   strcpy(person1.name, "George Orwell");

   person1.citNo = 1984;
   person1. salary = 2500;

   printf("Name: %s\n", person1.name);
   printf("Citizenship No.: %d\n", person1.citNo);
   printf("Salary: %.2f", person1.salary);
   
   return 0;
}