This blog is under construction

Thursday 25 July 2013

C program to find the minimum and maximum element in an array

Write a C program to find the smallest and largest element in an array.


  #include <stdio.h>
  #define MAX 256

  int main() {
        int min, max, i, n, array[MAX];

        /* get the number of elements from the user */
        printf("Enter the number of elements in i/p array:");
        scanf("%d", &n);

        /* boundary check */
        if (n < 0 || n > MAX) {
                printf("Boundary Level Exceeded!!\n");
                return 0;
        }

        /* get the array entries from the user */
        printf("Enter the array entries:\n");
        for (i = 0; i < n; i++) {
                printf("Array[%d]: ", i);
                scanf("%d", &array[i]);
        }

        min = max = array[0];

        /* find the minimum and maximum element in input array */
        for (i = 0; i < n; i++) {
                if (min > array[i]) {
                        min = array[i];
                }

                if (max < array[i]) {
                        max = array[i];
                }
        }

        /* print the result */
        printf("Minimum element in the given array: %d\n", min);
        printf("Maximum element in the given array: %d\n", max);

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of elements in i/p array:5
  Enter the array entries:
  Array[0]: 30
  Array[1]: 10
  Array[2]: 20
  Array[3]: 40
  Array[4]: 25
  Minimum element in the given array: 10
  Maximum element in the given array: 40


No comments:

Post a Comment