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 theprintf
function.struct Person
: Defines a structure namedPerson
with three members:name
(a character array),age
(an integer), andheight
(a float).struct Person person1 = {"Alice", 30, 5.5};
: Declares a variableperson1
of typestruct Person
and initializes it with values forname
,age
, andheight
.printf("Name: %s\n", person1.name);
: Prints thename
member ofperson1
.printf("Age: %d\n", person1.age);
: Prints theage
member ofperson1
.printf("Height: %.1f\n", person1.height);
: Prints theheight
member ofperson1
.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.