Structure


What is Structure?

Structure is one of the important data type in C language. Structure is a programmers-defined data type in C language. Structure allows us to combine dissimilar data types to a single variable.

Syntax of Structure

A structure variable in C can be declared using “struct” keyword. The general form of structure is as under:

struct s_name {
            data_type1 var_1;
            data_type1 var_2;
            ….
            Data_typen var_n;
}struct_var1, struct_var2;

  • struct is keyword of C language.
  • Structure name is s_name
  •  var_1 is one of the variable of structure s_name with data type data_type1(which may be any valid C language data type like int, float, char, etc.)
  • struct_var1, struct_var2 are the variables of structure s_name;


Example of Structure declaration

struct student{
char name[20];
int rollno;
float percentage;
}s1, s2;


Difference between Array and Structure
  • Array is a collection of variables of same datatype
  • Structure is a collection of variables with different datatypes
  • Array uses index or subscript for accessing array elements
  • Structures uses (.) operator for accessing structure members
  • Array is a derived data type where as structure is defined by programmers


Sample Structure Program


C program to show use of Structure concept.


//C program to demonstrate use of Structure in Library System.

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

struct Book{
   int   book_id;
   char  book_title[30];
   char  book_publisher[30];
   char  book_subject[30];
};

void main( ) {

   struct Book myBook;  // Declare variable of type Book

   //Initialise values to myBook variable
   myBook.book_id=101;
  
   printf("Enter Book Title:");
   gets(myBook.book_title);
  
   printf("Enter Book Publisher Name:");
   gets(myBook.book_publisher);
  
   printf("Enter Book Subject:");
   gets(myBook.book_subject);
  
   /* print myBook details */
   printf( "Book ID: %d\n", myBook.book_id);
   printf( "Book Title: %s\n", myBook.book_title);
   printf( "Book Publisher Name : %s\n", myBook.book_publisher);
   printf( "Book Subject : %s\n", myBook.book_subject);
}

//Output
Enter Book Title:Computer Studies
Enter Book Publisher Name:ABC India
Enter Book Subject:Computer Science
Book ID: 101
Book Title: Computer Studies
Book Publisher Name : ABC India
Book Subject : Computer Science


5 comments:

  1. Please send me nested structure definition

    ReplyDelete
    Replies
    1. Pl. refer the Nested Structure example at following link:

      https://cprogrampracticals.blogspot.com/2019/03/nested-structure-in-c.html

      Delete