I am getting an error in the word sum where it says average = sum / ARRAY_SIZE;. It is saying that the sum is undeclared. Even though I use sum previously in the getSum function, I only get the error here. I tried declaring it as a variable at the top but I am still getting that error. I do not know how else to declare it in a way that would stop this error.
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
// Function prototypes
int getHighest(int numbers[],int ARRAY_SIZE);
int getLowest(int numbers[],int ARRAY_SIZE);
int getSum(int numbers[],int ARRAY_SIZE);
int getAverage(int numbers[],int ARRAY_SIZE);
int main () {
// Variables
const int ARRAY_SIZE = 12; // Array size
int numbers [ARRAY_SIZE]; // Array with 12 integers
int count = 0; // loop counter variable
string filename;
// Open file
cout << "Enter input filename:";
cin >> filename;
ifstream inputFile(filename); // input file stream object
// Read numbers from file into array
while(count <ARRAY_SIZE && inputFile >> numbers[count])
count ++;
// Print results
cout<<ARRAY_SIZE<<" numbers read from input file."<<endl;
cout<<"The highest value is: "<<getHighest(numbers,ARRAY_SIZE)<<endl;
cout<<"The lowest value is: "<<getLowest(numbers,ARRAY_SIZE)<<endl;
cout<<"The sum of the numbers is: "<<getSum(numbers,ARRAY_SIZE)<<endl;
cout<<"The average of the numbers is: "<<getAverage(numbers,ARRAY_SIZE)<<endl;
}
int getHighest( const int numbers[], int ARRAY_SIZE)
{
int highest;
highest = numbers[0];
for(int count = 1 ; count < ARRAY_SIZE; count++)
{
if (numbers[count] > highest)
highest = numbers[count];
}
return highest;
}
int getLowest(const int numbers[], int ARRAY_SIZE)
{
int lowest;
lowest = numbers[0];
for (int count = 1; count < ARRAY_SIZE; count++)
{
if (numbers[count] < lowest)
lowest = numbers[count];
}
return lowest;
}
int getSum(const int numbers[], int ARRAY_SIZE)
{
int sum = 0;
for(int count = 0; count < ARRAY_SIZE; count++)
sum+= numbers[count];
return sum;
}
int getAverage(const int numbers[], int ARRAY_SIZE)
{
int average = 0;
for (int count = 0; count < ARRAY_SIZE; count++)
average = sum / ARRAY_SIZE;
return average;
}
It is saying that the sum is undeclared. Even though I use sum previously in the getSum function, I only get the error here.
sum is only a local variable in getSum so it cannot be accessed from getAverage, and in fact that variable does not exist anymore when you leave getSum
Note also the for in getAverage is useless because you do all the time average = sum / ARRAY_SIZE; whose value is always the same, so you want :
int getAverage(const int numbers[], int ARRAY_SIZE)
{
return getSum(numbers, ARRAY_SIZE) / ARRAY_SIZE;
}
Note your declarations and definitions do not correspond because in your definitions the array is const but not in your declarations. Put the array also const in the declarations :
int getHighest(const int numbers[],int ARRAY_SIZE);
int getLowest(const int numbers[],int ARRAYSIZE);
int getSum(const int numbers[],int SIZE);
int getAverage(const int numbers[],int SIZE);
may be also rename ARRAY_SIZE to size to not confuse with the global variable of the same name (even they receive its value), and SIZE to size because uppercase are generally not used to name a local variable/parameter.
Out of that, you are in C++, are you sure you want to use (C) arrays rather than for instance std::vector allowing to not give the size in argument to each functions and also to have iterators and predefined operations etc ?
Related
So basically i need to replace the two largest elements of an array, inputed by user. I don't understand why doesn't my code working.
#include <iostream>
using namespace std;
double Max (double a[], int n) {
double max1=0, max2=0;
for (int i=0; i<n; i++){
if(max1 < a[i]){
max2 = max1;
max1 =a[i];}
else
if(max2 < a[i]){
max2 = a[i];}
}
return max2,max1;
}
int main () {
setlocale(0,".1251");
double a[7];
cout<<"Input 7-digit array:\n";
for (int i=0; i<7; i++) cin >> a[i];
for (int i=0; i<7; i++) {
cout<<a[i]<<"\t";
}
system ("pause>>void");
return 0;
}
The function double Max (double a[], int n) is only defined, but you haven't called it. As it is right now, you are only outputting the same digits you inputted.
Also double Max (double a[], int n) can only return 1 double, so I'm assuming you were trying to return two variables return max2,max1; at once which isn't supported.
A fix to this could be by using a std::vector as data type and returning a 2 element array of max1 & max2 and then you would have to finish the code by actually calling the double Max (double a[], int n) function.
vector Maximums = Max(a[],7);
cout<< "\n max 1:\n" << Maximums[0] << "\n max 2:\n" << Maximums[1]
I keep getting function definition is not allowed where the '{' is after int getSmallest(int numbers[],int SIZE);. I am having trouble figuring out how to fix it and getting this program to compile.. This is what I have as of right now:
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
// Function prototypes
int getSmallest(int numbers[], int SIZE);
int main()
{
int count = 0;
int numbers[SIZE];
string inFile;
cout << "Enter input file name:";
cin >> inFile;
ifstream file(inFile);
//Reading from file
for (count = 0; count < SIZE; count++) {
cout << SIZE << "numbers read from file." << endl;
cout << "The smallest value is: " << getSmallest(numbers, SIZE) << endl;
}
}
int getSmallest(int numbers[], int SIZE)
{
smallest = numbers[0];
for (count = 1; count < SIZE; count++) {
if (numbers[count] < smallest) {
smallest = numbers[count];
}
return smallest;
}
}
The problem is in your function. Variable smallest and count are not defined ... you didn't specify type. You defined them in your main, but your function does not know anything about variables in main. Just about variables that you passed (numbers and SIZE). Try it like this:
int getSmallest(int numbers[], int SIZE)
{
int smallest = numbers[0];
for (int count = 1; count < SIZE; count++) {
if (numbers[count] < smallest) {
smallest = numbers[count];
}
return smallest;
}
}
*Note the int before smallest and count
I also noticed that this function returns immediately after one loop iteration. You should write that return statement outside for loop
int getSmallest(int numbers[], int SIZE)
{
int smallest = numbers[0];
for (int count = 1; count < SIZE; count++) {
if (numbers[count] < smallest) {
smallest = numbers[count];
}
}
return smallest;
}
Also, I don't know if that SIZE is defined anywhere in any header file, but it is not defined in your program.
You are also not reading from file. Maybe this link will help you understand how to read from file: http://www.cplusplus.com/doc/tutorial/files/
I am making a program that asked the user to open and existing txt file. The program should read the numbers from the file and storing them into arrays. I am supposed to create different functions with those numbers in the array, such as getting the largest number, the lowest number, the sum, and the average. I have done the functions already but I do not know how to extract the numbers from the array.
Here is an example of numbers but instead of being separated by space, they're separated by a new line.
53
22
87
103
-3
75
220
1
64
543
98
44
int getLowest(int num[], int size);
int getHighest(int num[], int size);
int getSum(int num[], int size);
int getAverage(int num[], int size);
int main()
{
string fileName;
ifstream inputFile;
const int ARRAY_SIZE = 12;
int numbers[ARRAY_SIZE];
cout << "Enter the name of imput file: ";
cin >> fileName;
inputFile.open(fileName);
if (inputFile)
{
cout << " numbers read from input file.\n"
<< "The lowest value is " << getLowest(numbers, ARRAY_SIZE) << endl;
}
else
{
//Display error message
cout << "Error, this file does not exist.";
}
system("pause");
}
int getLowest(int num[], int size)
{
int temp = num[0];
for (int i = 0; i < size; i++)
{
if (temp < num[i])
{
temp = num[i];
}
}
return temp;
}
int getHighest(int num[], int size)
{
int temp = num[0];
for (int i = 0; i > size; i++)
{
if (temp > num[i])
{
temp = num[i];
}
}
return temp;
}
int getSum(int num[], int size)
{
int sum = 0;
for (int i = 0; i < size; i++)
{
sum += num[i];
}
return sum;
}
double getAverage(int num[], int size)
{
int sum = 0;
double average;
for (int i = 0; i < size; i++)
{
sum += num[i];
}
average = sum / size;
return average;
}
When I open the file with the numbers shown above, the result I get does not work. I get:
010FFCE0 numbers read from input file.
The lowest value is 1968178332
Where it says "010FFCE0" i would like to get something that says the numbers of values, and the lowest value I would like it to be the actual lowest value.
Here is an example of reading numbers from a file into std::vector<int>:
int number = 0;
std::vector<int> database;
while (inputFile >> number)
{
database.push_back(number);
}
The std::vector is a good choice here because it expands dynamically as necessary (performing dynamic memory allocation as necessary).
However, you don't need to store the numbers in order to determine the highest, lowest and average:
int sum = 0;
int highest;
int lowest;
inputFile >> highest;
lowest = highest;
sum = highest;
int number;
int quantity = 1;
while (inputFile >> number)
{
if (number > highest)
{
highest = number;
}
if (number < lowest)
{
lowest = number;
}
sum += number;
++quantity;
}
double average = (sum * 1.0) / quantity;
Here is what I am trying to do, I want create a function that will compute and return (using by pass reference) the mean, maximum, and minimum. kinda new to c++ so I'd really appreciate the help.
Here exactly what I am trying to do:
Program describes what its suppose to do
Prompts the user to enter a number between 1 and 10, and then fills an array with positive floating point number
Outputs the contents of an array of floats, using a function
Use a function to compute the mean, max and min from an array of floats. The values are returned in pass by reference variables
Output the computed value
If at any point the user enters an invalid input, prompt them again
Terminates safely
Here is the code:
//include go here
#include <cstdio>
#include <iostream>
#include <cfloat>
using namespace std;
//Constants go here
const int MAX = 10;
const int MIN = 1
//outputs overview of program to user
void displayOverview();
//prompts user to enter a number between min and max and return it
//validated using a loop
int getIntInRange(int min, int max);
//prompts user to enter a floating point number that is > 0
//validated using a loop
float getPositiveFloat();
//prompts user for size of array (< size)
//fills nums with that many floating point values
int fillArray(float nums[], int size);
//outputs the array
void printArray (float arr[], int Size);
//Computes and returns the mean, maximum, and minimum
void computesValues(float arrr[], int size, float &mean, float &max, float &min);
int main(){
displayOverview();
float myArr[MAX];
int size = fillArray(myArr, MAX);
return 0;
}
//Prompt user to enter a number between Min and max
//If user entered a number within the range, is valid is true
//If user entered a number not within min and max, output sorry not in range
int getIntInRange(int min, int max){
int userInput = -1;
bool isValid = false;
while(!isValid){
printf("Please enter an integer between %d and %d\n", min, max);
scanf("%d", &userInput);
if(min <= userInput && userInput <= max){
isValid = true;
}else{
printf("Sorry, that is not in range\n Please try again\n");
}
}
return userInput;
}
//int numVals
int fillArray(float nums[], int size){
int numVals = getIntInRange(MIN, MAX);
for(int i=0; i< numVals&& i<size ; i++){
nums[i] = getPositiveFloat();
}
return numVals;
}
//Prompt user to enter a positive number
//if User enters a number that is not positive, output "Not a Positive"
float getPositiveFloat(){
float input;
do{
cout << "Please enter a positive number\n";
cin >> input;
if(!(input>0)){
cout << "Not a positive!\n";
}
}while(!(input>0));
return input;
}
//Introduction to the program
void displayOverview(){
cout << "Welcome to my program. You will see how magically I can compute things " <<
"from numbers!!" << endl;
}
//Print an array
void printArray(float arr[], int size){
for (int i = 0; i<size; i++){
cout << arr[i] << " ";
}
}
//Compute Min, max and mean.
void computesValues (float arr[], int size, float &mean, float &max, float &min){
}
void computesValues (float arr[], int size, float &mean, float &max, float &min)
{
float sum = 0.0;
for (int i = 0; i<size; i++){
sum = sum+ arr[i];
}
mean = sum/size;
max = arr[0];
for (int i = 1; i<size; i++){
if(arr[i] > max)
max = arr[i];
}
min = arr[0];
for (int i = 1; i<size; i++){
if(arr[i] < min)
min = arr[i];
}
printf("mean = %f max = %f min = %f\n", mean, max, min);
}
Mean is the average of the sum of the array elements: you have to add up the elements of the array and divide it by number of elements
To compute the maximum, set the first element as max, compare it with other elements and update it if any of the other elements exceeds it.
To compute the minimum, set the first element as min, compare it with other elements and update it if any of the other elements is less than it.
my assignment:
program should feature 2 functions, one to calculate the average of the values in the array (returning result as double) and one to find peak value in array (returning result as unsigned value). The array (unsigned ints) and number of values in the array(unsigned int) should be passed through functions as parameters.
Can someone please explain how to fix my code??
#include <iostream>
using namespace std;
#define SIZE 10
double findAverage (unsigned int);
unsigned findPeak (unsigned int);
unsigned numbers [SIZE] = {47, 1, 0, 1324, 99, 1000, 65536, 19, 0, 24000 };
unsigned sum;
unsigned peak;
int main()
{
double average;
for (int i = 0 ; i < SIZE; i++)
{
sum += numbers[i];
}
average = findAverage(numbers[SIZE]);
cout << "The average value is : " << average << endl;
peak = findPeak(numbers[SIZE]);
cout << "The peak value is : " << peak << endl;
}
double findAverage (unsigned sum)
{
double average;
average = sum / SIZE;
return average;
}
unsigned findPeak (unsigned int *)
{
for (int i = 0 ; i < SIZE; i++)
{
if (numbers[i] > peak)
{
peak = numbers[i];
}
}
return peak;
}
From the assignment description:
The array (unsigned ints) and number of values in the array(unsigned
int) should be passed through functions as parameters.
And where are there the two parameters in the functions?
double findAverage (unsigned int);
unsigned findPeak (unsigned int);
The functions can be defined the following way
double findAverage( const unsigned int a[], unsigned int n )
{
double sum = 0.0;
for ( unsigned int i = 0; i < n; i++ ) sum += a[i];
return n == 0 ? sum : sum / n;
}
unsigned int findPeak( const unsigned int a[], unsigned int n )
{
unsigned int max = 0;
for ( unsigned int i = 1; i < n; i++ )
{
if ( a[max] < a[i] ) max = i;
}
return max;
}
I defined function findPeak such a way that it retursn the index of the maximum element. You may rewrite it that it would return the maximum element itself.
Take into account that these tasks can be done with using standard algorithms std::accumulate and std::max_element declared respectively in headers <numeric> and
<algorithm>.
Also there is no any need to define your varaibles in the global namepsace. They could be defined like local variables of main.
You're passing numbers[SIZE] to findAverage instead of sum.
The parameter's name is missing in findPeak's definition.
Also, numbers[SIZE] is not in the array, numbers[SIZE-1] is the last element of the array, because indexing starts at 0.
It's also not a good idea to specify the size of the array and add the elements by hand (in {}). You can easily make a mistake.
Also, you should put all the code in the functions. So in main, you just call them. Don't use global variables either, they aren't necessary here at all and can cause all sorts of problems in bigger projects. So don't get used to bad habits.
Just put your variables in main and pass them to the functions as parameters.
(You're actually doing this, but currently it's unnecessary because for example sum is global.)
Your functions should be independent and reusable:
They should not rely on SIZE
They should not directly use the array: the array with the size should be parameters. Pass as const (no need to modify the array).
Below an example:
double findAverage (const unsigned myArray[], int arraySize)
{
unsigned sum = 0;
double average = 0.0;
for (int i = 0 ; i < arraySize; i++)
{
sum += myArray[i];
}
if (arraySize) average = sum / arraySize;
return average;
}
unsigned findPeak (const unsigned myArray[], int arraySize)
{
unsigned peak = 0;
for (int i = 0 ; i < arraySize; i++)
{
if (myArray[i] > peak)
{
peak = numbers[i];
}
}
return peak;
}
The call:
average = findAverage(numbers, SIZE);
peak = findPeak(numbers,SIZE);
Here a running version:
#include <iostream>
using namespace std;
double findAverage (unsigned int *, unsigned int);
unsigned int findPeak (unsigned int *, unsigned int);
int main()
{
const int size = 10;
unsigned int numbers [] = {47, 1, 0, 1324, 99, 1000, 65536, 19, 0, 24000 };
double average = findAverage(numbers, size);
cout << "The average value is : " << average << endl;
unsigned int peak = findPeak(numbers, size);
cout << "The peak value is : " << peak << endl;
}
double findAverage (unsigned int *numbers, unsigned int size)
{
unsigned int sum = 0;
for (int i = 0 ; i < size; i++)
{
sum += numbers[i];
}
double average = (double)sum / size;
return average;
}
unsigned int findPeak (unsigned int *numbers, unsigned int size)
{
unsigned int peak = 0;
for (int i = 0 ; i < size; i++)
{
if (numbers[i] > peak)
{
peak = numbers[i];
}
}
return peak;
}
Remarks:
You should avoid global variables.
I think the sum calculation makes more sense in findAverage(). Then it has to get passed the array.
The declaration of findPeak missed a *, it did not match the definition.
To pass an array, you must not provide any [...]. Just pass the pointer to the first element by writing the array name.
average = sum / SIZE; firstly evaluates sum / SIZE by doing an integer division, so the result is truncated. You have to cast one of the operands to force a double division.