Write a C program to print the element at the given position in an array.
#include <stdio.h>
#define MAXLIMIT 256
int main() {
int i, n, pos, data[MAXLIMIT];
/* get the number of elements from the user */
printf("Number of elements:");
scanf("%d", &n);
/* boundary check */
if (n > MAXLIMIT || n < 0) {
printf("Boundary Limit Exceeded!!\n");
return 0;
}
/* get the elements in the input array */
printf("Enter elements of your array:\n");
for (i = 0; i < n; i++) {
printf("Data[%d]: ", i);
scanf("%d", &data[i]);
}
/* get the desired position */
printf("Enter your desired position:");
scanf("%d", &pos);
/* boundary check */
if (pos > n || pos < 1) {
printf("Wrong Position!!\n");
return 0;
}
/* printing the result */
printf("Element at the given position is %d\n", data[pos - 1]);
return 0;
}
#define MAXLIMIT 256
int main() {
int i, n, pos, data[MAXLIMIT];
/* get the number of elements from the user */
printf("Number of elements:");
scanf("%d", &n);
/* boundary check */
if (n > MAXLIMIT || n < 0) {
printf("Boundary Limit Exceeded!!\n");
return 0;
}
/* get the elements in the input array */
printf("Enter elements of your array:\n");
for (i = 0; i < n; i++) {
printf("Data[%d]: ", i);
scanf("%d", &data[i]);
}
/* get the desired position */
printf("Enter your desired position:");
scanf("%d", &pos);
/* boundary check */
if (pos > n || pos < 1) {
printf("Wrong Position!!\n");
return 0;
}
/* printing the result */
printf("Element at the given position is %d\n", data[pos - 1]);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Number of elements:5
Enter elements of your array:
Data[0]: 100
Data[1]: 200
Data[2]: 300
Data[3]: 400
Data[4]: 500
Enter your desired position:4
Element at the given position is 400
Number of elements:5
Enter elements of your array:
Data[0]: 100
Data[1]: 200
Data[2]: 300
Data[3]: 400
Data[4]: 500
Enter your desired position:4
Element at the given position is 400
No comments:
Post a Comment