Structures in C are used to group variables of different data types under a single name. In this post, you’ll learn how to write a C program to read structure elements from the keyboard, along with a simple example and explanation.
What is a Structure in C?
A structure is a user-defined data type that allows grouping variables of different types. It is useful for modeling real-world entities like students, employees, products, etc.
Example:
struct Student {
int id;
char name[50];
float marks;
};
C Program to Read Structure Elements from Keyboard
#include <stdio.h>
// Define structure
struct Student {
int id;
char name[50];
float marks;
};
int main() {
struct Student s;
// Input from user
printf("Enter student ID: ");
scanf("%d", &s.id);
printf("Enter student name: ");
scanf("%s", s.name);
printf("Enter student marks: ");
scanf("%f", &s.marks);
// Display structure elements
printf("\nStudent Details:\n");
printf("ID: %d\n", s.id);
printf("Name: %s\n", s.name);
printf("Marks: %.2f\n", s.marks);
return 0;
}
Sample Output:
Enter student ID: 101
Enter student name: Alice
Enter student marks: 89.5
Student Details:
ID: 101
Name: Alice
Marks: 89.50
Explanation
- A
Student
structure is declared with three members:id
,name
, andmarks
. - The user is prompted to enter each value using
scanf()
. - The entered values are stored in the structure variable
s
. - The values are then printed using
printf()
.
Tips
- Use
fgets()
instead ofscanf("%s", ...)
if you want to allow spaces in names. - Always validate user input in real-world applications.
Final Thoughts
This example helps you understand how to define and use structures in C, especially how to read structure elements directly from user input. Structures are foundational for organizing complex data in a manageable way in C programming.