Find First Index Of a Number in an Array – Coding Ninjas

First Index Of a Number in an Array

How do you find the first index of an 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.

The first index means, the index of the 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 :
9 8 10 8
Sample Output :

Solution in Java

//Main function

import java.util.Scanner;

public class Runner {
	static Scanner s = new Scanner(;
	public static int[] takeInput(){
		int size = s.nextInt();
		int[] input = new int[size];
		for(int i = 0; i < size; i++){
			input[i] = s.nextInt();
		return input;
	public static void main(String[] args) {
		int[] input = takeInput();
		int x = s.nextInt();
		System.out.println(Solution.firstIndex(input, x));

//Solution by

public class Solution {

	public static int firstIndex(int input[], int x) {
		return ans(input,x,0);
    public static int ans(int input[],int x,int startIndex)
      int n=input.length;
            return -1;
            return startIndex;
        return ans(input,x,startIndex+1);


Thank you for reading this article so far, if you know some other way to write this program then you can leave a comment here or mail us at, So anyone can a get chance to publish their code on our website. As a result, one can improve knowledge and spread it to others

Please check most asked programming questions of strings with examples by clicking here, after that you might get a deep knowledge about string operations, in short, it will be helpful in clearing the interview.

You can also check other coding problems solved from the coding ninja’s platform here.

Thanks for reading this article so far. If you like this article, then please share it with your friends and colleagues. If you have any questions or feedback, then please drop a note.

You can also follow us on Twitter for daily updates.

Leave a Reply

Your email address will not be published. Required fields are marked *