how to divide depending on how many times the user inputs a value

Feb 27, 2014 at 6:16pm
For example, to calculate GPA, we add all the grade point of a course and divide by the number of courses we are taking. How do I create a program in such a way that when the user enters grade point for two courses, it will add the grade points for the two course and divide by 2. And if another user enters grade points for six courses, it adds the grade points and divides by 6.

Am a beginner, so, please show me an example. Thanks
Feb 27, 2014 at 6:45pm
I guess you will use some kind of loop to read the grade point input from the user. Define a variable before the loop and initialize it to 0. In the loop you increment the variable for each grade point you read. After the loop the variable will contain the total number of grade points that was given.
Feb 27, 2014 at 6:51pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <algorithm>
#include <vector>

int main()
{
	std::vector<unsigned> grades;
	unsigned grade;
	std::cin >> grade;
	while (grade != 0) {
	    grades.push_back(grade);
	    std::cin >> grade;
	}
	std::cout << "You have entered " << grades.size() << " elements" << std::endl;
	std::cout << "Your GPA is " << (std::accumulate(grades.begin(), grades.end(), 0u) / grades.size()) << std::endl;
}
http://ideone.com/WRGjOd

Do that if you need to acces grades late. Otherwise find sum of grades during input and keep counter of how many variables you read.
Last edited on Feb 27, 2014 at 6:52pm
Topic archived. No new replies allowed.