This blog is under construction

Monday 22 July 2013

C program to find the nth largest and smallest element using pointers

Write a C program to find the Nth largest and smallest element using pointers.


  #include <stdio.h>
  #include <stdlib.h>

  int main() {
        int i, j, n, *num, temp, large, small;

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

        /* dynamically allocate memory to store data */
        num = (int *)malloc(sizeof(int) * n);

        /* get the location of largest and smallest element */
        printf("Nth largest element:");
        scanf("%d", &large);

        printf("Nth smallest element:");
        scanf("%d", &small);

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

        /* get the input data from the user */
        printf("Enter your inputs:\n");
        for (i = 0; i < n; i++) {
                printf("Data[%d]: ", i);
                scanf("%d", (num + i));
        }

        /* sort the given data */
        for (i = 0; i < n - 1; i++) {
                temp = *(num + i);
                for (j = i + 1; j < n; j++) {
                        if (temp > *(num + j)) {
                                temp = *(num + j);
                                *(num + j) = *(num + i);
                                *(num + i) = temp;
                        }
                }
        }

        /* print the nth largest and mth smallest data */
        printf("%d largest element is %d\n", large, *(num + n - large));
        printf("%d smallest element is %d\n", small, *(num + small - 1));

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of elements:4
  Nth largest element:2
  Nth smallest element:1
  Enter your inputs:
  Data[0]: 200
  Data[1]: 100
  Data[2]: 400
  Data[3]: 300
  2 largest element is 300
  1 smallest element is 100


No comments:

Post a Comment