Unlocking the Power of Structures in C++ Programming
Are you ready to take your C++ skills to the next level? Let’s dive into an exciting example that combines arrays and structures to store and display information about students.
Creating a Student Structure
Imagine you’re tasked with storing data about 10 students, including their names, roll numbers, and marks. To accomplish this, we’ll create a structure called student
with three members: name
(a string), roll
(an integer), and marks
(a float).
Storing Student Information in an Array
Next, we’ll create an array of student
structures with a size of 10. This will allow us to store information about all 10 students in a single array. Using a for
loop, we’ll prompt the user to input the details of each student, which will then be stored in the array.
Displaying Student Information
Once the user has entered all the information, our program will display the data for each student on the screen. This is where the magic happens! You’ll see how easily we can access and manipulate the data using structures and arrays.
Putting it All Together
Here’s an example of what the program might look like:
“`
// Define the student structure
struct student {
string name;
int roll;
float marks;
};
int main() {
// Create an array of student structures
struct student students[10];
// Use a for loop to input student information
for (int i = 0; i < 10; i++) {
cout << "Enter student " << i + 1 << " information:" << endl;
cout << "Name: ";
cin >> students[i].name;
cout << "Roll: ";
cin >> students[i].roll;
cout << "Marks: ";
cin >> students[i].marks;
}
// Display student information
for (int i = 0; i < 10; i++) {
cout << "Student " << i + 1 << " information:" << endl;
cout << "Name: " << students[i].name << endl;
cout << "Roll: " << students[i].roll << endl;
cout << "Marks: " << students[i].marks << endl;
}
return 0;
}
“`
With this example, you’ll gain a deeper understanding of how to work with structures and arrays in C++ programming. So, what are you waiting for? Start coding and unlock the full potential of C++!