Learning Arrays, How can I find the value of an array and its number position

Viewed 37

How can I find the value of an array and its number position using for Loop?

import java.util.Scanner;

public class prac{
    
        public static void main(String[] args) {
            
            int n, element, pos=0, i;
            Scanner sc = new Scanner(System.in);        
            System.out.println("Enter array size [1-100]: ");
            n = sc.nextInt();
            
            int[] a = new int[100];
            System.out.println("Enter array elements: ");
            for(i=0; i<n; i++) {
                a[i]=sc.nextInt();
            }
            
            System.out.println("Enter element to search: ");
            element=sc.nextInt();
             
            for (i=0; i<n; i++) { 
                if (a[i]==element) {
                    System.out.println(element+ " found at position "+ i+1);
                }
            }
            System.out.println(element+"not found");

When I run this it gives me this output:Enter array size [1-100]: 3 Enter array elements: 1 2 3 Enter element to search: 3 3 found at position 21

What kind of solution should I do to fix this?

1 Answers

First problem is:

In the print command, when you write i+1 it is string.

For example if i = 5, the output is 51, but you mean an integer.

Thus write (i+1), So:

System.out.println(element + " found at position "+ (i+1));

Second problem is that your second print command is out of for loop. so it run anyway. One of the solution is that you can use boolean variable.

Try this:

import java.util.Scanner;

public class prac {

    public static void main(String[] args) {
        int n, element, pos = 0, i;
        boolean flag = false;
        Scanner sc = new Scanner(System.in);        
        System.out.println("Enter array size [1-100]: ");
        n = sc.nextInt();

       int[] a = new int[n];
       System.out.println("Enter array elements: ");
       for(i = 0; i < n; i++) 
           a[i] = sc.nextInt();
       

       System.out.println("Enter element to search: ");
       element = sc.nextInt();

       for (i = 0; i < n; i++) {
           if (a[i] == element) {
               System.out.println(element + " found at position " + (i+1));
               flag = true;
           }
       }
       if(!flag) // flag == false
           System.out.println(element + "not found");
   }
}

Good luck.

Related