C++ getSmallest program - c++

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/

Related

C++ array assistance

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 ?

function was not declared in this scope? [duplicate]

This question already has answers here:
Why is my HelloWorld function not declared in this scope?
(11 answers)
Closed 5 years ago.
I'm trying to write a program that displays asterisks and spaces based on their input and I've run into a compiler problem:
chart.cpp:24:41: error: ‘find_largest’ was not declared in this scope
int largest = find_largest(values, size);
This is my code:
/*
* Project 1
* Author: Erik Ingvoldsen
* Date: 2/1/2018
*/
#include <iostream>
using namespace std;
int size = 0; //initalizing "size" at 0.
const int MAX = 100; //setting max value
int values[MAX]; //100 int limit
int main(){
int num;
for (int i = 0; i < MAX; i++) {
cin >> num; //allow the user to put in a number
values[i] = num; //assigning value to the array
if (num <= 0) {
break; //stop if "0" or lower is entered
}
size++; //increase the size of array, assuming the for loop hasn't been broken
}
int largest = find_largest(values, size); //setting the amount of rows
for (int i = 0; i < size; i++) {
if (values[i] = largest) {
cout << "*"; //if the value of the area reachest the highest row, give a *
} else {
cout << "\n"; //otherwise just give a blank space
}
largest--; //by shrinking "largest", we move down the next row
cout << endl;
}
return 0;
}
int find_largest(int values[], int size) {
int largest = 0;
for (int i = 0; i < size; i++) {
if (values[i] > largest) {
largest = values[i]; //if the value of the array is bigger than the current largest it is replace
}
}
return largest; //once the for loop is completed, it returns the largest number found
}
I really can't tell the difference between this and the function...and I'm pretty sure I'm not supposed to declare it as "int largest = find_largest(values[], size);"
You are supposed to declare all functions before you use them. Simple way to do that is to use a prototype.
// prototype
int find_largest(int values[], int size);
int main(){
...
}
int find_largest(int values[], int size) {
...
}

Having issues eliminating duplicates and sorting from C++ array outfile

Trying to create a list of unique grades from a text file. Having issues with the output eliminating duplicates. Currently, I am trying to compare the value of each previous array entry to the next and if they are different, output the result to the outfile, but is just outputs an empty file.
I am also curious if there is an easy fix to change the sorting from 'low to high' into 'high to low'. Thank you in advance.
#include <iostream>
#include <string>
#include <limits>
#include <cmath>
#include <iomanip>
#include <fstream>
using namespace std;
int testScoreArray[100];
void selectSort(int testScoreArray[], int n);
void fileOutput(int testScoreArray[]);
int main()
{
int n = 100;
ifstream infile;
infile.open("testscoresarrayhomework.txt");
for (int i = 0; i < 100; i++) {
infile >> testScoreArray[i];
}
selectSort(testScoreArray, n);
fileOutput(testScoreArray);
infile.close();
return 0;
}
void selectSort(int testScoreArray[], int n)
{
//pos_min is short for position of min
int pos_min, temp;
for (int i = 0; i < n - 1; i++) {
pos_min = i; //set pos_min to the current index of array
for (int j = i + 1; j < n; j++) {
if (testScoreArray[j] < testScoreArray[pos_min])
pos_min = j;
//pos_min will keep track of the index that min is in, this is needed when a swap happens
}
//if pos_min no longer equals i than a smaller value must have been found, so a swap must occur
if (pos_min != i) {
temp = testScoreArray[i];
testScoreArray[i] = testScoreArray[pos_min];
testScoreArray[pos_min] = temp;
}
}
};
void fileOutput(int testScoreArray[])
{
ofstream outfile;
int gradeEvent = 0;
int previousGrade = 0;
outfile.open("testscoresoutput.txt");
outfile << "Test Score Breakdown: ";
outfile << endl
<< "Score / Occurance";
for (int i = 0; i < 100; i++) {
previousGrade = i;
if (previousGrade && previousGrade != i) {
outfile << '\n' << testScoreArray[i] << " / " << gradeEvent;
}
}
outfile.close();
};
You have declared a global variable testScoreArray and the function names use the same variable name for their parameters. It's best to avoid using global variables when possible. You can remove global declaration, then declare testScoreArray in main, and pass it to your functions. Example:
//int testScoreArray[100]; <=== comment out
void selectSort(int *testScoreArray, int n);
void fileOutput(int *testScoreArray, int n); //add array size
int main()
{
int testScoreArray[100]; //<== add testScoreArray in here
int n = sizeof(testScoreArray) / sizeof(testScoreArray[0]);
selectSort(testScoreArray, n);
fileOutput(testScoreArray, n);
...
}
In fileOutput you are basically checking to see if i != i, you need to examine the array, not indexing in the loop:
void fileOutput(int *testScoreArray, int n)
{
ofstream outfile("testscoresoutput.txt");
for(int i = 0; i < n; i++)
if(i && testScoreArray[i] != testScoreArray[i-1])
outfile << testScoreArray[i] << "\n";
};
To revers the sort, simply change the condition in this comparison
if (testScoreArray[j] < testScoreArray[pos_min])
pos_min = j;
To:
if(testScoreArray[j] > testScoreArray[pos_min])
pos_min = j;
Technically you would rename the variable to pos_max

C++ Program To Find Smallest and Largest Number In Array

Beginner in C++ here and learning arrays. The program below is supposed to return the smallest and largest number in an array using two separate functions. One for the largest and one for the smallest number. However, it is returning 0 all the time for function lastLowestIndex and I am unsure what I may be doing wrong.
Could someone ever so kindly advice and show me what is incorrect in that function and what can be done to correct it so that it returns the correct value? I am obviously not seeing and/or understanding what is incorrect.
Thank you so very much for your help and time in advance!!!
#include <iostream>
#include <cstdlib>
int lastLargestIndex(int [], int);
int lastLowestIndex(int [], int );
using namespace std;
int main()
{
const int N = 15;
int arr[N] = {5,198,76,9,4,2,15,8,21,34,99,3,6,13,61};
int location;
//int location2;
location = lastLargestIndex( arr, N );
cout << "The last largest number is:" << location << endl;
location = lastLowestIndex(arr, N);
cout << "The last smallest number is:" << location << endl;
// std::system ("pause");
return 0;
}
int lastLargestIndex( int arr[], int size )
{
int highNum = 0;
for( int i = 0; i < size; i++ )
{
if ( arr[i] > highNum )
{
highNum = arr[i];
}
}
return highNum;
}
int lastLowestIndex(int arr[], int size)
{
int smallest = 0;
for (int i = 0; i < size; i++)
{
if (arr[i] < smallest)
{
smallest = arr[i];
}
}
//cout << smallest << '\n';
return smallest;
}
However, it is returning 0 all the time for function lastLowestIndex and I am unsure what I may be doing wrong.
You got a logic error when you initialised smallest to 0 in function lastLowestIndex() - that way if (arr[i] < smallest) condition is not evaluated to true if all input is positive. Instead, you should initialise it to the first member of array arr. The function should look like this:
int lastLowestIndex(int arr[], int size)
{
int smallest = arr[0];
for (int i = 0; i < size; i++)
{
if (arr[i] < smallest)
{
smallest = arr[i];
}
}
return smallest;
}
lastLowestIndex() initialises smallest to be 0, and then compares all elements of the array (which are positive, in your example) with it. All positive values are greater than zero, so smallest will remain zero.
Note that your logic is also not general for finding the maximum. Consider what the code will do if all elements of the array are negative.
You would be better off adopting a logic that does not make any assumptions about the array, other than its size and that it contains integral values. For example;
int lastLargestIndex( int arr[], int size )
{
int highNum = arr[0];
for( int i = 1; i < size; i++ )
{
if ( arr[i] > highNum )
{
highNum = arr[i];
}
}
return highNum;
}
This doesn't exhibit the problems yours does, since it initialises highNum with the first element of the array, and iterates over the rest (if any). This does assume size is positive.
Your functions are also named in a misleading manner, since they (attempt to) return the maximum (or minimum) value in the array, but their name suggests they will return the index of that value. I'll leave resolving that little issue as an exercise.
This is the correct working code!
#include <iostream>
#include <cstdlib>
int lastLargestIndex(int [], int);
int lastLowestIndex(int [], int );
using namespace std;
int main()
{
const int N = 15;
int arr[N] = {5,198,76,9,4,2,15,8,21,34,99,3,6,13,61};
int location;
location = lastLargestIndex( arr, N );
cout << "The last largest number is:" << location << endl;
location = lastLowestIndex(arr, N);
cout << "The last smallest number is:" << location << endl;
// std::system ("pause");
return 0;
}
int lastLargestIndex( int arr[], const int size )
{
int highNum = -100001;
for( int i = 0; i < size; i++ )
{
if ( arr[i] > highNum )
{
highNum = arr[i];
}
}
return highNum;
}
int lastLowestIndex(int arr[], const int size)
{
int smallest = 100001;
for (int i = 0; i < size; i++)
{
if (arr[i] < smallest)
{
smallest = arr[i];
}
}
//cout << smallest << '\n';
return smallest;
}
Modifications done:
Replaced argument in function from int size to const int size, since N is declared as const int in main function
Replaced highNum with -100001
Replaced smallest with 100001

Extremely large numbers showing up in output file

I have a program which takes in a data file full of numbers (5 digits - 1 digit), sorts it, then calculates the average.
Problem is, for some strange reason, I seem to be getting random numbers. For example, here's an example of the output file (it changes everytime for some reason):
-1634367306
-1461109043
-542664683
-542664639
-542664491
-2
-1
-1
0
0
And towards the end...
2003150324
2003165000
2003165000
2003165011
2003165011
2003165090
2003195799
2003196010
2003196054
2003284685
2003834952
2006176524
2006176524
2006221796
2006221796
The numbers from the input file are from 0 - 99999, so I have no clue why these numbers are showing up.
Here's my code concurrently for it:
#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;
void getData(int[], int);
void outputData(int[], int);
double calcAverage(int[], int);
int findHighest(int[], int);
int findLowest(int[], int);
void removeDuplicates(int[], int);
void selectionSort (int[], int);
int main() {
const int SIZE = 1000;
int table[SIZE];
getData(table, SIZE);
selectionSort(table, SIZE);
cout << "Highest number: " << findHighest(table, SIZE) << endl;
cout << "Lowest number: " << findLowest(table, SIZE) << endl;
cout << "Average: " << calcAverage(table, SIZE) << endl;
outputData(table, SIZE);
}
/** selectionSort
** - Sorts an array of numbers
**/
void selectionSort(int array[], int size) {
int startScan, minIndex, minValue;
for (startScan = 0; startScan < (size - 1); startScan++) {
minIndex = startScan;
minValue = array[startScan];
for (int index = startScan + 1; index < size; index++) {
if (array[index] < minValue) {
minValue = array[index];
minIndex = index;
}
}
array[minIndex] = array[startScan];
array[startScan] = minValue;
}
}
/** getData
** - Opens a file of a set of numbers
** - Reads data from file into an array of numbers
**/
void getData(int table[], int size) {
ifstream iFile;
iFile.open("numbers.txt");
if (!iFile) {
cout << "File failed to load, please try again." << endl;
return;
}
for (int i = 0; i < size; i++) {
iFile >> table[i];
}
iFile.close();
}
/** outputData
** - outputs a sorted array of numbers to a text file
**/
void outputData(int table[], int size) {
ofstream oFile;
oFile.open("entry.txt");
for (int i = 0; i < size; i++) {
oFile << table[i] << endl;
}
oFile.close();
}
/** calcAverage
** - Calculate and return average of all data entries
**/
double calcAverage(int table[], int size) {
double total = 0;
for (int i = 0; i < size; i++) {
total += table[i];
}
return total / size;
}
/** findHighest
** - return highest number from array
**/
int findHighest(int table[], int size) {
int high = 0;
for (int i = 0; i < size; i++) {
if (table[i] > high)
high = table[i];
}
return high;
}
/** findLowest
** - return lowest number from array
**/
int findLowest(int table[], int size) {
int low = findHighest(table, size);
for (int i = 1; i < size; i++) {
if (table[i] < low)
low = table[i];
}
return low;
}
Typical results of the Highest, Lowest, Average, show:
Highest number: 2006221796 Lowest number: 2006221796 Average: 2.71055e
+ 007
No clue what I'm getting wrong here. No compiler errors, and I'm pretty sure everything was initialized properly.
'Input file is unordered, and has 921 lines of numbers' - so how your progam will know how many items were read into the array? You declare const int SIZE = 1000; and use that value as a range of sorting – so you're sorting 79 uninitialized items of the array, data which were not in your input,
Try writing your input routine something like this in order to determine the number of elements that were actually read in:
int getData(int table[], int maxsize) {
ifstream iFile("numbers.txt");
if (!iFile) {
cerr << "Can't open number.txt\n";
return 0;
}
int n, i = 0;
while (iFile >> n) {
if (i >= maxsize) {
cerr << "Table overflow\n";
break;
}
table[i++] = n;
}
iFile.close();
return i; // return the number of elements read
}