Java - Find a Specific Number in Integer Array in Java.


IncludeHelp 07 August 2016

This code snippet will demonstrate you to declare array, read array elements and find any particular number from all array elements.

This program will read total number of elements and read N array elements. Then program will read a specific number to be found.

Program will check entered numbers with all elements of the array one by one (through loop from 0 n-1), if number found index will print.

Java Code Snippet - Find a Specific Number from Integer Array in Java

//Java - Find a Specific Number in Integer Array in Java.

import java.util.*;

public class FindNumberInArray
{
	  public static void main(String args[]){
		  int n,loop;
		  
		  Scanner SC=new Scanner(System.in);
		  System.out.print("Enter total number of elements: ");
		  n=SC.nextInt();
		  
		  //declare integer array with n elements
		  int arr[]=new int[n];
		  
		  //reading array elements
		  System.out.println("Enter array elements:");
		  for(loop=0; loop<n; loop++){
			  System.out.print("Enter element (" + (loop+1) +"): ");
			  arr[loop]=SC.nextInt();
		  }
		  
		  //read number to find in array
		  int num;
		  System.out.print("Enter number to search: ");
		  num=SC.nextInt();
		  
		  //find number in array
		  int index=-1;		  
		  for(loop=0;loop<n;loop++){
			  if(arr[loop]==num){
				  index=loop;
				  break;
			  }
		  }
		  
		  if(index==-1){
			  System.out.println("Sorry! " + num + " is not found in array.");
		  }
		  else{
			  System.out.println(num + " found at index " + index);
		  }
		  
		  SC.close();		  
	  }
}
    

    First Run:
    Enter total number of elements: 5
    Enter array elements:
    Enter element (1): 10
    Enter element (2): 20
    Enter element (3): 30
    Enter element (4): 40
    Enter element (5): 50
    Enter number to search: 30
    30 found at index 2

    Second Run:
    Enter total number of elements: 5
    Enter array elements:
    Enter element (1): 10
    Enter element (2): 20
    Enter element (3): 30
    Enter element (4): 40
    Enter element (5): 50
    Enter number to search: 100
    Sorry! 100 is not found in array.




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.