I just finished my first assignment using arrays and I feel like it is a little more complex than it has to be. The program reads a file with scores in it and counts the occurrences of a score within a certain range and then outputs the number of occurrences.
I am wondering if there is a more efficient way of completing this task (using only arrays).
I understand the array saved me from having to make 8 separate variables but there are still so many if statements!!
header
#ifndef HEADER_H_INCLUDED
#define HEADER_H_INCLUDED
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cctype>
#include <cstdlib>
using namespace std;
void extern input(ifstream&, ofstream&, int&, int*);
void extern calculate (int, int*);
void extern output (ofstream&, int*);
#endif // HEADER_H_INCLUDED
main
#include "header.h"
int main()
{
int grade;
int array[8] = {0};
ifstream inData;
ofstream outData;
inData.open("Ch9_Ex4Data.txt");
if (!inData)
{
cout << "Cannot open the input file."
<< endl;
return 1;
}
outData.open("DataOut.txt");
while (inData)
{
input(inData, outData, grade, array);
}
output (outData, array);
system("PAUSE");
return EXIT_SUCCESS;
}
input
#include "header.h"
void input(ifstream& inData, ofstream& outData, int& grade, int array[])
{
while(inData >> grade) // while a grade is read
{
calculate(grade, array);
}
}
calculate
#include "header.h"
void calculate (int grade, int array[])
{
int index;
if (grade >= 0 && grade < 25)
{
index = 0;
array[index]++;
}
else if (grade >= 25 && grade < 50)
{
index = 1;
array[index]++;
}
else if (grade >= 50 && grade < 75)
{
index = 2;
array[index]++;
}
else if (grade >= 75 && grade < 100)
{
index = 3;
array[index]++;
}
else if (grade >= 100 && grade < 125)
{
index = 4;
array[index]++;
}
else if (grade >= 125 && grade < 150)
{
index = 5;
array[index]++;
}
else if (grade >= 150 && grade < 175)
{
index = 6;
array[index]++;
}
else if (grade >= 175 && grade <= 200)
{
index = 7;
array[index]++;
}
}
output
#include "header.h"
void output (ofstream& outData, int array [])
{
outData << "number of students with score of 0-24 is " << array[0] << endl;
outData << "number of students with score of 25-49 is " << array[1] << endl;
outData << "number of students with score of 50-74 is " << array[2] << endl;
outData << "number of students with score of 75-99 is " << array[3] << endl;
outData << "number of students with score of 100-124 is " << array[4] << endl;
outData << "number of students with score of 125-149 is " << array[5] << endl;
outData << "number of students with score of 150-174 is " << array[6] << endl;
outData << "number of students with score of 175-200 is " << array[7] << endl;
}
You’re right, because they’re evenly spaced it could be a LOT shorter, e.g.
output()could be turned into a loop, the calculation for high and low of each bin is straightforward (using multiplication).If the bins weren’t equally spaced, you’d need to use a lookup table like Serge’s suggestion.