sequential search problem

hello
i wanted to ask how to create a function that makes the insertion code search for an occurence that i will insert with a cin , instead of picking the first occurence
for example the array is arr[]={1,2,3,5,3,1,3}
there are 3 threes here , i want to get the index for the one i want using a cin , plz help me
i tried this code , but it always displays zero
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
32
33
34
35
36
37
38
#include<iostream>

using namespace std;

int last(int arr[] , int ssize , int key ,int val)
{
int i ;
 for (int i = 0, count = 0; count< val; i++) {

{if (arr[i] == key)            
count++;
}

return i ; 
} 
return -1 ;
}

int main()
{
	
	int arr[]={1,2,4,76,4,7,2,1,7,9};
	int val;
		int k;
	for(int i=0;i<10;i++)
	{cout<<arr[i]<<endl;
}
cout<<"enter key"<<endl;
cin>>k;
cout<<"enter val"<<endl;
cin>>val;
	int ret=last(arr,10,k,val);
		if (ret==-1)
			cout<<"not found"<<endl;
		else cout<<ret<<endl;
system("pause");
return 0;
}
Last edited on
put the return i in your last() in your if statement-- at the moment it reads the if and returns 0 the first time through
Last edited on
i put it in the statement but it didn't work
did i put it in the righ way ??

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
32
33
34
35
36
37
38
39
 #include<iostream>

using namespace std;

int last(int arr[] , int ssize , int key ,int val)
{
int i ;
 for (int i = 0, count = 0; count< val; i++) {

{if (arr[i] == key)            
count++;
return i ;
}

 return -1 ;
} 
}

int main()
{
	
	int arr[]={1,2,4,76,4,7,2,1,7,9};
	int val;
		int k;
	for(int i=0;i<10;i++)
	{cout<<arr[i]<<endl;
}
cout<<"enter key"<<endl;
cin>>k;
cout<<"enter val"<<endl;
cin>>val;
	int ret=last(arr,10,k,val);
		if (ret==-1)
			cout<<"not found"<<endl;
		else cout<<ret<<endl;
system("pause");
return 0;
}
 
Last edited on
try this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int last(int arr[] , int ssize , int key ,int val)
{
int i ;
 for (int i = 0, count = 0; count< val; i++) {

if (arr[i] == key){            
count++;}

if(count == val){
return i ;}


 }
 return -1 ;

}

Last edited on
thx guyz the problem was solved
Topic archived. No new replies allowed.