My code is done and working. But i cant figure out how to count the number of attempts made by the user and invalid account numbers that were entered. I am supposed to do this in main starting after cin >> accountNum. After the user enters 9999 to quit, it is supposed to display the number of attempts made and the number of invalid charge account numbers that were entered. When i run it i get 0 for number of attempts and -1 for invalid numbers entered.
#include <iomanip>
#include <iostream>
#include <fstream>
using namespace std;
void getAccountNumbers(int[], int);
void displayAccountNumbers(int[], int);
void selectionSort(int[], int);
int binarySearch(const int[], int, int);
int main()
{
int accountNum;
int results;
int attempts = 0;
int invalidNumbers = 0;
const int ARRAY_SIZE = 18; // Array size
int numbers[ARRAY_SIZE]; // Array with 18 elements
int count = 0;
//ifstream inputFile;
getAccountNumbers(numbers, ARRAY_SIZE);
cout << "Original Order" << endl;
displayAccountNumbers(numbers, ARRAY_SIZE);
selectionSort(numbers, ARRAY_SIZE);
cout << "Sorted List" << endl;
displayAccountNumbers(numbers, ARRAY_SIZE);
cout << "********************" << endl;
cout << "Enter an Account number or 9999 to quit" << endl;
cin >> accountNum;
if(accountNum == 9999)
{
cout << "Thank You!" << endl;
}
while(accountNum != 9999)
{
results = binarySearch(numbers, ARRAY_SIZE, accountNum);
if(results == -1)
{
cout << "That number was not found" << endl;
invalidNumbers = results++;
}
else
{
cout << "That number is valid " << endl;
}
attempts = results++;
cin >> accountNum;
}
cout << "Number of attempts: " << attempts << endl;
cout << "Invalid numbers entered: " << invalidNumbers << endl;
system("pause");
return 0;
}
void getAccountNumbers(int nums[], int size)
{
ifstream inputFile;
int count = 0;
//Open the file
inputFile.open("charges.txt");
while(count < size && inputFile >> nums[count])
count ++;
//Close the file
inputFile.close();
}
void displayAccountNumbers(int nums[], int size)
{
for(int count = 0; count < size; count++)
cout << nums[count] << "\t";
cout << endl << endl;
}
void selectionSort(int nums[], int size)
{
int startScan, minIndex, minValue;
for(startScan = 0; startScan < (size - 1); startScan++)
{
minIndex = startScan;
minValue = nums[startScan];
for(int index = startScan + 1; index < size; index++)
{
if(nums[index] < minValue)
{
minValue = nums[index];
minIndex = index;
}
}
nums[minIndex] = nums[startScan];
nums[startScan] = minValue;
}
}
int binarySearch(const int nums[], int size, int value)
{
int first = 0, //First element
last = size - 1, // Last element
middle, // Midpoint
position = -1; //Position of search value
bool found = false;
while(!found && first <= last)
{
middle = (first + last) / 2; //Midpoint
if(nums[middle] == value)
{
found = true;
position = middle;
}
else if(nums[middle] > value) // Value is in lower half
last = middle - 1;
else
first = middle + 1; // Value is in upper half
}
return position;
}
Your problem is in the lines where you are trying to add to invalidNumbers and attempts. The ++ postfix operator adds one to the number before it. You needn't say invalidNumbers = results++;; you merely need invalidNumbers++;, and the same applies for attempts. What your code was doing was setting invalidNumbers (and attempts) to the value of results and then adding one to results instead.
Related
`
#include <iostream>
#include <iomanip>
using namespace std;
void getGrades(double g[], const int SIZE)
{
cout << "Please enter " << SIZE << " grades:" << endl;
for(int i = 0; i < SIZE; i++)
{
cin >> g[i];
}
}
double getAverage(double g[], const int SIZE)
{
int total = 0;
for(int i = 0; i < SIZE; i++)
{
total += g[i];
}
return total/SIZE;
}
void findDropInfo(double g[], const int SIZE, int &lowest, double average)
{
int total = 0;
lowest = g[0];
for(int i = 1; i < SIZE; i++)
{
if (lowest > g[i]) {
lowest = g[i];
}
}
average = (total - lowest)/SIZE;
return average;
}
void printData(double g[], int lowest, double average, double avg_before)
{
cout << "The 5 grades entered by the user are:" << endl;
cout << g[];
cout << "Grade dropped: " << lowest << endl;
cout << "Final Average: " << average << endl;
cout << "Average before drop: " << avg_before << endl;
}
// TODO: Complete the function definitions
int main()
{
const int SIZE = 5;
double grades[SIZE];
int lowest;
double avg,
avgBeforeDrop;
// TODO: Add function calls
getGrades(grades[SIZE], SIZE);
getAverage(grades[SIZE], SIZE);
findDropInfo(grades[SIZE], SIZE, lowest, avg);
printData(grades[SIZE], lowest, avg, avgBeforeDrop);
return 0;
}
`
Whenever I run the program, I get multiple errors saying there's no matching candidate function. I'm not sure if the problems are in the functions themselves or in the function calls, but from what I know the functions themselves should be fine. I'm also told there's an expected expression in g[] but I' not sure what's wrong there either, as it's meant to be empty.
Most issues have already been resolved in the comments, but note: cout << g[] does not print the elements of g.
The way to do this is
char separator = /* the character you want to use to separate the printed elements of g */
for (int i = 0; i < SIZE; i++)
{
cout << g[i] << separator;
}
if (separator != '\n') cout << '\n'; //this is to put the next print on the next line
I would put this as a comment but I don't have enough reputation :|
For an assignment, we were to fill an array with user-defined characters that stops filling once the user enters a full stop ".". Part of the assignment is to print out the characters entered in the array in reverse, but what I have seems to just print nothing.
First time asking, so apologies if it's a silly question. Thanks in advance.
#include <iostream>
using namespace std;
//Function declarations
bool fillArray(char charArray[], int arraySize, int& numberUsed);
void outputInReverse(const char charArray[], int& numberUsed);
int main() {
const int arraySize = 100;
char charArray[arraySize] = { };
int numberUsed = 0;
//Function calls
cout << "\nFILLING ARRAY....\n";
fillArray(charArray, arraySize, numberUsed);
cout << "\nARRAY OUTPUT....\n";
outputInReverse(charArray, numberUsed);
}
//Function definitions
bool fillArray(char charArray[], int arraySize, int& numberUsed) {
char inputChar;
int index = 0;
const char sentinel = '.';
bool sentinelEntered = false;
bool arrayFull = false;
int count = 0;
//Take user input
for (int i = 0; i < arraySize; i++) {
if ((!sentinelEntered)) {
cout << "Enter up to " << arraySize << " character values. Enter full stop to end. " << "Enter char " << (i + 1) << ": " << endl;
cin >> inputChar;
charArray[index] = inputChar;
//How many entries made
numberUsed = i;
count++;
if ((inputChar == sentinel)) {
sentinelEntered = true;
cout << "Number of entries: " << (count - 1) << endl;
return count;
}
}
}
if (numberUsed == arraySize) {
arrayFull = true;
return arrayFull;
}
return sentinelEntered;
return count;
}
// Reverse
void outputInReverse(const char charArray[], int& numberUsed) {
for (int i = numberUsed; i > 0; i--) {
cout << "Output in reverse: " << charArray[i] << endl;
}
}
FILLING ARRAY....
Enter up to 100 character values. Enter full stop to end. Enter char 1:
a
Enter up to 100 character values. Enter full stop to end. Enter char 2:
b
Enter up to 100 character values. Enter full stop to end. Enter char 3:
c
Enter up to 100 character values. Enter full stop to end. Enter char 4:
d
Enter up to 100 character values. Enter full stop to end. Enter char 5:
e
Enter up to 100 character values. Enter full stop to end. Enter char 6:
.
Number of entries: 5
ARRAY OUTPUT....
Output in reverse:
Output in reverse:
Output in reverse:
Output in reverse:
Output in reverse:
Not sure what you are trying to return from fillArray(), but since its a bool type, assuming you are trying to return if the array is empty or not. Observe added comments to see corrections.
int main() {
const int arraySize = 100;
//corrected
char charArray[arraySize] = { NULL };
int numberUsed = 0;
//Function calls
cout << "\nFILLING ARRAY....\n";
fillArray(charArray, arraySize, numberUsed);
cout << "\nARRAY OUTPUT....\n";
outputInReverse(charArray, numberUsed);
return 0;
}
bool fillArray(char charArray[], int arraySize, int& numberUsed) {
char inputChar;
int index = 0;
const char sentinel = '.';
bool sentinelEntered = false;
bool arrayFull = false;
int count = 0;
//Take user input
for (int i = 0; i < arraySize; i++) {
if ((!sentinelEntered)) {
cout << "Enter up to " << arraySize << " character values. Enter full stop to
end. " << "Enter char " << (i + 1) << ": " << endl;
cin >> inputChar;
//corrected: shifted here so before '.' can enter into array we return
if ((inputChar == sentinel)) {
sentinelEntered = true;
cout << "Number of entries: " << (count) << endl;
//correction: update numberUsed before returning and no of
//elements = count
numberUsed = i;
return count;
}
//correction: array index should not be "index" but i
charArray[i] = inputChar;
//How many entries made
numberUsed = i;
count++;
}
}
if (numberUsed == arraySize)
return true;
return false;
}
void outputInReverse(const char charArray[], int& numberUsed) {
for (int i = numberUsed-1; i >= 0; i--) {
cout << "Output in reverse: " << charArray[i] << endl;
}
}
(Sorry if this is formatted terribly. I've never posted before.)
I've been working on a program for class for a few hours and I can't figure out what I need to do to my function to get it to do what I want. The end result should be that addUnique will add unique inputs to a list of its own.
#include <iostream>
using namespace std;
void addUnique(int a[], int u[], int count, int &uCount);
void printInitial(int a[], int count);
void printUnique(int u[], int uCount);
int main() {
//initial input
int a[25];
//unique input
int u[25];
//initial count
int count = 0;
//unique count
int uCount = 0;
//user input
int input;
cout << "Number Reader" << endl;
cout << "Reads back the numbers you enter and tells you the unique entries" << endl;
cout << "Enter 25 positive numbers. Enter '-1' to stop." << endl;
cout << "-------------" << endl;
do {
cout << "Please enter a positive number: ";
cin >> input;
if (input != -1) {
a[count++] = input;
addUnique(a, u, count, uCount);
}
} while (input != -1 && count < 25);
printInitial(a, count);
printUnique(u, uCount);
cout << "You entered " << count << " numbers, " << uCount << " unique." << endl;
cout << "Have a nice day!" << endl;
}
void addUnique(int a[], int u[], int count, int &uCount) {
int index = 0;
for (int i = 0; i < count; i++) {
while (index < count) {
if (u[uCount] != a[i]) {
u[uCount++] = a[i];
}
index++;
}
}
}
void printInitial(int a[], int count) {
int lastNumber = a[count - 1];
cout << "The numbers you entered are: ";
for (int i = 0; i < count - 1; i++) {
cout << a[i] << ", ";
}
cout << lastNumber << "." << endl;
}
void printUnique(int u[], int uCount) {
int lastNumber = u[uCount - 1];
cout << "The unique numbers are: ";
for (int i = 0; i < uCount - 1; i++) {
cout << u[i] << ", ";
}
cout << lastNumber << "." << endl;
}
The problem is my addUnique function. I've written it before as a for loop that looks like this:
for (int i = 0; i < count; i++){
if (u[i] != a[i]{
u[i] = a[i]
uCount++;
}
}
I get why this doesn't work: u is an empty array so comparing a and u at the same spot will always result in the addition of the value at i to u. What I need, is for this function to scan all of a before deciding whether or no it is a unique value that should be added to u.
If someone could point me in the right direction, it would be much appreciated.
Your check for uniqueness is wrong... As is your defintion of addUnique.
void addUnique(int value, int u[], int &uCount)
{
for (int i = 0; i < uCount; i++){
if (u[i] == value)
return; // already there, nothing to do.
}
u[uCount++] = value;
}
#include <iostream>
#include <iomanip>
using namespace std;
// Function Prototype
void sortArray(int array[], int size);
void showArray(const int arr[], int size);
void average(int testScores[], int size);
int main()
{
int *testScores;
int numGrades,count;
cout << "How many grades? " << endl;
cin >> numGrades;
testScores = new int[numGrades];
cout << "Please enter the scores below." << endl;
for (count = 0; count < numGrades; count++)
{
cin >> testScores[count];
}
sortArray(testScores, numGrades);
showArray(testScores, numGrades);
average(testScores, numGrades);
delete[] testScores;
testScores = 0;
system("pause");
return (0);
}
//function for ascending order
int * testScores[];
void sortArray(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);
}
// display array function
void showArray(const int arr[], int size)
{
cout << " Scores in ascending order." << endl;
for (int count = 0; count < size; count++)
{
cout << " " << arr[count] << "";
}
cout << endl;
cout << endl;
}
// function to get average of the array
void average(int testScores[], int numGrades)
{
float total = 0.0;
for (int count = 0; count < numGrades; count++)
{
total += testScores[count];
}
float average = total / numGrades;
cout << " This is the average of the scores entered." << endl;
cout << endl;
cout << fixed << showpoint << setprecision(2);
cout << " *** " << average << " ***" << endl;
}
So this program was made to allow students to enter as many test scores as they want and the program will show them in ascending order and then will calculate the average of all test scores. It works wonderful until you enter a negative test score and then it throws the averaging process off. I can't seem to be able to make the program not accept the negative numbers. Any clues or hints would work wonders! Please and Thank You.
You are doing this:-
cin >> testScores[count];
This would accept all integers positive as well as negative. One way is to check the number, if it's positive then insert it into array.
Hello I am not sure what is wrong with my code.
Selection Sort works but when the program asks the user again to input a name, they don't get the correct person. Can someone help me? I'm not sure what is wrong.
EDIT: The error I am getting now for the second time I ask for input is "Name not found". I don't get why
Image is here:
http://i.imgur.com/2Gkd0gh.pngh
Here is my complete code:
#include <iomanip>
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
// GLOBAL CONSTANTS
const int NUM_NAMES = 20;
// FUNCTION PROTOTYPES
void getNames(ifstream &, string[], int[], int);
int linearSearch(const string[], int, string);
int binarySearch(const string[], int, string);
void selectionSort(string[], int[], int);
void displayData(const string[], const int[], int);
void displaySearch(const string[], const int[], int);
int main()
{
// LOCAL VARIABLES
string names [NUM_NAMES];
int marks [NUM_NAMES];
ifstream inStream; // Input file stream variable
int index = 0;
string searchWho;
// FUNCTION CALL 1
getNames (inStream, names, marks, NUM_NAMES);
cout << endl;
cout << " Students and Marks:" << endl;
cout << " ______________________________" << endl << endl;
// FUNCTION CALL 2: DisplayData
displayData(names, marks, NUM_NAMES);
// OUTPUT - Perform search - USER INPUT
cout << endl;
cout << " Please enter the first and last name of who who want to look up, seperated with a space." << endl << endl;
cout << " "; cin >> searchWho;
cout << endl << endl;
// FUNCTION CALL 3: linearSearch
index = linearSearch (names, NUM_NAMES, searchWho);
// FUNCTION CALL 4: displaySearch
displaySearch(names, marks, index);
// FUNCTION CALL 5: selectionSort
selectionSort (names, marks, NUM_NAMES);
cout << endl;
cout << " Students and Marks:" << endl;
cout << " ______________________________" << endl << endl;
displayData(names, marks, NUM_NAMES);
// OUTPUT - Perform search - USER INPUT
cout << endl;
cout << " Please enter the first and last name of who who want to look up, seperated with a space." << endl << endl;
cout << " "; cin >> searchWho;
cout << endl << endl;
// FUNCTION CALL 4
index = binarySearch (names, NUM_NAMES, searchWho);
displaySearch(names, marks, index);
cout << " "; return 0;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// FUNCTION 1: getNames
// DESCRIPTION: Function opens data file students.txt
// Function reads data from students.txt and stores data
// appropriately according to customerCode and utilityCharge
// in parallel arrays Customer[] and Charge[]
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void getNames (ifstream &inStream, string names[], int marks[], int numElts)
{
// Open input file
inStream.open ("students.txt");
string studentNames; // Student names - Last name followed by first
int studentMarks = 0; // Student mark for text/exam
// Read in data from students.txt
while (!inStream.eof())
{
for(int count = 0; count < numElts; count ++)
{
inStream >> names[count];
inStream >> marks[count];
}
}
inStream.close();
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// FUNCTION: LinearSearch
// DESCRIPTION:
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
int linearSearch (const string names[], int numElts, string who)
{
int index = 0; // Used as a subscript to search array
int position = -1; // To record position of search value
bool found = false; // Flag to indicate if value was found
while (index < numElts && !found)
{
if (names[index] == who) // If the name is found
{
found = true; // Set the flag
position = index; // Record the value's subscript
}
index++; // Go to the next element
}
return position; // Return the position, or -1
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// FUNCTION: SelectionSort
// DESCRIPTION:
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void selectionSort(string names[], int marks[], int numElts)
{
int startScan;
int minIndex;
int startName;
for (startScan = 0; startScan < (numElts - 1); startScan++)
{
startName = startScan;
for (int minIndex = startScan + 1; minIndex < numElts; minIndex++)
{
if (names[minIndex] > names[startName])
{
startName = minIndex;
string tempString = names[startScan];
names[startScan] = names[minIndex];
names[minIndex] = tempString;
// Aligning arrays
int tempInt = marks[startScan];
marks[startScan] = marks[minIndex];
marks[minIndex] = tempInt;
}
}
}
}
int binarySearch(const string names[], int numElts, string who)
{
int first = 0; // First array element
int last = numElts - 1; // Last array element
int middle; // Mid point of search
int position = -1; // Position of search value
bool found = false; // Flag
while (!found && first <= last)
{
middle = (first + last) / 2; // Calculate mid point
if (names[middle] == who) // If value is found at mid
{
found = true;
position = middle;
}
else if (names[middle] > who) // If value is in lower half
{
last = middle - 1;
}
else
{
first = middle + 1; // If value is in upper half
}
}
return position;
}
void displayData(const string names[], const int marks[], int numElts)
{
// OUTPUT
for (int count = 0; count < numElts; count++)
{
cout << " " << left << setw(15) << names[count] << right << setw(15) << marks[count] << endl;
}
}
void displaySearch(const string names[], const int marks[], int index)
{
if (index == -1)
{
cout << " Name not found. Restart the program to search again." << endl << endl;
}
else
{
cout << names[index] << " scored " << marks[index] << " marks." << endl << endl;
}
}
From the shared image http://i.imgur.com/2Gkd0gh.pngh, the array is not properly sorted. For examples,
Allison,Jeff 45
Collins,Bill 80
Allen,Jim 82
As in the code belows:
if (names[minIndex] > names[startName])
{
startName = minIndex;
//...
}
startName means the index of the max name in names array, doesn't it? (the array is descendingly sorted, right?)
So it supposes to be to swap the max name at index startName with the current scanning name at index startScan. Then it should be
startName = startScan;
for (int minIndex = startScan + 1; minIndex < numElts; minIndex++)
{
if (names[minIndex] > names[startName])
{
startName = minIndex;
}
}
string tempString = names[startScan];
names[startScan] = names[startName];
names[startName] = tempString;
// Aligning arrays
int tempInt = marks[startScan];
marks[startScan] = marks[startName];
marks[startName] = tempInt;
And in the binarySearch, it supposes the array is in ascending order.
Therefore, to sort the array in ascending order, you may change
if (names[minIndex] > names[startName])
{
startName = minIndex;
}
to
if (names[minIndex] < names[startName])
{
startName = minIndex;
}