Advertisement

Responsive Advertisement

Structures in c

 Learning Sections          show

Structures in C

Example


#include<stdio.h>  // Include the standard input-output library

struct Person {
    char name[50];
    int age;
    float height;
};

int main() {
    // Declare and initialize a structure variable
    struct Person person1 = {"Alice", 30, 5.5};

    // Accessing structure members
    printf("Name: %s\n", person1.name);
    printf("Age: %d\n", person1.age);
    printf("Height: %.1f\n", person1.height);

    return 0;
}
    

Explanation:

Structures in C are user-defined data types that allow grouping of variables of different types under a single name.

In this example:

  • #include<stdio.h>: Includes the standard input-output library which allows us to use the printf function.
  • struct Person: Defines a structure named Person with three members: name (a character array), age (an integer), and height (a float).
  • struct Person person1 = {"Alice", 30, 5.5};: Declares a variable person1 of type struct Person and initializes it with values for name, age, and height.
  • printf("Name: %s\n", person1.name);: Prints the name member of person1.
  • printf("Age: %d\n", person1.age);: Prints the age member of person1.
  • printf("Height: %.1f\n", person1.height);: Prints the height member of person1.
  • return 0;: Ends the main function and returns 0 to the operating system, indicating that the program ended successfully.

In summary, structures in C allow you to create complex data types that group variables of different types, enabling more organized and manageable code.