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
}
Related
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;
I am trying to use bubble sort to sort a set of random numbers. But my code results in a messed up order. For example, instead of it sorting 9 12 15 100 150,it will sort as 12 15 100 9 150. Any help will be appreciated. Below is my code.
#include <iostream>
#include <cstdlib>
using namespace std;
void sortArray(int[], int);
void showArray(const int[], int);
int main()
{
const int MIN_VALUE = 1;
const int MAX_VALUE = 200;
int numbers[MAX_VALUE];
for (int count = 0; count < MAX_VALUE; count++)
{
numbers[count] = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE;
cout << numbers[count]<< endl;
sortArray(numbers, count);
showArray(numbers, count);
}
}
void sortArray(int numbers[], int size)
{
bool swap;
int temp;
do
{
swap = false;
for (int count = 0; count < (size -1); count++)
{
if (numbers[count] > numbers[count + 1])
{
temp = numbers[count+1];
numbers[count+1] = numbers[count];
numbers[count] = temp;
swap = true;
}
}
} while (swap);
}
void showArray(const int numbers[], int size)
{
for (int count = 0; count < size; count++)
cout <<numbers[count] << endl;
}
Thanks
The sorting code is correct.
The only problem is that you're calling the sort and printing out the array in the same loop that is filling the data.
You should first fill all the data, then sort, then display the sorted result.
http://imgur.com/TnUACAc
This is the link that shows the result.
And this result is how my result of C++ must be like
As this result shows, there are Bubble sort, Selection Sort, and Insertion Sort,
and every process of each sort is shown to the black screen.
For example, (Bubble Sort)
20 10 40 30
20 10 30 40
10 20 30 40.
I have to use void displayPtrArray to show like that.
#include <iostream>
#include <string>
#include <array>
#include <iomanip>
using namespace std;
void reset(int array[], const int size);
void displayIntArray();
void displayPtrArray(const int array[], int size);
void BubbleSort(int array[], int size);
void SelectionSort(int array[], int size);
void InsertionSort(int a[], int size);
const int RR = 4;
int main()
{
int arr[RR];
reset(arr, RR);
}
void reset(int array[], const int size)
{
cout << "The originial array has been reset to:" << endl;
int array[RR] = { 20, 40, 10, 30 };
for (int n = 0; n < size; n++)
{
cout << setw(5) << array[n];
}
cout << endl << endl;
}
void displayPtrArray(const int array[], int size)
{
}
void displayIntArray()
{
}
void BubbleSort(int array[], int size)
{
bool swap;
int temp;
do
{
swap = false;
for (int count = 0; count < (size - 1); count++)
{
if (array[count] > array[count + 1])
{
temp = array[count];
array[count] = array[count + 1];
array[count + 1] = temp;
swap = true;
}
}
} while (swap);
}
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;
}
}
void InsertionSort(int a[], int size)
{
for (int i = 1; i<size; i++)
{
int j;
int current = a[i];
for (j = i - 1; j >= 0 && a[j]> current; j--)
{
a[j + 1] = a[j];
}
a[j + 1] = current;
}
}
I use the function for every sort, but if that is wrong please tell me.
And teach me how to show the process of each sort with
void displayPtrArray
I really don't know..... T_T...........
PLEASE HELP !!
You already have the exact code you need for displayPtrArray! The for loop defined in reset should do it.
Looking at the expected output, the array gets displayed every time there's a change to it. For bubble sort, the array changes when you do your swap (at the end of the if statement), so you want to add your call to displayPtrArray in the line after swap = true.
For selection sort, the array changes at the end of your outer for loop, so you should add the call to displayPtrArray in the line after array[startScan] = minValue;.
For insertion sort, the array changes at every iteration of the inner for loop and also in the last line of the outer for loop, so you'll probably have to call displayPtrArray in both of those places.
Note: just in case you aren't familiar with the syntax, you call the function like this: displayPtrArray(array, size); where array is the name of your array variable (the name is array in bubble and selection sorts; it's a in insertion sort) and size is the size of the array (named consistently in all three of your sorting functions).
Actually, viewing the process of the sorting is rather simple. You just have to output during the sorting process. You don't need to call another function for that. Try something like this
void BubbleSort(int array[], int size)
{
bool swap;
int temp;
do
{
swap = false;
for (int count = 0; count < (size); count++)
{
if (array[count] > array[count + 1])
{
temp = array[count];
array[count] = array[count + 1];
array[count + 1] = temp;
swap = true;
}
cout << "\nThe array is ";
for ( int i = 0; i < ( size - 1 ); i++ )
cout << array[i] << "\t"; // Look here
cout << "\nThe value of temp is " << temp << endl; // and here
}
} while (swap);
}
I need to calculate the total number of swapping process and sorting running time for my bubble sort function. For running time, I was successful. But for the total number of swapping processes, I couldn't really understand what to do. I thought of initializing "count" and then tried to call it into the main function. That was a failure.
This if my bubble sort function:
void bubbleSort(T patient[], int size)
{
bool noChange = true; // stop when a pass causes no change
for(int i = size; i > 0; i--)
{
noChange = true;
for(int j = 1; j < i; j++)
{
if(patient[j] < patient[j - 1])
{
swap(patient[j], patient[j-1]);
count = count + 1;
noChange = false;
} // end if
} // end for(j)
if (noChange)
return; // sorted--no need to continue
} // end for(i)
}
"count" seems to show no value when called into the main function. Any tips on what I should try so that I could get the total number of swapping process in this?
EDIT 3:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <time.h>
#include <string>
#include <ctime>
using namespace std;
const int SIZE = 5;
template <class T>
void printArray(T ar[], int sz);
template <class T>
int bubbleSort(T ar[], int sz);
//////////////////////////////////////////////////////////////////////////
// Main Function Implementation
//////////////////////////////////////////////////////////////////////////
int main() {
int numOfData = 50000;
string line, temp;
ofstream resultFile;
string patient[numOfData];
ifstream dataFile("shufflePatient.txt");
int times,i,count;
cout << "Program to shuffle data" << endl << endl;
cout << "This program will calculate swapping processes and running time.";
/*Storing data*/
cout << "Reading data in process.." << endl;
if (dataFile.is_open()) {
i=-1;
while (dataFile.good()) {
getline (dataFile, line);
if (i>=0) patient[i] = line;
i++;
}
dataFile.close();
}
double start_s=clock();
bubbleSort(patient,SIZE);
double stop_s=clock();
cout << "time: " << (stop_s-start_s)/double(CLOCKS_PER_SEC) << endl;
count = bubbleSort(patient,SIZE) ;
cout << "swapping process : " << count ;
cin.get(); // hold window open
/*Writing to file*/
cout << "Writing to file.." << endl;
resultFile.open ("test.txt");
for (int i=0 ; i<numOfData ; i++) {
resultFile << patient[i] << "\n";
}
resultFile.close();
system("pause");
return 0;
}
//----------------------------------------------------------------------------
// prints array of size size
//----------------------------------------------------------------------------
template <class T>
void printArray(T patient[], int size)
{
for(int i = 0; i < size; i++)
cout << patient[i] << " ";
cout << endl;
}
//----------------------------------------------------------------------------
// sorts array of size size by Bubble Sort method
//----------------------------------------------------------------------------
template <class T>
int bubbleSort(T patient[], int size) //returning an int
{
int count = 0; //initializing count
bool noChange = true;
for(int i = size; i > 0; i--)
{
noChange = true;
for(int j = 1; j < i; j++)
{
if(patient[j] < patient[j - 1])
{
swap(patient[j], patient[j-1]);
count = count + 1;
noChange = false;
}
}
if (noChange)
return count; // returning count
}
return count; // returning count
}
This is my updated code. Count value returns to 0. I don't know if the code I've used is right or wrong (where i call the return value of count). Any thoughts?
PS
Also, after changing my functions from void to int, for some reason my code stops sorting the data alphabetically when its written into the "text" file. Whats up with this?
You are not using the return value from the function, why don't you make the function return int - and return the count of number of swaps:
int bubbleSort(T patient[], int size) //returning an int
{
int count = 0; //initializing count
bool noChange = true;
for(int i = size; i > 0; i--)
{
noChange = true;
for(int j = 1; j < i; j++)
{
if(patient[j] < patient[j - 1])
{
swap(patient[j], patient[j-1]);
count = count + 1;
noChange = false;
}
}
if (noChange)
return count; // returning count
}
return count; // returning count
}
PS
The problem in the original code could be where you declared or initialized count (which is not shown in the code snap).
Also, using local variable is usually a better practice than using global ones.