BIT102 ยท 2081 ยท 5 marks
What is structure? Write a program to read roll, name and marks of 10 students using structure and then display all records. [1+4]
What is structure? Write a program to read roll, name and marks of 10 students using structure and then display all records. [1+4]
C ProgrammingChapter 9: Structures and UnionsStoring and displaying structure data
Quick answer
A structure is a user-defined data type in C that allows grouping of variables of different data types under a single name. Each variable inside a structure is called a member or field.
Structure in C
What is Structure?
Syntax:
struct structure_name {
data_type member1;
data_type member2;
...
};
Program: Read and Display Records of 10 Students
#include <stdio.h>
// Define the structure
struct Student {
int roll;
char name[50];
float marks;
};
int main() {
struct Student s[10];
int i;
// Read records of 10 students
printf("Enter details of 10 students:\n");
for (i = 0; i < 10; i++) {
printf("\nStudent %d:\n", i + 1);
printf("Enter Roll No : ");
scanf("%d", &s[i].roll);
printf("Enter Name : ");
scanf(" %s", s[i].name);
printf("Enter Marks : ");
scanf("%f", &s[i].marks);
}
// Display all records
printf("\n\n--- Student Records ---\n");
printf("%-10s %-20s %-10s\n", "Roll No", "Name", "Marks");
printf("----------------------------------------\n");
for (i = 0; i < 10; i++) {
printf("%-10d %-20s %-10.2f\n", s[i].roll, s[i].name, s[i].marks);
}
return 0;
}
Sample Output
Enter details of 10 students:
Student 1:
Enter Roll No : 1
Enter Name : Ram
Enter Marks : 85.5
...
--- Student Records ---
Roll No Name Marks
----------------------------------------
1 Ram 85.50
2 Sita 90.00
...
Key Points
| Feature | Description |
|---|---|
| Keyword | struct |
| Members | Can be of different data types |
| Array of structures | struct Student s[10] stores 10 students |
| Member access | Using dot operator (.) |
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.