WAP to create Database using array of structure & display it in C
#include <stdio.h>
struct Student {
int rollNo;
char name[50];
float marks;
};
int main() {
int numStudents;
printf("Enter the number of students: ");
scanf("%d", &numStudents);
struct Student students[numStudents];
for (int i = 0; i < numStudents; i++) {
printf("Enter details for student %d:\n", i + 1);
printf("Roll No: ");
scanf("%d", &students[i].rollNo);
printf("Name: ");
scanf("%s", students[i].name);
printf("Marks: ");
scanf("%f", &students[i].marks);
printf("\n");
}
printf("Student Database:\n");
for (int i = 0; i < numStudents; i++) {
printf("Student %d\n", i + 1);
printf("Roll No: %d\n", students[i].rollNo);
printf("Name: %s\n", students[i].name);
printf("Marks: %.2f\n", students[i].marks);
printf("\n");
}
return 0;
}
Explanation:
We start by including the standard input/output library
stdio.h
, which provides functions for input and output operations in C.Next, we define a structure called
Student
with three members:rollNo
(integer),name
(character array of size 50), andmarks
(float).In the
main
function, we declare a variablenumStudents
to store the number of students.We prompt the user to enter the number of students using
printf
and read the input usingscanf
.We then declare an array of structures
students
with sizenumStudents
to store the student details.Using a
for
loop, we iteratenumStudents
times to input the details for each student.Inside the loop, we prompt the user to enter the details for each student, such as roll number, name, and marks, using
printf
. We read the input usingscanf
and store the values in the corresponding members of thestudents
array.After the loop, we display the student database using another
for
loop. We iterate over each student in thestudents
array and print their roll number, name, and marks usingprintf
.Finally, we return
0
from themain
function, indicating successful execution of the program.
This program allows the user to create a database of students by entering their details and then displays the database on the console.