C Program to Print the kth Element in the Array

«
»

This is a C program to print the kth element in the array.

Problem Description

This C Program implements an array prints the kth element in the array where the position k is entered by the user as an input.

Problem Solution

1. Create an array and taking its size from the users, define all its elements.
2. Take an input from users, the position in the array where we want to access element.
3. The element would be in the index (entered_position -1) of the array, print it.

advertisement
Program/Source Code

Here is source code of the C Program to print the kth element in the array. The program is successfully compiled and tested using Turbo C compiler in windows environment. The program output is also shown below.

  1.  
  2.     /*
  3.      * C Program to Print the kth Element in the Array
  4.      */
  5.  
  6.     #include <stdio.h>
  7.     int main()
  8.     {
  9.         int arr[100], len, i, j, temp, n;
  10.         printf("Enter the size of array");
  11.  
  12.         scanf("%d", &len);
  13.         printf("\n Enter the array elements");
  14.  
  15.         for (i = 0; i < len; i++) 
  16.         {
  17.             scanf("%d", &arr[i]);
  18.         }
  19.  
  20.         printf("\n Enter Which kth Number You want");
  21.         scanf("%d", &n);
  22.         printf("\n The %d th kth number is: %d", n, arr[n - 1]);
  23.         return 0;
  24.     }
Program Explanation

1. Declare an array of some fixed capacity, 100.
2. Take size from users as an input.
3. Using for loop, define the elements of the array according to the size.
4. Enter the position(i.e k) where we want to access the element.
5. The index of the array where we will find the required element according to the position entered is – (k-1).

advertisement
Runtime Test Cases
Enter the size of array4
 
Enter the array elements
12
13
17
20
Enter Which kth Number You want 4
 
The 4th kth number is: 20

Sanfoundry Global Education & Learning Series – 1000 C Programs.

Here’s the list of Best Reference Books in C Programming, Data Structures and Algorithms.

advertisement

advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn