I am writing a program that's supposed to search an array that is filled by user input and return different output depending on whether or not another integer given by the user is in that array. the output is the index of the element.
e.g., suppose my array is {1, 2, 3}. using search(), if I enter 2, it should tell me that 2 is in the array and that its index value is 1.
But for some reason, this function only works correctly if I enter the very first element. This means that if I search for 1 in the array above, it will tell me that the index value is 0 like it's supposed to, but it won't do that for other elements.
My code is below. What am I doing wrong here?
#include <iostream>
using namespace std;
const int DECLARED_SIZE = 20;
void fillArray(int a[], int size, int& numberUsed);
int search(const int a[], int numberUsed, int target);
int search2(const int a[], int numberUsed, int target);
int main() {
int size;
cout << "Enter the array size: ";
cin >> size;
int arr[size], listSize, target;
fillArray(arr, size, listSize);
char ans;
int result;
do {
cout << "Enter a number to search for: ";
cin >> target;
cout << endl << endl;
result = search(arr, size, target);
if (result == -1) {
cout << target << " is not on the list." << endl << endl;
cout << "Search again? (y/n): ";
cin >> ans;
cout << endl << endl;
}
else {
cout << target << " is stored in array position " << result << "." << endl << endl;
cout << "Search again? (y/n): ";
cin >> ans;
cout << endl << endl;
}
} while ((ans != 'n') && (ans != 'N'));
cout << "End of program." << endl;
return 0;
}
void fillArray(int a[], int size, int& numberUsed) {
cout << "Enter up to " << size << " non-negative whole numbers." << endl;
cout << "Mark the end of the list with a negative number." << endl;
int next, index = 0;
cin >> next;
while ((next >= 0) && (index < size)) {
a[index] = next;
index++;
cin >> next;
}
numberUsed = index;
}
//searches an array that is filled by the user
//this is where i think i am struggling
int search(const int a[], int numberUsed, int target) {
int index = 0;
bool found = false;
while ((!found) && (index < numberUsed)) {
if (target == a[index]) {
found = true;
}
else {
index++;
}
if (found) {
return index;
}
else {
return -1;
}
}
return 0;
}
If you look at your search function you will see that it always returns at the bottom of the while loop. That's why you only find the first number. What you should do is return if you find the number but carry on if you don't. Like this (with some other simplifications of your code)
int search(const int a[], int numberUsed, int target) {
for (int index = 0; index < numberUsed; index++) {
if (target == a[index]) {
return index;
}
}
return -1;
}
In your while loop in your search function, you're doing:
if (found) {
return index;
} else {
return -1;
}
Which means if you didn't find your input, it immediately returns -1 instead of trying the next index. You should only return when you've visited all other indexes.
Related
Let's say I enter {1,3,3,5} as my array and I input 6 when asked to enter the key whose index I want to know. How do I edit my code to print that "the key entered is not in your array"?
My code is given below:
#include <iostream>
using namespace std;
void linearsearch(int arr[], int n, int key) {
int i;
for (i = 0; i < n; i++) {
if (arr[i] == key) {
cout << " \nthe index is: " << i;
}
}
}
int main() {
int n;
cout << "enter the size of your array : ";
cin >> n;
int arr[n];
cout << "\nenter the keys of your array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int key;
cout << "\n enter the key whose index you want to know: ";
cin >> key;
linearsearch(arr, n, key);
}
// You can use a boolean control variable in the void function and when you find the number you can set its value to true and insert an if statement at the end of the loop to check the value of the bool variable, if the, if statement in the loop wasn't executed, meant that the number was not found and the value of the variable was false so it would print the line you were asking about //
#include <iostream>
using namespace std;
void linearsearch(int arr[], int n, int key) {
int i;
bool found = false;
for (i = 0; i < n; i++) {
if (arr[i] == key) {
cout << " \nthe index is: " << i;
found = true;
}
}
if (found == false){
cout << "The key entered is not in your array." << endl;
}
}
int main() {
int n;
cout << "enter the size of your array : ";
cin >> n;
int arr[n];
cout << "\nenter the keys of your array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int key;
cout << "\n enter the key whose index you want to know: ";
cin >> key;
linearsearch(arr, n, key);
}
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;
}
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.
was looking over this program and im trying to figure out how to search for letters in an array instead of numbers, it works for numbers but how can i make it work for letters. please help............... here is the code
#include <iostream>
using namespace std;
const int DECLARED_SIZE = 4;
void fillArray(int a[], int size, string& letter);
int search(const int a[], string letter, string target);
int main( )
{
int arr[DECLARED_SIZE]; string listletter; string target;
fillArray(arr, DECLARED_SIZE, listletter);
char ans;
int result;
do
{
cout << "Enter a letter to search for: ";
cin >> target;
result = search(arr, listletter, target);
if (result == -1)
cout << target << " is not on the list.\n";
else
cout << target << " is stored in array position "
<< result << endl
<< "(Remember: The first position is 0.)\n";
cout << "Search again?(y/n followed by Return): ";
cin >> ans;
} while ((ans != 'n') && (ans != 'N'));
cout << "End of program.\n";
return 0;
}
void fillArray(int a[], int size, string& letter)
{
cout << "Enter up to " << size << " letter.\n"
<< "Mark the end of the list with a negative number.\n";
int next, index = 0;
cin >> next;
while ((next >= 0) && (index < size))
{
a[index] = next;
index++;
cin >> next;
}
}
int search(const int a[], string numberUsed, string target)
{
int index = 0;
string run = "run";
bool found = false;
while ((!found)) // && (index < numberUsed))
if (target == run)
found = true;
else
index++;
if (found)
return index;
else
return -1;
}
I noticed you're loading an int in fillArray. You need to use char if you want character input.
void fillArray(int a[], int size, string& letter)
{
cout << "Enter up to " << size << " letter.\n"
<< "Mark the end of the list with a negative number.\n";
char next;
int index = 0;
cin >> next;
while ((next >= 0) && (index < size))
{
a[index] = next;
index++;
cin >> next;
}
}