In this C++ program, we have to store the information of 5 students (Name, Rollno, and Marks entered by the user ) in a structure and display it.
The structure is a user-defined data structure that helps to store the data of different data types using a single name. For example, suppose we need to store a student's data like Name, number, marks, etc, we can use a structure. The keyword struct is used to create a structure. the syntax for that is
struct structure_name
{
// data members
}
Note: for accessing a member and its data we have to use the dot '.' operator with the structure instance.
For storing the student data in C++, we have to declare a structure called student, with its data members as Name, Rollno, and Marks.
struct student
{
char name[50];
int roll;
float marks;
};
Then create a structure array of size 5. Ask the user to enter the details of 5 students' data like Name, Rollno, and Marks. Use a for loop
to add the information of 5 students we have created from the user screen. Finally, display the data entered by the user on the screen.
Step 1: Call the header file iostream
.
Step 2: Use the namespace std.
Step 3: Create struct student
Step 4: Create structure members' name, roll, and marks.
Step 5: create a structure array of size 5. s[5]
Step 6: Open the integer type main function; int main().
Step 7: Ask the user to enter the details of the student.
Step 8: Store the entered details in the array by using a for loop
Step 9: Display the details on the screen
Step 10: Exit
#include <iostream>
using namespace std;
struct student
{
char name[50];
int roll;
float marks;
} s[5];
int main()
{
cout << "Enter information of students: " << endl;
// storing information
for(int i = 0; i < 5; ++i)
{
s[i].roll = i+1;
cout << "For roll number" << s[i].roll << "," << endl;
cout << "Enter name: ";
cin >> s[i].name;
cout << "Enter marks: ";
cin >> s[i].marks;
cout << endl;
}
cout << "Displaying Information: " << endl;
// Displaying information
for(int i = 0; i < 5; ++i)
{
cout << "\nRoll number: " << i+1 << endl;
cout << "Name: " << s[i].name << endl;
cout << "Marks: " << s[i].marks << endl;
}
return 0;
}
Enter information of students: For roll number1, Enter name: a1 Enter marks: 55 For roll number2, Enter name: a2 Enter marks: 65 For roll number3, Enter name: a3 Enter marks: 95 For roll number4, Enter name: a4 Enter marks: 85 For roll number5, Enter name: a5 Enter marks: 25 Displaying Information: Roll number: 1 Name: a1 Marks: 55 Roll number: 2 Name: a2 Marks: 65 Roll number: 3 Name: a3 Marks: 95 Roll number: 4 Name: a4 Marks: 85 Roll number: 5 Name: a5 Marks: 25