This blog is under construction

Saturday 6 July 2013

C program to sort numbers in descending order using functions

Write a C program to sort numbers in descending order using functions.


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

  /* sorts the input in decending order */
  void decendingOrder(int input[], int num) {
        int i, j, temp;
        for (i = 0; i < num - 1; i++) {
                temp = input[i];
                for (j = i + 1; j < num; j++) {
                        /* swapping small and big */
                        if (temp < input[j]) {
                                temp = input[j];
                                input[j] = input[i];
                                input[i] = temp;
                        }
                }
        }
        return;
  }

  int main() {
        int n, *input, i;
        /* get the number of inputs from the user  */
        printf("Enter the number of inputs:");
        scanf("%d", &n);

        /* allocate memory to hold n elements */
        input = (int *) malloc(sizeof(int) * n);

        /* get n inputs from the user */
        for (i = 0; i < n; i++) {
                printf("input[%d]:", i);
                scanf("%d", &input[i]);
        }
        /* sort the input in decending order */
        decendingOrder(input, n);

        /* print the results after sorting */
        printf("\nAfter sorting:\n");
        for (i = 0; i < n; i++) {
                printf("%d  ", input[i]);
        }
        printf("\n");
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of inputs:5
  input[0]:10
  input[1]:20
  input[2]:15
  input[3]:25
  input[4]:23

  After sorting:
  25  23  20  15  10  



No comments:

Post a Comment