BIT102 ยท 2078 ยท 5 marks
Write a program to store and display basic information (Roll, name, address, email. and phone) of students of using a structure.
Write a program to store and display basic information (Roll, name, address, email. and phone) of students of using a structure. [5]
C ProgrammingChapter 9: Structures and UnionsStoring and displaying structure data
Quick answer
A structure in C is a user-defined data type that groups related variables of different data types under a single name.
Program to Store and Display Student Information Using Structure
Concept
C Program
#include <stdio.h>
#include <string.h>
// Define the structure
struct Student {
int roll;
char name[50];
char address[100];
char email[50];
char phone[15];
};
int main() {
int i, n;
printf("Enter number of students: ");
scanf("%d", &n);
// Declare an array of structures
struct Student s[n];
// Input student information
for (i = 0; i < n; i++) {
printf("\n--- Enter details for Student %d ---\n", i + 1);
printf("Roll Number : ");
scanf("%d", &s[i].roll);
printf("Name : ");
getchar(); // clear input buffer
fgets(s[i].name, sizeof(s[i].name), stdin);
s[i].name[strcspn(s[i].name, "\n")] = '\0'; // remove newline
printf("Address : ");
fgets(s[i].address, sizeof(s[i].address), stdin);
s[i].address[strcspn(s[i].address, "\n")] = '\0';
printf("Email : ");
fgets(s[i].email, sizeof(s[i].email), stdin);
s[i].email[strcspn(s[i].email, "\n")] = '\0';
printf("Phone : ");
fgets(s[i].phone, sizeof(s[i].phone), stdin);
s[i].phone[strcspn(s[i].phone, "\n")] = '\0';
}
// Display student information
printf("\n========== Student Information ==========\n");
for (i = 0; i < n; i++) {
printf("\nStudent %d:\n", i + 1);
printf(" Roll Number : %d\n", s[i].roll);
printf(" Name : %s\n", s[i].name);
printf(" Address : %s\n", s[i].address);
printf(" Email : %s\n", s[i].email);
printf(" Phone : %s\n", s[i].phone);
}
return 0;
}
Sample Output
Enter number of students: 2
--- Enter details for Student 1 ---
Roll Number : 101
Name : Ram Sharma
Address : Kathmandu
Email : [email protected]
Phone : 9841000001
--- Enter details for Student 2 ---
Roll Number : 102
Name : Sita Thapa
Address : Pokhara
Email : [email protected]
Phone : 9841000002
========== Student Information ==========
Student 1:
Roll Number : 101
Name : Ram Sharma
Address : Kathmandu
Email : [email protected]
Phone : 9841000001
Student 2:
Roll Number : 102
Name : Sita Thapa
Address : Pokhara
Email : [email protected]
Phone : 9841000002
Key Points
| Feature | Detail |
|---|---|
struct Student | User-defined structure with 5 members |
struct Student s[n] | Array of structures to store multiple students |
s[i].roll | Dot operator used to access structure members |
fgets() | Used to read strings with spaces |
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.