Pointer

I need to calculate the average grade. Here is my code:
I keep receiving 0 when I'm trying to calculate the avg.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <string>

#include "Student.h"
using namespace std;

int main(){
	
	int numOfStudents;

	cout << " Please enter the number of students " << ":";
	cin >> numOfStudents;
	Student *s = new Student[numOfStudents];
	cout << "Please enter student data" << ":" << endl;

	string studentName;
	int studentGrade = 0;

	for (int i = 0; i < numOfStudents; i++){
		cout << "Name " << ": ";
		cin >> studentName;
		cout << "Grade " << ":";
		cin >> studentGrade;
		s[i].setName(studentName);
		s[i].setGrade(studentGrade);
		cout << s[i].getName() << endl;
		cout << s[i].getGrade() << endl;
	}

	int size = 0; int sub=0; float avg = 0;

	for (int i = 0; i < size; i++){
		sub += s[i].getGrade();

		avg = sub / (float)(size);
	}
	cout << avg << endl;
	
		system("pause");
		return 0;
}
1
2
3
4
5
for (int i = 0; i < size; i++){
		sub += s[i].getGrade();

		avg = sub / (float)(size);
	}


Think carefully here. Why is

avg = sub / (float)(size); Inside the for-loop? This should only be done once right?
That's right,

but still doesn't calculate correctly.

1
2
3
4
5
6
7
int size = 0; int sub=0; float avg = 0;

	for (int i = 0; i < size; i++){
		sub += s[i].getGrade();
	}
	avg = sub / (float)(size);
	cout << avg << endl;
Let me borrow some of your code:
1
2
3
4
5
6
7
8
9
#include <iostream>

int main() {
  int size = 0;
  for ( int i = 0; i < size; ++i ) {
    std::cout << "Hello\n";
  }
  return 0;
}

What does that program say? Why?
Your problem is this.


1
2
3
int size = 0;

for (int i = 0; i < size; i++)


"Run this for-loop 0 times" Is what you're telling the program to do.

Edit: Dont forget to delete the allocated memory.
Last edited on
yours works once I put the cout statement after }, but for loop is not doing anything.
Yeh... Look at my post. Size is equal to 0. You tell the loop to run 0 times. There for loop never runs, its being skipped by the program. So everything that happens inside the loop, never does.
I see.... omg hahaaaa
thank u so much!!!
My pleasure^^

Happy coding!
Topic archived. No new replies allowed.