ChattTheDev
ChattTheDev

Reputation: 17

Array Program for Searching a Specific number in Array

I have just learned 1D Array in Java, and I wrote a code to take input from the user for a specific array length, and then print the users entered data. After that user writes a number to check if the number is present or not in the array.

I have the desired output, but in one place I couldn't understand the logic. Please guide me.

Here is the program:

    //Program to get value from user using array and print all the values

import java.util.Scanner;
class Array{
public static void main(String args[]){

int[] a = new int[5];
System.out.println("Enter 5 Numbers to Store in a Array");
for(int i = 0; i<a.length; i++){
Scanner in = new Scanner(System.in);
a[i] = in.nextInt();
}

System.out.println("Numbers you Entered are:\n");
for(int i = 0; i<a.length; i++){
System.out.println(a[i]);
}

System.out.println("Check if the number is present in the array or not:");
Scanner ing = new Scanner(System.in);
int input = ing.nextInt();

**if(input == a[4]**){
System.out.println("Number is found");
}
else{
System.out.println("Not Found");
}

}
}

and the output:

    Enter 5 Numbers to Store in an Array
56
45
78
79
80
Numbers you Entered are:

56
45
78
79
80
Check if the number is present in the array or not:
80
Number is found

I want to know why the number is found in the array size is a[4], because I have the array size a[5].

Upvotes: 0

Views: 65

Answers (1)

Ananth.P
Ananth.P

Reputation: 445

Since arrays are Zero based indexing,so the position which you have found for value 80 is 4

Please refer this [https://softwareengineering.stackexchange.com/questions/110804/why-are-zero-based-arrays-the-norm]

Upvotes: 2

Related Questions