I'm begginer to C++. I'm trying to write a program that asks the user to input student ID,student year and student grade (GPA ) for 50 students. Then I'm trying to find the total of students that their grade is bigger or equal to 2. I've done the code below and it runs fine no issues, but the total no returns does not return the correct number. My code as below:
#include <iostream>
usingnamespace std;
long student_Id;
int year_no;
float GPA;
int main()
{
for ( int i = 0 ; i <50 ; i++) {
cout<< " please enter the student ID:";
cin>> student_Id;
cin.ignore();
cout<< " please enter the year: ";
cin>> year_no;
cin.ignore();
cout<< " please enter GPA:";
cin>> GPA;
cin.ignore();
}
int total = 0 ;
if ( GPA >= 2)
total+= GPA;
cout<<" expected students:" <<total;
return 0;
}
if I run the program,E.g
Student 1: GPA = 1
Student 2: GPA = 2
Student 3: GPA = 3
etc etc
expected: to get the total of students that their GPA bigger or equal to 2 = 2 students
For the "sum/total" calculation, your program does the same as the following program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
int main()
{
using std::cout;
using std::cin;
float GPA;
cout << " please enter GPA of the last student:";
cin >> GPA;
cin.ignore();
int total = 0 ;
if ( GPA >= 2 ) {
total += GPA;
}
cout << " expected students:" << total;
return 0;
}
Why? Because your calculation is after the loop. It should be [i]within[i].
PS. Does your "total" mean
"how many students have GPA of at least 2"
or
"what is the sum of GPA's (that are at least 2)"
Thank you for your reply. The reason I put the calulation after the loop, is becuase I'm using the loop to ask the user to enter the same information for 50 students, then for these 50 students am trying to find how many of these 50 students have GPA equal or bigger than 2.
If I put the if statment within the loop, then it would print the cout after each student GPA.. Hope that answers your question
#include <iostream>
using namespace std;
long student_Id;
int year_no;
float GPA;
int total = 0;
int main()
{
for ( int i = 0 ; i <50 ; i++) {
cout<< " please enter the student ID:";
cin>> student_Id;
cin.ignore();
cout<< " please enter the year: ";
cin>> year_no;
cin.ignore();
cout<< " please enter GPA:";
cin>> GPA;
cin.ignore();
if ( GPA >= 2)
total+= GPA;
}
cout<<" expected students:" <<total;
return 0;
}
Now if I run the program
E.g
Student 1 : GPA = 2
Student 2 : GPA = 3
Student 3 : GPA = 1
Expected : to get the number of students who their GPA bigger or equal to 2 = 2 studnets
but actual : returns 6, which bascially calculates and adds all GPA together