C++ Program To Find First And Last Occurrence Of Key In An Array

c++, array, array example, c++ problem, c++ program for practice

 

Iterative Method

Program:

#include <iostream>
using namespace std;

int firstocc(int arr[],int n,int key)   //getting the index of first occurrence
{
    for(int i = 0; i < n; i++)
    {
        if(arr[i] == key)
        return i;
    }
    return -1;
}

int lastocc(int arr[],int n,int key)    //getting the index of last occurrence
{
    for(int i = n-1; i >= 0; i--)
    {
        if(arr[i] == key)
        return i;
    }
    return -1;
}

int main()
{
    int arr[] = {1,2,3,2,3,5,2,6};
    int n = sizeof(arr)/sizeof(arr[0]);

    cout << "First Occurrence is at: " << firstocc(arr,n,2) << endl;
    cout << "Last Occurrence is at: " << lastocc(arr,n,2) << endl;

    return 0;
}

Output:

First Occurrence is at: 1
Last Occurrence is at: 6

Recursive Method

Program:

#include <iostream>

using namespace std;

int firstocc(int a[],int n,int i,int key)
{
    
    if(i == n)	//when entire array is searched but key is not found then 
    return -1;	//return -1
    
    if(a[i] == key)	//when key is found first time return its index
    return i;
    
    return firstocc(a,n,i+1,key);	//recursive call the function until key is not found
}

int lastocc(int a[],int n,int i,int key)
{
    if(i == n)
    return -1;
    
    int restarray=lastocc(a,n,i+1,key);
    
    if(restarray != -1)
    return restarray;
    
    if(a[i] == key)	//check array elements from stack
    return i;		//and when key is found return its index
    
    return -1;		//if not found return -1
}

int main()
{
    int a[7]={1,2,3,2,5,2,6};
    
    cout << "First Occurrence is at: " << firstocc(a,7,0,2) << endl;
    cout << "Last Occurrence is at: " << lastocc(a,7,0,2) << endl;

    return 0;
}

Output:

First Occurrence is at: 1
Last Occurrence is at: 5
C++ Program To Find First And Last Occurrence Of Key In An Array C++ Program To Find First And Last Occurrence Of Key In An Array Reviewed by Beast Coder on April 16, 2021 Rating: 5

No comments:

Powered by Blogger.