Skip to content
Related Articles

Related Articles

Java Program to Print the kth Element in the Array
  • Difficulty Level : Basic
  • Last Updated : 17 Dec, 2020

We need to print the element at the kth position in the given array. So we start the program by taking input from the user about the size of an array and then all the elements of that array. Now by entering the position k at which you want to print the element from the array, the program will print the element at the k-1 position in the array.

Note: The indexes of elements in a Java array always start with 0 and continue to the number 1 below the size of the array. Thus, for an array having 10 elements, the indexes will be from 0 to 9.

Examples

Input: 5 (size of an array)
       1, 2, 3, 4, 5 (array elements)
       3 (position k)
Output: 3

Input: 5
       5, 3, 7, 1, 9
       3
Output: 7

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to Print the kth Element in the Array
  
import java.io.*;
import java.util.Scanner;
  
class GFG {
    public static void main(String[] args)
    {
        {
            int n;
  
            // scanner object to acces user input
            Scanner s = new Scanner(System.in);
            System.out.print(
                "Enter number of elements you want in array:");
  
            // storing input in variable
            n = s.nextInt();
  
            // create int array
            int a[] = new int[n];
            System.out.println("Enter all the elements:");
  
            // iterating for loop to enter the values in the
            // array
            for (int i = 0; i < n; i++) {
                a[i] = s.nextInt();
            }
  
            System.out.print(
                "Enter the k th position at which you want to check number:");
            int k = s.nextInt();
            System.out.println("Number is :" + a[k - 1]);
        }
    }
}

chevron_right


Output

Enter number of elements you want in array: 5
Enter all the elements: 
5
3
7
1
9
Enter the k th position at which you want to check number: 3
Number is : 7

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :