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

So do you want to put in, for example, "3 2" and have it find the second occurrence of the value "3"?

@OP

How about this:

cin >> num;
cin >> occuranceValue;

for (int index = 0, count = 0; count < occuranceValue; index++) {
        if (arr[index] == num)
            count++;
}

return index; // shows the index in the array where the nth occurance of num is present.

Edited 6 Years Ago by myk45: n/a

it is gives me always a zero

#include<iostream>

using namespace std;

int last(int arr[] , int ssize , int key ,int val)
{
int i ;
for ( i=0 ; i<=ssize ;i++ )
{ 
for (int count =0 ;count<val ;count ++)
{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;
}

plz help , whats wrong in the code ??

plz help , whats wrong in the code ??

Here's what I see wrong:
1) Bad formatting, making the code hard to follow (see this)
2) Using system("pause"); (see this)
3) Incrementing the FOR loop counter within the FOR loop.

The first two are not quite what you were looking for, but they are what you asked for.

using the system pause is necessary for me because i use the dev c++
and where shall i increment the for loop counter ??

now i modified it but it still views the first occurence

#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)            



return i ; 
} 
}
return -1 ;
}

int main()
{
	
	int arr[]={1,2,4,76,4,7,2,1,7,4};
	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;
}

@OP

int last(int arr[] , int ssize , int key ,int val)
{

 int ans = -1;

 for (int i = 0, count = 0; count < val; i++) {
	if (i == ssize)
		break;

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

You were returning on the first occurance.

This article has been dead for over six months. Start a new discussion instead.