Quick Array Problem

New to using arrays, and C++ all together for that matter but heres my problem.

I've created a program that asks the user to give 20 numbers then to search for a specific number within that array. I have a very good idea as to where i've gone wrong but am clueless on what I need to change it to, heres my code.

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
#include <iostream>
using namespace std;

int main()
	{
		int key, i, j, array[20];

			for(int i=0; i<20; i++)
				{
				cout << "Enter number: ";
				cin >> array[i];
				}
		cout << "Enter a number to look for in your array" << endl;
				cin >> key;
					for(int j = 0; j < 20; j++)
					{   //I believe I've went wrong here.
						if(array[j] == key)
						{
						cout << "The number " << key << " was found in the array" << endl;
						}
						else
						{
						cout << key << " was not found in the array" << endl;
						return 0;
						}
					}
}


the output constantly states that the number wasn't found in the array.
Last edited on
Fixed my own problem. I set a flag.. works great now! Not sure why I didn't think of it before!
In C++, you normally declare variables where you first need them. Declareing i and j in the first line in your code is redundant. I suggest you use a named constant for the 20 value.

You can also replace your manual search loop with the standard library find function, like this:
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
#include <iostream>
using namespace std;

const int SIZE = 20;

int main()
{
    int key, array[SIZE];
    
    for(int i=0; i<SIZE; i++)
    {
        cout << "Enter number: ";
        cin >> array[i];
    }
    cout << "Enter a number to look for in your array" << endl;
    cin >> key;
    
    if(find(array, array+SIZE, key) != array+SIZE)
    {
        cout << "The number " << key << " was found in the array" << endl;
    }
    else
    {
        cout << key << " was not found in the array" << endl;
    }
}


You might also replace the array with a vector, like this:
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 <vector>
#include <iostream>
using namespace std;

const int SIZE = 20;

int main()
{
    int key;
    vector<int> vec(SIZE);
    
    for(int i=0; i<SIZE; i++)
    {
        cout << "Enter number: ";
        cin >> vec[i];
    }
    cout << "Enter a number to look for in your array" << endl;
    cin >> key;
    
    if(find(vec.begin(), vec.end(), key) != vec.end())
    {
        cout << "The number " << key << " was found in the array" << endl;
    }
    else
    {
        cout << key << " was not found in the array" << endl;
    }
}


Of course, with vector you probably want to let the user decide how many number to put in, and use push_back instead of cin >> vec[i]. If you want to ignore duplicates, you might want set instead of vector...
Last edited on
Topic archived. No new replies allowed.