Monday 28 August 2017

Java Code to find the position of a number in an array

Problem:

Find the position of a number in an array of n elements.

Solution:

package array.programs;

import java.util.Scanner;

public class PositionOfANumber {

int[] numbers;
int n;
int input;

public static void main(String[] args) {
PositionOfANumber positionOfANumber = new PositionOfANumber();
positionOfANumber.initializeTheArray();
System.out.println("the array elements are: ");
positionOfANumber.printArray();
System.out.println();
positionOfANumber.findPositionOfANumber();

}

public void initializeTheArray(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter n value");
n = scanner.nextInt();
numbers = new int[n];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = i + 1;
}
System.out.println("enter the number which you want to find position");
input = scanner.nextInt();
scanner.close();
}

public void printArray(){
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
}

public void findPositionOfANumber(){
int position = -1;
for (int i = 0; i < numbers.length; i++) {
if(numbers[i] == input){
position = i + 1;
break;
}
}
if(position == -1){
System.out.println("the given number is not in an array");
}
else{
System.out.println("the position of given number is" + position);
}
}

}



Output:

enter n value
12
enter the number which you want to find position
8
the array elements are:
1 2 3 4 5 6 7 8 9 10 11 12
the position of given number is8

enter n value
20
enter the number which you want to find position
21
the array elements are:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
the given number is not in an array





No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...