Write a C program to print the Kth element in an array using a for loop.
#include <stdio.h> int main() { int Size, i, k; printf("Please Enter the Array size = "); scanf("%d", &Size); int arr[Size]; printf("Enter the Array %d elements : ", Size); for (i = 0; i < Size; i++) { scanf("%d", &arr[i]); } printf("Enter Kth Position Array Item to Check = "); scanf("%d", &k); printf("Kth Element (%d) in this Array = %d \n", k, arr[k - 1]); }
This C program uses a while loop and prints the Kth element in the given array. In this C example, we used an extra if else to check whether the Kth element is within the array size.
#include <stdio.h> int main() { int Size, i, k; printf("Please Enter the Array size = "); scanf("%d", &Size); int arr[Size]; printf("Enter the Array %d elements : ", Size); for (i = 0; i < Size; i++) { scanf("%d", &arr[i]); } printf("Enter Kth Position Array Item to Check = "); scanf("%d", &k); if(k <= Size) { printf("Kth Element (%d) in this Array = %d \n", k, arr[k - 1]); } else { printf("The Kth Element is Out of this Array Range\n"); } }
Please Enter the Array size = 7
Enter the Array 7 elements : 22 9 11 44 99 12 87
Enter Kth Position Array Item to Check = 5
Kth Element (5) in this Array = 99
Please Enter the Array size = 3
Enter the Array 3 elements : 10 20 30
Enter Kth Position Array Item to Check = 5
The Kth Element is Out of this Array Range