14.
Structures
AIM:
To understand and implement the concept of structures in the C.
Description:
A structure in C is a user-defined data type that allows grouping different data types together.
These data types can be of various types, such as integers, floats, characters, etc. A structure is
defined using the struct keyword. It is helpful when we need to represent an entity that
requires multiple attributes (such as a "student" entity with name, roll number, marks, etc.).
Syntax to define a structure:
struct structure_name {
data_type member1;
data_type member2;
// Additional members
};
Algorithm:
1. Start
2. Define a structure using the struct keyword.
3. Declare the structure members with their respective data types.
4. Declare a variable of the structure type.
5. Initialize the structure members with values.
6. Access and manipulate the structure members using the dot (.) operator.
7. End
Program:
#include <stdio.h>
// Define the structure
struct Student
{
char name[50];
int roll_no;
float marks;
};
int main()
{
// Declare a variable of the structure
struct Student student1;
// Initialize structure members
printf("Enter student name: ");
fgets([Link], sizeof([Link]), stdin); // To accept strings with spaces
printf("Enter roll number: ");
scanf("%d", &student1.roll_no);
printf("Enter marks: ");
scanf("%f", &[Link]);
// Display structure information
printf("\nStudent Information:\n");
printf("Name: %s", [Link]);
printf("Roll Number: %d\n", student1.roll_no);
printf("Marks: %.2f\n", [Link]);
return 0;
}
Output:
Result: