Java Program to Print the kth Element in the Array
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
// 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 access 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 ]); } } } |
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