The objective is to take input of subjects and their marks from a user and finally display them as a report card. Everything works as expected except that the compiler prints the name of the last subject entered for each different subject name in the final report.
Here is the C++ code that I tried:
#include <iostream>
using namespace std;
int main() {
string fname, lname;
int subjects;
float totalMarks;
cout << "Enter your first name: ";
cin >> fname;
cout << "Enter your last name: ";
cin >> lname;
cout << "Enter total marks: ";
cin >> totalMarks;
cout << "Marks of how many subjects: ";
cin >> subjects;
float subjectMarks[subjects];
string subjectNames[subjects];
for (int i = 0; i < subjects; i++) {
for (int j = 0; j < subjects; j++) {
cout << "Enter name of subject: ";
cin >> subjectNames[j];
break; // I've used 'break' to exit the inner loop and go to outer loop for
// entering the marks obtained in the subject
};
cout << "Enter marks obtained in the subject: ";
cin >> subjectMarks[i];
};
cout << "Dear, " << fname << " " << lname << "! The subjects and their marks are shown below: \n";
cout << "RESULTS IN SUBJECTS\n\n";
for (int i = 0; i < subjects; i++) {
for (int j = 0; j < subjects; j++) {
cout << subjectNames[j] << "\t\t";
break;
}
cout << subjectMarks[i] << endl;
};
return 0;
}
What I expected?
As you can see in the screenshot, 'Chemistry' is printed twice with different marks. It should have printed first 'Physics' with marks '80' and then 'Chemistry' with marks '70' as inputted by the user. I doubt there is a problem with subjectNames[] array.
But this is what actually happened
I'm stuck on this problem for more than 3 hours. Please help!