Write a C program to print the first and last element of an array.
#include <stdio.h>
#define MAXLIMIT 256
int main() {
int i, n, array[MAXLIMIT];
/* get the number of elements in the input array */
printf("Number of elements in your input array:");
scanf("%d", &n);
/* boundary check to avoid stack overrun */
if (n > MAXLIMIT || n < 0) {
printf("Boundary Exceeded!!\n");
return 0;
}
/* get the input elements from the user */
for (i = 0; i < n; i++) {
printf("Array[%d]: ", i);
scanf("%d", &array[i]);
}
/* printing the contents of the input array */
printf("\nContents of the input array:\n{");
for (i = 0; i < n; i++) {
printf("%d, ", array[i]);
}
printf("\b\b}\n");
/* printing first and last element in the given array */
printf("\nFirst Element of the given array: %d\n", array[0]);
printf("Last Element of the given array:%d\n", array[n -1]);
return 0;
}
#define MAXLIMIT 256
int main() {
int i, n, array[MAXLIMIT];
/* get the number of elements in the input array */
printf("Number of elements in your input array:");
scanf("%d", &n);
/* boundary check to avoid stack overrun */
if (n > MAXLIMIT || n < 0) {
printf("Boundary Exceeded!!\n");
return 0;
}
/* get the input elements from the user */
for (i = 0; i < n; i++) {
printf("Array[%d]: ", i);
scanf("%d", &array[i]);
}
/* printing the contents of the input array */
printf("\nContents of the input array:\n{");
for (i = 0; i < n; i++) {
printf("%d, ", array[i]);
}
printf("\b\b}\n");
/* printing first and last element in the given array */
printf("\nFirst Element of the given array: %d\n", array[0]);
printf("Last Element of the given array:%d\n", array[n -1]);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Number of elements in your input array:4
Array[0]: 10
Array[1]: 20
Array[2]: 30
Array[3]: 40
Contents of the input array:
{10, 20, 30, 40}
First Element of the given array: 10
Last Element of the given array:40
Number of elements in your input array:4
Array[0]: 10
Array[1]: 20
Array[2]: 30
Array[3]: 40
Contents of the input array:
{10, 20, 30, 40}
First Element of the given array: 10
Last Element of the given array:40
No comments:
Post a Comment