Help with code for counting the occurrence of NUmbers

closed account (Eh5fjE8b)
Hey guys, I am still new to C++ programming and I really need your help, I am trying to write a code that outputs a histogram of student grades. The program details are: The program should read the first number in the file
– it will specify how many grades follow it in the file. The program should then dynamically
allocate an integer array of that size, read the grades into the array, compute the histogram,
and print out the results. You should define functions for reading in the grades, computing the
histogram, and printing out the results.
I have included the code I wrote here, but it is not quite right. Can someone help me?


1
2
3
4
5
6
7
8
9
10
11
12
  #include <iostream>
#include <fstream>
using namespace std;

void read(int arr[], int size);
void compute(int *arr,int *count, int *numbers, int &size);
void output(int *arr,int *count, int *numbers, int &size);
void swapValues(int& v1, int& v2);	 

	ifstream fin;
	ofstream fout;
Last edited on
To start, I would highly suggest creating a class called Student and reading the values into an object of the class. It makes it readable and much easier, and the member functions of the class would let you do all operations (except reading in).

Here is a possible class idea:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Student
{
    private:
        int* grades;
        int numGrades;
        
    public:
        Student();
        Student(int*);
        ~Student();
        
        //Computational functions here
        //I'm not exactly sure what you are trying to do
        
        friend ostream& out(ostream&);//Possible way to output
        string toString();//Another possible way tyo output
    
};


It may not be a good idea to put a namespace inside of a function. You might as well set the entire program to namespace std.

Look out for memory leaks. It looks like you allocate memory in lines 35-37 but I don't see you giving it back anywhere.

I can't give you any actual algorithms since it is probably an assignment, but a class would definitely be helpful here. Good luck!
58
59
60
61
62
63
64
65
66
67
//sort array
for (int i=0 ; i<size; i++)
{
    if(arr[i]>arr[i+1])	{
        int temp= arr[i];
        arr[i]= arr[i+1];
        arr[i+1]= temp;
    
    }	
}

I've never heard of a comparison-based sorting algorithm that runs in O(n) time....
(In other words, double-check your sorting algorithm.)

Also, you don't need to pass size by reference.
And on line 96, for(int k=0; k <=size ;k++) should be a < instead of a <=.
closed account (Eh5fjE8b)
Thanks guys I think most of the problem came with my sorting loop. I have fixed it and I really appreciate all your help.
Thank you very much.
Topic archived. No new replies allowed.