"Uninitialized Local Variable Used" - c++

I have a call to 2 functions which find the highest and lowest grade, respectively. they return "highestGrade" and "lowestGrade" but I am confused why the error appears when I compile. This is a lab assignment and most of the code was pre-written and I was tasked with filling in the missing code. The error occurs around lines 55 and 63, and the functions I am referring to are at the end of the code.
I am new to using arrays so I am assuming I may have some for of erroneous code inside the functions "findHighest" and "findLowest". For example, the program in "findHighest" will assume the first array it runs into is the highest grade and will compare the remaining arrays to it until it finds one that is higher. If it is, it will then assign that array to "highestGrade".
float findAverage(const GradeType, int);
int findHighest(const GradeType, int);
int findLowest(const GradeType, int);
int main()
{
GradeType grades;
int numberOfGrades;
int pos;
float avgOfGrades;
int highestGrade;
int lowestGrade;
// Read in the values into the array
pos = 0;
cout << "Please input a grade from 1 to 100, (or -99 to stop)" << endl;
cin >> grades[pos];
int i = 1;
while (grades[pos] != -99)
{
// read in more grades
pos = i;
cout << "Please input a grade from 1 to 100, (or -99 to stop)" << endl;
cin >> grades[pos];
}
numberOfGrades = pos; // Fill blank with appropriate identifier
// call to the function to find average
findAverage(grades, numberOfGrades);
avgOfGrades = findAverage(grades, numberOfGrades);
cout << endl << "The average of all the grades is " << avgOfGrades << endl;
// Fill in the call to the function that calculates highest grade
findHighest(grades, highestGrade);
highestGrade = findHighest(grades, highestGrade);
cout << endl << "The highest grade is " << highestGrade << endl;
// Fill in the call to the function that calculates lowest grade
findLowest(grades, lowestGrade);
// Fill in code to write the lowest to the screen
lowestGrade = findLowest(grades, lowestGrade);
cout << endl << "The lowest grade is " << lowestGrade << endl;
return 0;
}
float findAverage(const GradeType array, int size)
{
float sum = 0; // holds the sum of all the numbers
for (int pos = 0; pos < size; pos++)
sum = sum + array[pos];
return (sum / size); //returns the average
}
int findHighest(const GradeType array, int size)
{
// Fill in the code for this function
float highestGrade = array[0];
for (int i = 0; i < size; i++)
{
if (array[i] > highestGrade)
highestGrade = array[i];
}
return highestGrade;
}
int findLowest(const GradeType array, int size)
{
// Fill in the code for this function
float lowestGrade = array[0];
for (int i = 1; i < size; i++)
{
if (array[i] < lowestGrade)
lowestGrade = array[i];
}
return lowestGrade;
}
The program is unable to output the highest and lowest grade due to the error.

findLowest(grades, lowestGrade);
You are using lowestGrade before initializing it.
int lowestGrade;
should be
int lowestGrade = 0; // or to anything that has meaning for your app.
And of course, as better C++, declare it just before you need it, not at the top of the function.
Same thing for the other variables.
All of this of course if the logic is correct. Why do you pass the lowest/higest grade as a size parameter in the functions?

Related

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);

C++ getting highest test score and using pointers

created a program to prompt the user to enter test scores and find the average, highest, and sort the test score. I am having problems I cant seem to get the higest test scores from the function I made and when I created the sorting test score function the program crashes. Can someone look at my functions and see where my problem is, I seem to get the average test score to show.
double getAverage(double*, int);
double gethighest(double*, int);
double getlowest(double*, int);
void arrayAscending(double*, int);
int main()
{
// Variable declarations
double *testScores; // Dynamically allocate an array of test scores
double average, highest, lowest;
int numTests; // Number of test scores
int count; // Counter variable
// Get the number of tests
cout << "How many tests do you wish to process? ";
cin >> numTests;
// Verify input is not a negative number
while (numTests <= 0)
{
// Get input again.
cout << "Please enter a positive number: ";
cin >> numTests;
}
// Dynamically allocate an array large enough to hold the test scores
testScores = new double[numTests];
// Get the specified number of test scores
cout << "Enter the test scores below.\n";
for (count = 0; count < numTests; count++)
{
cout << "Test " << (count + 1) << ": ";
cin >> *(testScores + count);
// Verify input is not a negative number
while (*(testScores + count) < 0)
{
// Get input again.
cout << "Please enter a valid test score.\n";
cin >> *(testScores + count);
}
}
// Calculate the average test score
average = getAverage(testScores, numTests);
highest = gethighest(testScores, numTests);
lowest = getlowest(testScores, numTests);
// Display the results.
arrayAscending(testScores, numTests);
cout << endl;
cout << "The average of those scores is: " << average << endl;
cout << "The higest of those scores is: " << highest << endl;
cout << "The lowest of those scores is: " << lowest << endl;
// Free dynamically allocated memory
delete[] testScores;
testScores = 0; // Make testScores point to null
return 0;
}
//function getAverage - calculates the average of the test scores
double getAverage(double* scores, int num)
{
double avg;
double total = 0.0;
for (int count = 0; count < num; count++)
{
total += scores[count];
}
avg = total / num;
return avg;
}
double gethighest(double* scores, int num)
{
double highnum = 0.0;
for (int i = 0; i < num; i++)
{
if (scores[i] > highnum)
highnum = scores[i];
}
return highnum;
}
double getlowest(double* scores, int num)
{
double lowestnum = 100;
for (int i = 0; i < num; i++)
{
if (scores[i] < lowestnum)
lowestnum = scores[i];
}
return lowestnum;
}
void arrayAscending(double *array, int size)
{
int startScan, minIndex;
double minElem;
for (startScan = 0; startScan < (size - 1); startScan++)
{
minIndex = startScan;
minElem = array[startScan];
for (int index = startScan + 1; index < size; index++)
{
if ((array[index]) < minElem)
{
minElem = array[index];
minIndex = index;
}
}
array[minIndex] = array[startScan];
array[startScan] = minElem;
}
}
void arrayAscending(double *[], int);
should be
void arrayAscending(double *, int);
You are sorting an array of doubles, not an array of pointers to double.
Also,
double *minElem;
is used later without any memory being allocated for it. Again, you probably need just
double minElem;
and not a pointer.
If you don't need to use pointers, then use std::vector and algorithms from the standard library like std::sort.

Trying to use pointer notation instead of array notation on this test scores program but I'm stuck

Ok so I have this assignment where I write a program that the user enters test scores and them I sort them into ascending order. But it also asks to change array notation to pointer notation. Below is my code. It runs but it has all array notation. Please help!
#include <iostream> //libraries
#include <iomanip>
using namespace std; //standard
void arrSelectSort( double*, int ); //prototypes
void showArr( double* arr, int size ) //array
{
for( int i = 0; i < size; ++i )
cout << setw(8) << arr[i];
}
int main() //main function No array boxes allowed
{
int numTests; //declare variable
cout << "How many test scores would you like to enter? " << endl; //ask user how many test scores they want to enter
cin >> numTests; //user input
cin.sync();
double* testScores = new double[numTests]; //pointer?
cout << "Enter the test scores below:" << endl; //ask user to input test scores
double sumTestScores = 0.0; //declare variable
for( int super = 0; super < numTests; ++super ) //super is inheritance
{
cout << "Test Score " << (super + 1) //inheritance
<< ": " << endl;
cin >> testScores[super]; //Need to rid of this array notation
cin.sync();
sumTestScores += testScores[super]; //need to get rid of the array notation
}
cout << "You entered testScores: " << endl; //show results
cout << fixed << showpoint << setprecision(2); //show results
showArr( testScores, numTests);
cout << "The test scores sorted in ascending order are: " << endl; //show tests in ascending order
arrSelectSort( testScores, numTests ); // show ascending
showArr( testScores, numTests );
cout << "The average score is " << sumTestScores / numTests << endl; //show average test score
delete [] testScores; // free memory
testScores = 0; // make testScores point to null
char c; //safe exit
cout << "Please hit any key and <ENTER> to continue..." << endl;
cin >> c; //user input
return 0; //exit
}
void arrSelectSort( double* arr, int size ) //ascending order sort
{
int startScan; //declare variables
double minIndex; // declare variables
double minElem; // declare variables
for (startScan = 0; startScan < (size - 1); startScan++) //loop for scores
{
minIndex = startScan; //pointer?
minElem = arr[startScan]; //no array
for(int index = startScan + 1; index < size; index++) //ascending loop sort
{
if (arr[index] < minElem) //
{
minElem = arr[index]; //
minIndex = index; //
}
}
arr[(int)minIndex] = arr[startScan]; //
arr[startScan] = minElem;//
}
}
// I have tried declaring the arrays and changing them to pointers but it won't run
//This program runs but has a line spacing problem
array[index] is equivalent to *(array + index), so replace one with the other.

C++ Arrays, Array Conversion not working

I've been stuck on a problem for quite a while today, and despite my searching the internet, I'm not sure as to what I should do. This program (that I will post the source code to) is supposed to be based off of the Birthday Paradox, and help us to prove it correct.
The idea is that we have multiple arrays, one of which simulates the paradox by counting the times that there is NOT a matching birthday pair, another which takes that array and creates a ratio(array value/over total iterations) and another that creates a theoretical array ratio value.
Now, this is where I"m stuck. I can get the first two functions to work perfectly, birthdayFrequency and ratioArray, but the next one idealArray I cannot get to work properly. Both ratioArray and idealArray should be a double data type, and ratioArray stores it properly as a double.
However, idealArray does not. It stores the data in the array positions as integers. I want to know if there's something I missed, something that might have caused me to accidentally make the array an integer.
*I'm going to apologize, the code is really long. Also, I can't get it all to fit in a code window. I apologize.
using namespace std;
//Arraytype declarations
typedef int Birthday[365];
typedef bool Counter[365];
typedef double Ratio[365];
void ratioArray(int, Birthday, Ratio);
void idealArray(Ratio);
void outputTable();
int randomInt(int);
//Main function
int main()
{
Birthday array = {0};
Ratio vector = {0};
Ratio matrix = {0};
int seed;
int runs;
//Prompt the user for the number of times the simulation is to be run.
cout << "Hello and welcome to the Birthday Paradox Simulator. " << endl;
cout << "This program uses simulated runs to calculate and verify the paradox." << endl << endl;
cout << "Please enter the number of runs you want done. IMPORTANT, must be a positive integer." << endl;
cin >> runs;
while (runs <= 0)
{
cout << "That's an invalid value. Please enter a positive number." << endl;
cin >> runs;
}
//Prompt the user for a non-negative integer seed value
cout << "Please input a seed to be used for randomly generating numbers. It must be an integer, and non-negative." << endl;
cin >> seed;
while (seed < 0)
{
cout << "I'm sorry, that is an invalid value. Please enter a non-negative number)" << endl;
cin >> seed;
}
//Seed the srand function
srand(seed);
//Call birthdayFrequency function
birthdayFrequency(runs, array);
//Call ratioArray function
ratioArray(runs, array, vector);
//Call idealRatioArray function
idealArray(matrix);
//Testing values
cout << array[1] << endl;
cout << array[2] << endl;
cout << array[3] << endl;
cout << vector[1] << endl;
cout << vector[2] << endl;
cout << vector[3] << endl;
cout << matrix[1] << endl;
cout << matrix[2] << endl;
cout << matrix[3] << endl;
//Call outputTable function
outputTable();
return 0;
}
void birthdayFrequency(int n, Birthday number)
{
int iteration = 0;
int value;
int boundary = 364;
//For loop for n iterations
for ( int k =0 ; k < n ; k++)
{
Counter boolean = {0};
iteration = 0;
//Randomly mark birthdays until there's a duplicate using a for loop
for ( int i = 0; i < 366; i ++)
{
value = randomInt(boundary);
if (boolean[value] == 1)
break;
else
boolean[value] = 1;
number[iteration]++; //Increment the frequency array for every non-match
iteration++;
}
}
}
void ratioArray(int n, Birthday number, Ratio vectors)
{
double ratio;
//For loop for the number of runs, storing the value of ratios to the total number of runs.
for ( int i = 0 ; i < 364 ; i++)
{
ratio = (double)number[i] / n;
vectors[i] = ratio;
}
}
void idealArray(Ratio number)
{
number[0]= 1.0;
number[1] = 1.0;
//Create an ideal, theoretical probability array
for ( int n = 2; n < 364; n++)
{
number[n] = (number[n - 1]*(1- (n-1)/365));
}
}
void outputTable()
{
//Not completed yet.
}
int randomInt(int bound)
{
return static_cast<int>( rand() / (RAND_MAX + 1.0) * bound );
}
In this code:
for ( int n = 2; n < 364; n++)
{
number[n] = (number[n - 1]*(1- (n-1)/365));
}
n is an integer, therefore (1-(n-1)/365)) will evaluate to an integer value, since all values in the expression are integers. Also, an integer multiplied by an integer will produce an integer. Since you start off setting number[1] to 1.0, and each element is calculated by multiplying the previous element by an integer amount, all subsequent values will be integer amounts (although stored as doubles).
Change your code to use doubles for the calculation:
for ( int n = 2; n < 364; n++)
{
number[n] = (number[n - 1]*(1.0-((double)n-1.0)/365.0));
}

Dynamic arrays using float

I've got a small task I need to complete and I'm rather confused. This task has 3 parts to it which are:
Write a program that dynamically allocates a float array of a size specified by a user (currently working on - if anyone could check my code for this it would be appreciated.
It should then allow the user to input that number of floats, which should be stored in the array. (I have no clue what this means so if I'd appreciate someone explaining it if they could)
Program should print what was saved into the array, the sum, and the average value in the array, and exit.
As you could tell I'm new to C++ and coding in general so please spell it out for me wherever possible. It is mandatory that I am using pointers so I'm afraid I can't change that.
#include <iostream>
using namespace std;
int main()
{
int length;
cout << “Please enter the length of the array: “;
cin >> length;
float * dArray = new float [length];
for (int i = 0; i < length; i++)
{
cin >> dArray[i] = i;
for (int i = 0; i < length; i++)
{
cout << dArray[i] << “ “;
}
cout << ‘/n’;
int sum = 0;
for (int i=0; i < length; i++)
{
sum +=dArray[i];
avg =sum/length;
cout << “Sum is “ << sum << “/nAverage is “ << average;
delete [] dArray;
}
return 0;
}
Please explain the 2nd part.
Thanks in advance.
Regarding
It should then allow the user to input that number of floats, which should be stored in the array. (I have no clue what this means so if I'd appreciate someone explaining it if they could)
It means that you have to let the user input the values to that array. What you are doing is giving them values yourself.
What you need to do is change
for (int i = 0; i < length; i++)
{
dArray[i] = i;
}
to
for (int i = 0; i < length; i++)
{
cin>>dArray[i];
}
Also Note that length should be an int and not a float.
After completion, this would probably be the code you need ( although I would advice you to do the part of finding the sum and average by yourself and use this code I have posted as reference to check for any mistake, as finding the sum and average for this is really easy )
#include <iostream> // include library
using namespace std;
int main() // main function
{
int length; // changed length to int
float sum = 0 , avg; // variables to store sum and average
cout << "Please enter the length of the array: "; // ask user for array
cin >> length;
float *dArray = new float[length];
cout << "\nEnter " << length << " values to be added to the array\n";
for (int i = 0; i < length; i++)
{
cin >> dArray[i]; //accepting values
sum += dArray[i]; // finding sum
}
avg = sum / length; //the average
cout << "\nThe array now contains\n"; // Displaying the array
for ( int i = 0; i < length; i++) // with the loop
{
cout << dArray[i] << " ";
}
cout << "\nThe sum of all values in the array is " << sum; // the sum
cout << "\n\nThe average value is " << avg; // the average
delete[] dArray;
return 0;
}
EDIT
After getting your comment, I decided to post this new code. ( I am assuming what you meant is that the program should repeat as long as the user wants )
I have done it by using a do while loop.
#include <iostream> // include library
using namespace std;
int main() // main function
{
int length; // changed length to int
char a; // a variable to store the user choice
do
{
float sum = 0 , avg; // variables to store sum and average
cout << "\nPlease enter the length of the array: "; // ask user for array
cin >> length;
float *dArray = new float[length];
cout << "\nEnter " << length << " values to be added to the array\n";
for ( int i = 0; i < length; i++ )
{
cin >> dArray[i]; //accepting values
sum += dArray[i]; // finding sum
}
avg = sum / length; //the average
cout << "\nThe array now contains\n"; // Displaying the array
for ( int i = 0; i < length; i++ ) // with the loop
{
cout << dArray[i] << " ";
}
cout << "\nThe sum of all values in the array is " << sum; // the sum
cout << "\n\nThe average value is " << avg; // the average
cout << "\n\nDo you want to try again ( y/n ) ?\n";
cin >> a;
delete[] dArray;
}while( a =='Y' || a == 'y' ); // The do while loop repeats as long as the character entered is Y or y
return 0;
}
Well, hope this is what you were looking for, if not, please do notify me with a comment... :)
Just so you know, the new code you have posted doesn't even compile. Here are some of the problems.
cin >> dArray[i] = i;
You don't need to use = i here. Just cin >> dArray[i] ; is enough.
The next problem is
cout << ‘/n’;
First of all, its \n and not /n. You also need to enclose it in double quotes and not single quotes. That is cout << "\n";
Next one, you have not defined the variable avg . Also note that you have also used an undefined variable average, which I assume you meant avg.
Now here's one of the main problems , You have not closed the curly brackets you opened. You open the brackets for for loops, but forget to close it. I'm leaving that part to you as you need to learn that part yourself by trying.
Now Here's one problem I don't understand, you have used “ “, which is somehow not the same as " ". I don't know if it's something wrong with my computer, or if it's a totally different symbol. My compiler couldn't recognize it. If its not causing any trouble on your end, then don't mind it.
Well, this sums up the problems I noticed in your code ( the problems that I noticed ).
Your issues are too simple for us to just give you the answers, but I've commented your code with suggestions on how to solve your problem:
#include <iostream>
using namespace std;
int main()
{
float length; //it doesn't make sense for something to be of a float length
//should be size_t instead
cout << "Please enter the length of the array: ";
cin >> length;
float *dArray = new float[length];
for (int i = 0; i < length; i++)
{
dArray[i] = i; //this line is incorrect
//how should we read the data into this array?
//we've used cin before
}
for (int i = 0; i < length; i++)
{
cout << dArray[i] << " ";
}
cout << '\n';
//now we've output the array, just need to output the sum and average value
int sum = 0;
for (int i=0; i < length; i++)
{
sum += //what should go here?
}
int average = //how should we calculate the average?
cout << "Sum is " << sum << "\nAverage is " << average;
delete[] dArray;
return 0;
}