Linear Search

Hello
my problem with this code is that instead of
showing "element not found" it show n+1th position
which is element out of array

Please help where am i struck?
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
29
30
31
#pragma GCC diagnostic ignored "-fpermissive"
#include <iostream>
using namespace std;
int main()
{
	int a[256];
	int n, num;
	cout << "Enter the total number of values in array : " << endl;
	cin >> n;
	//get the values
	for(int i = 0; i <= n; i++)
	{
		cout << "Enter the number : " << endl;
		cin >> a[i];
	}
	//now to search the number
	cout << "Enter the number to be Searched : " << endl;
	cin >> num;
	//search loop
	for(int i = 0; i < n; i++)
	{
		if(a[i] == num)
		break;
	}
	
	if(i == n)
		cout << "Number not found..." << endl;
	else
		cout << "Number is at : " << i + 1 << " Position." << endl;
	return 0;
}
This:
 
if(i == n)

should be:
 
if(a[i] == n)
Code you posted should not compile: all i variables are destroyed (on lines 15 and 24) when program reaches line 26.

Post code where you actually have problem with output and not compilation.
@kbw
Thanks really really thanks
Yes I overlooked this small mistake and bloody whole program suffered due to that..... Thanks so much
Last edited on
Topic archived. No new replies allowed.