Answer to Question #337677 in Java | JSP | JSF for mjayyyyyyyyyyyyyyy

Question #337677

Write a program using one-dimensional array that searches a number if it is found on the list of the given 5 input numbers and locate its exact location in the list.





Sample input/output dialogue:





Enter a list of numbers: 5 4 8 2 6 Enter a number to be searched: 2 2found in location 4


1
Expert's answer
2022-05-05T09:33:19-0400
import java.util.Scanner;

public class Answer {
    static int find(int[] arr , int el) {
        for (int i = 0; i < arr.length; i++) {
            if (el == arr[i]) {
                return i;
            }
        }
        return -1;
    }
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int[] array = new int[5];
        System.out.println("Enter a list of numbers: ");
        for (int i = 0; i < array.length; i++) {
            array[i]  = scanner.nextInt();
        }
        System.out.println("Enter a number to be searched:  ");
        int el = scanner.nextInt();
        int ans = find(array, el);
        if (ans == -1) {
            System.out.println("Element not found");
        } else {
            System.out.println(el + " found in location " + (ans + 1));
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS