C++ Online Compiler
Example: Modular Student Structure Processing in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Modular Student Structure Processing #include <iostream> // For input/output operations #include <string> // For using std::string #include <vector> // For using std::vector (dynamic array) #include <numeric> // For std::accumulate (summing up scores) // Define the Student structure struct Student { int id; std::string name; double score; }; // Function to add a new student void addStudent(std::vector<Student>& students, int id, const std::string& name, double score) { Student newStudent = {id, name, score}; students.push_back(newStudent); std::cout << "Added student: " << name << std::endl; } // Function to display all student records void displayStudents(const std::vector<Student>& students) { if (students.empty()) { std::cout << "No student records to display." << std::endl; return; } std::cout << "\n--- Student Records ---" << std::endl; for (const Student& s : students) { std::cout << "ID: " << s.id << ", Name: " << s.name << ", Score: " << s.score << std::endl; } std::cout << "-----------------------" << std::endl; } // Function to calculate the average score of all students double calculateAverageScore(const std::vector<Student>& students) { if (students.empty()) { return 0.0; } double totalScore = 0.0; for (const Student& s : students) { totalScore += s.score; } return totalScore / students.size(); } int main() { std::vector<Student> students; // Add students using the addStudent function addStudent(students, 101, "Alice", 85.5); addStudent(students, 102, "Bob", 78.0); addStudent(students, 103, "Charlie", 92.3); // Display all students using the displayStudents function displayStudents(students); // Calculate and display the average score double average = calculateAverageScore(students); std::cout << "\nAverage Score: " << average << std::endl; // Example: Add another student and redisplay addStudent(students, 104, "Diana", 89.0); displayStudents(students); average = calculateAverageScore(students); std::cout << "\nNew Average Score: " << average << std::endl; return 0; }
Output
Clear
ADVERTISEMENTS