Linear Search

#include <iostream>

using namespace std;

int search() {
int i, num;
int a[] = {12, 18, 95, 3, 16, 1, 16, 25, 30, 45, 19, 89, 99, 32};
cin >> num;
for (i = 0; i < 14; i++) {
if (num == a[i])
cout << "The number was found in index: " << i << endl;
}
if (num != a[i])
return -1;
}

int main() {
search();
system("pause");
return 0;
}

I'm supposed to "return -1" as my output if the number was not found in any index. I'm getting exit code -10384893 or something like that... Any idea how to fix this?
There is some errors in your code. Firstly the if condition outside the loop does not make sense. Secondly you are accessing the wrong data in the conditional statement outside of the loop. Thirdly your function must return an integer value on all paths. Here is a better version of it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>

using namespace std;

int search()
{
     int num;
     int a[] = {12, 18, 95, 3, 16, 1, 16, 25, 30, 45, 19, 89, 99, 32};
     cin >> num;
     for (int i = 0; i < 14; i++)
    {
        if (num == a[i])
           return i;
     }
     return -1;
}

int main()
{
int num;
num = search()'
if(num != -1)
cout << "The number was found in index: " << num << endl;
else
cout << "The number was  not found." << endl;
system("pause");
return 0;
} 
Last edited on
So, the command prompt never actually outputs -1? I'm starting to understand the approach you took. It's interesting... Also, I took the second if statement out of the loop because it was outputting a sentence every time 'i' was incremented. When you say "Your function must return an integer value on all paths," does that mean within a loop, method, etc.? For example: My for loop has to return a value AND my method as a whole?
No it means all possible paths like your original function would return either -1 if the condition outside the loop is true. Or it would return no value at all if that condition is false. That is what I meant. What happens when the if condition does not execute and what is the function returning? This is the question.

Now your normal program has only one path but when you use a conditional statement you automatically come at break. Now you have two paths in which the program can go. The first is if the conditional statement is true. The second is if the conditional statement is false. Something like this. Now do you get what I meant by all paths?
Don't confuse the return value from a function with outputting something to the screen. It's two different things.

Functions are often used to do some calculation or to carry out some task. The return value is what you get back when calling the function. If you want to print this value you need to write the code to actually do so.
Got it! Thanks guys! It's an assignment due tonight for my Data Structures class, so I'm grateful that I was able to receive help and advice before I submit it. Much appreciated!
Topic archived. No new replies allowed.