Structures in C Programming with Examples

 

Structures in C Programming

A structure in C is a user-defined data type that allows you to group different types of data together. It is useful when you want to store related information in a single unit.


Why Use Structures?

  • Store multiple data types together
  • Represent real-world entities (Student, Employee, Book, etc.)
  • Organize complex data easily

Structure Declaration

Syntax:


struct structure_name {

    data_type member1;

    data_type member2;

};

Example:


struct Student {

    int roll;

    char name[50];

    float marks;

};


Creating Structure Variables


struct Student s1;


Accessing Structure Members

Use the dot (.) operator to access members.


s1.roll = 101;

strcpy(s1.name, "Rahul");

s1.marks = 85.5;


Complete Example


#include <stdio.h>

#include <string.h>

struct Student {

    int roll;

    char name[50];

    float marks;

};

int main() {

    struct Student s1;

    s1.roll = 1;

    strcpy(s1.name, "Ankit");

    s1.marks = 90.5;

    printf("Roll: %d\n", s1.roll);

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

    printf("Marks: %.2f", s1.marks);

    return 0;

}


Advantages of Structures

  • Better data organization
  • Easy to handle complex records
  • Foundation for advanced concepts like structures with pointers

Conclusion

Structures allow grouping of related data into one unit. The next important topic after structures is Unions in C programming.

Comments

Popular posts from this blog

What is C programming?

Arrays in C Programming for Beginners with Examples