« First Index of Number in the array.
Problem
First Index of Number in array
Given an array of length N and an integer x, you need to find and return the first index of integer x present in the array. Return -1 if it is not present in the array. First index means, the index of first occurrence of x in the input array. Do this recursively. Indexing in the array starts from 0.
Input Format :
Line 1 : An Integer N i.e. size of array
Line 2 : N integers which are elements of the array, separated by spaces
Line 3 : Integer x
Output Format :
first index or -1
Constraints :
1 <= N <= 10^3
Sample Input :
4
9 8 10 8
8
Sample Output :
1
Solution
1#include <iostream>2#include <iomanip>3#include <algorithm>4#include <string>5#include <cstring>6#include <vector>7#include <cmath>8#include <map>9#include <climits>10// climits for INT_MIN11#include <unordered_map>12using namespace std;1314int firstIndex(int input[], int size, int x)15{16 if (input[0] == x)17 {18 return 0;19 }2021 if (size == 1)22 {23 return -1;24 }25 else26 {27 int an = firstIndex(input + 1, size - 1, x);28 if (an >= 0)29 {30 return an + 1;31 }32 else33 {34 return an;35 }36 }37}38int main()39{40 int n;41 cin >> n;4243 int *input = new int[n];4445 for (int i = 0; i < n; i++)46 {47 cin >> input[i];48 }4950 int x;5152 cin >> x;5354 cout << firstIndex(input, n, x) << endl;5556 return 0;57}