The goal is to write a function that searches an array for a value.
If the array contains the value, return the index where the key is located.If the array does not contain the value, return a -1
I have a c++ function that returns the index of an array variable. I need explanation on why my part of my code ( ie the 'i++' in the for loop expression) is tagged 'unreachable' by my IDE
I have tried debugging the code line by line to see if i can decipher why the i++ is unreachable. I am unable to identify why. However, I suspect it might have to do with my 'return' statement
int main()
{
const int size = 4;
int array[] = { 345, 75896, 2, 543 };
int searchKey = 543;
std::cout << "Found at: " << search(array, size, searchKey);
return 0;
}
int search(int* array, int size, int searchkey)
{
while (1) {
std::cout << "Enter an Integer to search. Hit -1 to quit.\n";
scanf("%d", &searchkey);
if (searchkey == -1) {
break;
}
for (int i = 0; i < size; i++) {
if (array[i] == searchkey) {
return 1;
}
else {
return -1;
}
}
}
}
I expect the function to return the index of the array if a searchKey exists in the array, but it always ends up returning '-1'
The for loop is not quite right. The function returns in the first iteration of the loop regardless of the value of the first item in the array. If the first item matches the search key, the function returns 1. If not, it returns -1. It never touches the second item in the array.
You need to remove the else part. Return -1 only after the loop ends.
for(int i=0; i<size; i++){
if(array[i] == searchkey){
// Key was found. Return the index.
return i;
}
}
// Key was not found.
return -1;
Your logic in code decide to return 1 or -1 in the very first time in for loop, so it never touch the i++.
You should only return -1 when loop ended (when search done)
for(int i=0; i<size; i++){
if(array[i] == searchkey){
// return the INDEX of array when found immediately
return i;
}
}
return -1;
Related
I thought to move the return -1 to outside the loop or by instead using an else block, but my apparently this is not possible. Why is this?
Here is the code:
int index_of(vector<string> &names, string name)
{
for (int i = 0; i < names.size(); i++)
{
if (to_lowercase(names[i]) == to_lowercase(name))
{
return i;
}
return -1;
}
}
The function has to guarantee a return value. In your code, your return -1; depends completely on whether or not names.size() is greater than 0. If names.size() is less than or equal to 0, the thread won't even enter the for loop, meaning that your function will return effectively nothing.
int search( int arr[], int size, int num) {
int i, loc;
loc=i;
for (i=0;i<size;i++){
if (arr[i]==num)
return loc;
else
return -1;
}
}
can someone tell me where did I go wrong?
There are several problems with the shown code as described below.
Problem 1
The variables i and loc are uninitialized and using those uninitialized variables(which you did when you wrote loc = i) is undefined behavior.
Problem 2
The logic that you've used for the for loop and also for the if else part is not correctly implemented. In particular, suppose the for loop is not entered due to the condition i<size being false, then no return statement will be encountered for your non-void returning function again leading to undefined behavior.
Solution
There is no need to create a variable named loc. You can just directly return i when the element is found. Moreover there is no need for the else block. If the element is not found while iterating through the elements, we just return -1 after the for loop.
int search( int arr[], int size, int num) {
for (int i=0; i < size; i++)
{
if (arr[i]==num)
return i;//value found so return i directly
}
return -1; //value was never found
}
int main()
{
int arr[] = {1,2,33,54,3};
std::cout<<search(arr, 5, 3)<<std::endl; //prints 4
std::cout<<search(arr, 5, 33)<<std::endl; //prints 2
std::cout<<search(arr, 5, 98)<<std::endl; //prints -1
}
Working demo.
Here is a solution that resolves the issues in your initial code. Let's break it down by commenting the code.
int search(int arr[], int size, int num) {
// Initialize `location` to a value, this is very important
// In this case, it's okay to initialize to the "not found"
// value and you can simply `return location` at the end of
// this function.
int location = -1;
for (int index = 0; index < size; index++) {
// Check to see if `arr[index] == num`
// If so, we found `num` in `arr` !
// Otherwise, let the loop continue
if (arr[index] == num) {
// Since we found `num` in `arr`, let's store the index
// by updating our location
location = index;
// We found the index we are looking for
// No need to continue the `for` loop
break;
}
// No need for an `else` here, as it was noted in comments that
// returning in the `else` block would exit your loop early
}
// Just return `location`. It either stores `-1` of the index of `num`
return location;
}
Take time to review your solution and compare it to this particular solution. The primary issues with your original code were
You didn't initialize the loc variable nor did you ever update it before returning. This results in Undefined Behavior.
You had an else statement that returned -1 inside your for loop, which resulted in the loop only ever iterating a single time
Note that there are several ways to write this function and I've just shown one approach. Consider how you could write something functionally equivalent using your own approach.
Also note that you could simplify this code to not use a location variable altogether, as in the answer provided by #AnoopRana. I've left the use of the location variable in my example since it seemed to be closer to what you were originally going for. This solution is verbose in an attempt to help you understand more thoroughly what the algorithm is doing.
#include <iostream>
int search(int arr[], int n , int element)
{
int i = 0;
while (i < n)
{
if (arr[i] == element) {
break;
}
i++;
}
if (i < n)
{
return i;
}
else {
return -1;
}
return 0;
}
int main()
{
int arr[] = { 1, 2, 33, 54, 98 };
int n = sizeof(arr)/sizeof(arr[0]);
int element;
std::cout<<"Enter element to search for ";
std::cin>>element;
std::cout<<search(arr,n,element);
}
here is the instructions for code I am trying to write:
Consider the testPIN function used in Program 7-21. For convenience, we have reproduced the code for you below. Modify this function as follows:
change its type to int
change its name to countMATCHES
make it return the number of corresponding parallel elements that are equal
I have this code here:
int countMatches(int custPIN[], int databasePIN[], int size) {
for (int index = 0; index < size; index++) {
if (custPIN[index] == databasePIN[index])
return index;
}
return size;
}
Where exactly am I failing to do? Is it that I am infinitely stuck in this loop or is it something else?
As per description your code should be like below :
int countMatches(int custPIN[], int databasePIN[], int size)
{
int counter =0;
for (int index = 0; index < size; index++) {
if (custPIN[index] == databasePIN[index])
counter++;
}
return counter;
}
Perhaps in the first line of the function you want to initialise a new counter variable to 0, and then, if the customer and database pins match, you increment it.
In the end, instead of returning the size, perhaps you want to return the counter, which now has been incremented for each matching character.
The problem is that your function trying return more than once. If condition is true then you will return index but also will trying to return the size (which is not possible) where if its false then it will only return size
Change the code as follows :
int countMatches(int custPIN[], int databasePIN[], int size) {
int e;
for (int index = 0; index < size; index++){
if (custPIN[index] == databasePIN[index]) {
e++;
}
}
if(e!=0)
return e;
}
Hope this will help you.
I have the following pseudocode which a sequential search pseudocode and I am trying to understand what return -1 mean. why would we return -1 could someone please explain.
A[n] <-- K
i <-- 0
while A[i] != K do
i = i + 1
if(i<n)
return i;
else
return -1; //What is this mean ?
Returning -1 is a way of conveying the fact that the code reached the end without returning in the middle. Returning -1 in this case means that the element K does not exist in the array.
Note that returning 0 is not used for this purpose as it could mean the element is present at the 0th index. If your function was something which could return -1 at some point in the middle, some other return value to indicate failure would have been chosen.
If you were to search a sequence for an element, and return the index of that element, you'd want some way to show that the element wasn't found. A negative value is an invalid index in many languages, so returning -1 could only mean the element couldn't be found for one reason or another.
int index_of(const int *array, int sz, int elem) {
for (int i = 0; i < sz; ++i) {
if (array[i] == elem) { // found the element
return i; // return the index of the element
}
}
return -1; // couldn't find it
}
Then in the calling code you might have
int calling() {
int array[N];
// populate array with data ...
int idx = index_of(array, N, 4); // find where 4 is in the array
if (idx < 0) {
// 4 isn't in the array
} else {
// 4 IS in the array !
}
}
I'm trying to make a program to solve the eight queens problem, however it keeps reaching the last return, when it should not, and tried putting it on an else, but then it never reached it, even if i initially give it an empty stack.
Also for whatever reasons the first time i call the top() function, it return a different element than the last i added, but if i call it again it return the correct element.
So i would like to know where the problem is?
bool search(stack<nodo>& board, int n) {
nodo queen;
queen=board.top();
queen=board.top();
if (queen.y == n)
return true;
bool valid;
if (!board.empty()) {
queen.y += 1;
for(int i; i<=n; i++) {
queen.x = i;
valid = isvalid(queen,board);
if (valid) {
board.push(queen);
search(board,n);
}
}
board.pop();
}
return false;
}
use while not if
while(!board.empty()) {
queen.y += 1;
for(int i; i<=n; i++){
queen.x = i;
valid = isvalid(queen,board);
if (valid) {
board.push(queen);
search(board,n);
}
}
board.pop();
}
if means check for one time only , but while mean do the samething till board.empty() == true.