Doesn't calculate min and max grades in program. (c++) (fstream) - c++

The point of this program is to open and read a text file, with student's academic code -> aem and the grade he/she has overall. Then, if the grade of a particular student is greater than 5, it will write his/her academic code on the text named successful, as well as the grade etc.
My problem is that it calculates the average of those 5 students grades correctly but it does not calculate the max and min grades. When I run the program, the window coming up, shows the correct average of the course, however max and min grades are always 0.
Can anyone help me? Probably I don't compare them in the right way.
#include <iostream>
#include <fstream>
using namespace std;
const int arraySize = 5;
int main(int argc, char** argv)
{
ifstream d;
d.open("students.txt");
ofstream b;
b.open("succesful.txt");
ofstream c;
c.open("unsuccesful.txt");
int aem;
double a[arraySize];
int min, max;
double grades, average;
grades = average = 0;
min = max = 0;
for (int i = 0; i < arraySize; i++)
{
d >> aem >> a[i];
grades = grades + a[i];
average = grades / arraySize;
if (a[i] >= 5) b << aem << " " << a[i] << endl;
else c << aem << " " << a[i] << endl;
}
for (int i = 0; i < arraySize; i++)
{
if (a[i] = max)
max = a[i];
break;
if (a[i] = min)
min = a[i];
break;
}
cout << "The average is:" << average;
cout << "Maximum is:" << max;
cout << "Minimum is:" << min;
d.close(); c.close(); b.close();
system("pause");
return 0;
}

int main(int argc, char** argv)
There's no need argc and argv to be here. It can be just int main().
int min, max;
double grades, average;
grades = average = 0;
min = max = 0;
Assigning value after declaration is unnecessary and inefficient. Also, 0 is an integer, not a floating point. You can just initialize them: int min = 0, max = 0; double grades = .0, average = .0;
grades = grades + a[i];
Can be shortened to grades += a[i];
average = grades / arraySize;
This statement is inside a for-loop pointlessly. You can do this after the loop.
for (int i = 1; i < arraySize; i++) {
You forgot the zeroth element of a. int i = 1; must be replaced to int i = 0;
if (i >= max)
max = i;
if (i <= min)
min = i;
You've mistaken a[i] for i. And if a[i] and max already compare equal, there is no need to assign a[i] to max. They can be just:
if (a[i] > max)
max = a[i];
if (a[i] < min)
min = a[i];
And,
system("pause");
std::system is dependent to the system environment and can have unexpected behavior. It should be replaced to:
std::cout << "Press enter key." << std::endl;
std::cin.get();

Related

Your C++ program must use functions to input the scores, compute the average, and find the index of the highest score

I've been working on this for hours now and I'm almost done. I can't get the program to display the correct student ID.
Also the "highIndex" function is suppose to be an "int" but I started with a double. When I try to change it, everything else seems to fall apart.
How do I get the high score to be associated with the student ID so I can output it correctly? I also need to highIndex to be an int which means some other things needs to be changed.
Any help would be much appreciated :)
Here's what I have so far
void inputAnswers(int studentIds[], double scores[]);
double getAverage(double scores[])
{
double total = 0;
for (int count = 0; count <= 6; count++)
{
total += scores[count];
}
return total / 7;
}
double highIndex(double score[])
{
double highScore = score[0];
double indexHigh = 1;
for (int count = 0; count <= 6; count++)
{
if (score[count] > highScore)
{
highScore = score[count];
indexHigh = count;
}
}
return highScore;
}
int main()
{
const int ids = 7;
int student[ids] = { 1234, 2333, 4432, 3323, 2143, 3425, 4123 };
double scores[7];
double highScore[7];
// Gets the test score from user
inputAnswers(student, scores);
// Calculates the average
cout << "The average score is " << getAverage(scores) << endl;
// Calculates highest score
cout << "The high score was student " << highIndex(highScore) << " with a score of " << highIndex(scores);
return 0;
}
// Function gets student scores
void inputAnswers(int student[], double scores[])
{
for (int count = 0; count <= 6; count++)
{
cout << "Enter the score for student "<< student[count] << ": ";
cin >> scores[count];
}
}
As per my observation you haven't supplied any values to the Highscore array and it is not required as well.
If all you need is to find average score, highscore and id of student with highscore this slight change will do the trick just adjusted 3 values from your code and is documented at corresponding lines.
#include<iostream>
using namespace std;
double getAverage(double scores[])
{
double total = 0;
for (int count = 0; count <= 6; count++)
{
total += scores[count];
}
return total / 7;
}
void inputAnswers(int student[], double scores[])
{
for (int count = 0; count <= 6; count++)
{
cout << "Enter the score for student "<< student[count] << ": ";
cin >> scores[count];
}
}
int highIndex(double score[])
{
double highScore = score[0];
double indexHigh = 0; //as we are assigning from position 0
for (int count = 1; count <= 6; count++)
{
if (score[count] > highScore)
{
highScore = score[count];
indexHigh = count;
}
}
return indexHigh; //returns index of highscore
}
int main()
{
const int ids = 7;
int student[ids] = { 1234, 2333, 4432, 3323, 2143, 3425, 4123 };
double scores[7];
//double highScore[7]; no need
// Gets the test score from user
inputAnswers(student, scores);
// Calculates the average
cout << "The average score is " << getAverage(scores) << endl;
// Calculates highest score
cout << "The high score was student " << student[highIndex(scores)] << " with a score of " << scores[highIndex(scores)]; //uses returned index to find values from array
return 0;
}
Although i strongly recommend using class or structures for such data collection of any entitiy. Happy Coding :-)

Maximum and minimum values not printing in main () function

I am doing a code on tracking how much food tigers eat in 1 week and I am tracking 3 tigers.
I am supposed to print average, maximum and minimum. Whenever I run the code it doesn't print the max or minimum, only the initialized values I have in the function. I am assuming the int main() ignores my return values completely, but I can't see why is that. I have done many functions before and I do the same code every time and call it in main
Here is the code:
int main(){
cout << "Enter whether you want to find minimum for tiger 1 2 or 3. (Please
only enter 0, 1 or 2): ";
cin >> temp;
if (temp < 0) {
cout << "CAN'T RUN NEGATIVE NUMBERS";
exit(2);
}
least(food, temp, minimum);
cout << "\n";
cout << "The Tiger " << temp << " has minimum: " << minimum << " ";
cout << "\n \n ";
}
float least(float food[][DAYS], int temp, float min) //loop for days only
{
minimum = food[0][0];
//temp has to be less than 3
for (int j = 0; j < DAYS; ++j) {
if (min<food[temp][j]) {
min = food[temp][j];
}
}
cout << min << " ";
return max;
}
system("PAUSE");
return 0;
}
Since you are not using the return value, use the max and min argument as reference variable in your function definitions. Also the comparison in least & Most functions seems to be wrong. It should be the opposite way.
float least(float food[][DAYS], int temp, float &min) //loop for days only
{
min = food[0][0]; //temp has to be les
for (int j = 0; j < DAYS; ++j) {
if (min>food[temp][j]) {
min = food[temp][j];
}
}
cout << min << " ";
return min;
}
float Most(float food[][DAYS], int amb, float &max) //loop for days only
{
max = food[0][0];
//amb has to be less than 3
for (int j = 0; j < DAYS; ++j) {
if (max<food[amb][j]) {
max = food[amb][j];
}
}
cout << max << " ";
return max;
}
You do not use your methods' return values. Replace
Most(food, amb, maximum);
and
least(food, temp, minimum);
with
maximum = Most(food, amb, maximum);
and
minimum = least(food, temp, minimum);

how to make random score generator using array?

I am trying to make a program that calculates the average score of class and counting the number of A, B, C, D students. Now I am trying another idea: If the test scores are randomly given to students(between 60 to 100), how can I input those random scores into an array? Mine requires users to input all scores one by one. I would like to know how to fill in the array automatically.
#include <iostream>
#include <cstdlib>
using namespace std;
double Average(double *scores, int N)
{
int i;
double total = 0;
for(i = 0; i < N; i++)
{
total = total+scores[i];
}
return total / N;
}
int Agrade(double *scores, int N)
{
int i;
int count = 0;
for(i = 0; i < N; i++)
{
if(scores[i] >= 90 && scores[i] <= 100) count++;
}
return count;
}
int Bgrade(double *scores, int N)
{
int i;
int count = 0;
for(i=0; i < N; i++)
{
if(scores[i] >=80 && scores[i] < 90) count ++;
}
return count;
}
int Cgrade(double *scores, int N)
{
int i;
int count = 0;
for(i=0; i < N; i++)
{
if(scores[i] >=70 && scores[i] < 80) count ++;
}
return count;
}
int Dgrade(double *scores, int N)
{
int i;
int count = 0;
for(i=0; i < N; i++)
{
if(scores[i] >=60 && scores[i] < 70) count ++;
}
return count;
}
int Fgrade(double *scores, int N)
{
int i;
int count = 0;
for(i=0; i < N; i++)
{
if(scores[i] < 60) count ++;
}
return count;
}
int main(){
int i;
int N;
double *scores;
std::cout<<"How many test scores? "<<endl;
cin>>N;
if(N<1){
std::cout<<"Invalid input. try again"<<endl;
}
else if(N>25)
{
std::cout<<"1-25 only."<<endl;
}
else if(N>0 && N<25){
std::cout<<"Total number of test is: "<< N << endl;
}
scores = new double[N];
for(i = 0; i < N; i++)
{
cout << "Randomly generating score of students" << i + 1 << ": ";
cout << (rand() % 40 + 60) << endl; //Trying to give random scores between 60-100
if(!(cin >> scores[i]) || scores[i] < 0 || scores[i] > 100)
{
if(!cin)
{
cin.clear();
cin.ignore(1000, '\n');
}
cout << "Score must be between 0 to 100.\n\n"; i--; continue;
}
}
double averagescore = Average(scores, N);
int scoreAcount = Agrade(scores, N);
int scoreBcount = Bgrade(scores, N);
int scoreCcount = Cgrade(scores, N);
int scoreDcount = Dgrade(scores, N);
int scoreFcount = Fgrade(scores, N);
cout << "The average test score : " << averagescore << endl;
cout << "The number of A grades : " << scoreAcount << endl;
cout << "The number of B grades : " << scoreBcount << endl;
cout << "The number of C grades : " << scoreCcount << endl;
cout << "The number of D grades : " << scoreDcount << endl;
cout << "The number of F grades : " << scoreFcount <<endl;
cout << endl;
return 0;
}
Can I just modify this part to make it work?
for(i = 0; i < N; i++)
{
cout << "Randomly generating score of students" << i + 1 << ": ";
cout << (rand() % 40 + 60) << endl; //Trying to give random scores between 60-100
if(!(cin >> scores[i]) || scores[i] < 0 || scores[i] > 100)
{
if(!cin)
{
cin.clear();
cin.ignore(1000, '\n');
}
cout << "Score must be between 0 to 100.\n\n"; i--; continue;
}
}
or do I need to modify all functions?
If what you want is to assign result of std::rand() function to all elements in array, you should take a look at std::generate function from <algorithm> header, which does exactly what you want. Take a look at this simple example:
#include <algorithm>
#include <iostream>
#include <vector>
#include <cstdlib>
int main() {
std::srand(0);
const int N = 5;
std::vector<int> scores(N);
std::generate(scores.begin(), scores.end(), [](){return std::rand() % 40 + 60; });
for(auto s : scores) {
std::cout << s << ' ';
}
}
This will fill vector scores with randomly generated numbers from specified interval using std::generate function and lambda function given as its third argument that returns random number.
In your case, if you're not allowed to use std::vector, you can still do it with plain C-arrays, like this:
int scores[5];
std::generate(std::begin(scores), std::end(scores), [](){return std::rand() % 40 + 60; });
Unfortunately, std::begin and std::end functions cannot be applied straight-forward to dynamically allocated arrays, but this still should work in your case:
const int N = 5;
double* scores = new double[N];
std::generate(scores, scores+N, [](){return std::rand() % 40 + 60; });
for(int i=0; i<N; ++i) {
std::cout << scores[i] << ' ';
}
// remember to release memory allocated using new
You need to seed the random number generator to make sure the random numbers have a reasonably random seed. So before the for loop you mentioned, you need to call something like srand(time(NULL)) and include time.h in your code. That should be enough.
And just as an aside, in your code, I only see allocation of the scores array. Remember to delete! Even better, use vectors throughout.

Finding min and max value in a random array

Working on an assignment that requires me to put in some functions (finding max/min value, sum and average value of random numbers in an array), I've managed to complete all of them but for min value I'm getting a value of -2145379808. I'm not sure where I've messed up and I would appreciate the help.
Code so far:
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main(int argc, char** argv) {
{
cout << "Enter array size " << endl;
}
float avg;
float sum;
int size;
cin >> size;
int array[size];
int max = array [0];
int min = array [0];
srand((unsigned)time(NULL));
for (int i = 1; i < size + 1; i++)
{
array[i] = 1+rand()%100 ;
sum += array[i];
cout << "number " << i << " = "<< array[i] << endl;
}
for (int x = 1; x < size; x++){
if (array[x] > max){
max = array[x];
}
if (array[x] < min){
min = array[x];
}
}
cout << "\nmax = " << max << endl;
cout << "\nmin = " << min << endl;
cout << "\nsum = "<< sum << endl;
cout << "\navg = " << sum / size << endl;
return 0;
}
Setting max and min to the uninitialised element of array is never going to end well. On this note, you also need to initialise sum. You may as well remove avg since you don't use it.
You need to set max and min to the first element of array once you know what it is. Crudely, you could set max to std::numeric_limits<int>::min() and min to std::numeric_limits<int>::max().
Note also that the bounds of array are array[0] to array[size - 1]. Therefore you need to revisit the indexing in your loops.
Then once you have it working, bin it, and use std::vector<int>, and things like minmax_element: http://en.cppreference.com/w/cpp/algorithm/minmax_element
The problem is in following lines:
float avg;
float sum;
...
int max = array [0];
int min = array [0];
Because at this point the value at array [0] are garbage value.
To correct your code change this line as following (also include climits header file). Also, change loops index accordingly:
float avg = 0;
float sum = 0;
...
int max = INT_MIN;
int min = INT_MAX;
Following is corrected code(some changes made for optimization). See it working here:
#include <cstdlib>
#include <iostream>
#include <ctime>
#include <climits>
using namespace std;
int main(int argc, char** argv) {
{
cout << "Enter array size " << endl;
}
float sum = 0;
int size;
cin >> size;
int array[size];
int max = INT_MIN;
int min = INT_MAX;
srand((unsigned)time(NULL));
for (int i = 0; i < size; i++)
{
array[i] = 1+rand()%100 ;
sum += array[i];
cout << "number " << i << " = "<< array[i] << endl;
if (array[i] > max){
max = array[i];
}
if (array[i] < min){
min = array[i];
}
}
cout << "\nmax = " << max << endl;
cout << "\nmin = " << min << endl;
cout << "\nsum = "<< sum << endl;
cout << "\navg = " << sum / size << endl;
return 0;
}
To insure your max and min are initialized correctly, C++ provides std::numeric_limits for all types. They each have max() and min() member functions to return the max and min value for the type. In any code you want to find a maximum and minimum, you want to first initialize your maximum to the minimum of the type and vice versa. That way any value will be larger than your min and smaller than your max.
You do that with std::numeric_limits similar to:
int min = std::numeric_limits<int>::max()
int max = std::numeric_limits<int>::min()
Let me know if you have more questions.

How to get average from array

Trying to get some C++ basics but have a problem. I need to get an average value of temperature array values. Posting code in here. I know that I've done something wrong, because I'm getting the wrong answers. Can you please tell me what's wrong?
#include <iostream>
using namespace std;
int main()
{
int d = 0, i;
double avg = 0, sum = 0, Temperature[100];
// -----------------------------------------
cin >> d;
for (i = 1; i <= d; i++)
{
cin >> Temperature[i];
}
for (i = 1; i <= d; i++)
{
cout << Temperature[i] << endl; // was Temperatura[i] ?
}
for (i = 1; i <= d; i++);
{
sum += Temperature[i];
}
avg= sum / d;
cout << "Average: " << avg << " Sum: " << sum << endl;
system("pause");
return 0;
}
The problem is a result of silly mistake:-
for (i = 1; i <= d; i++); << semicolon
Remove semicolon from end of for loop.
Maybe it because the input number d is larger than 100
#include <iostream>
using namespace std;
int main()
{
int d = 0, i;
double avg = 0, sum = 0, *Temperature=0;
// -----------------------------------------
cin >> d;
Temperature=new double[d]; //<== Use new to allocate array
for (i = 0; i < d; i++) //<== Normaly array start at 0
{
cin >> Temperature[i];
}
for (i = 0; i < d; i++)
{
cout << Temperatura[i] <<endl;
}
for (i = 0; i < d; i++);
{
sum += Temperature[i];
}
average = sum / d;
cout << "Average: " << avg << " Sum: " << sum << endl;
if(Temperature!=0) //<== Free memory
{
delete []Temperature;
}
system("pause");
return 0;
}
You don't need to initialize int d; if you are taking d as input before it use for first time.
Once d taken as input. Now declare the int Temperature[d]; so that if the total number of observation exceed 100 it should work.
Now iterate the array, for taking input and calculating sum. Note that - Array indices starts from zero instead of one. Goes to d-1.
for() loop doesn't have; at the end.
Steps:
You declare the Temperatures array, the number of temperatures (you used 'd', but you don't need to initialize it with 0, just read it) and a variable which keeps the sum of Temperatures (ex.: double sum = 0)
In a for loop (for i = 1; i <= d; i++ || for i = 0; i < d; i++) you read the Temperatures and increase the sum with each of the elemens (sum += Temperatures[i] || sum = sum + Temperatures[i]
Output: cout << sum / n; Formula : average = (elem1 + elem2 + ... + elem n) / n