Write a program which accept 5 integer value from user and display in ascending and descending order.

0 votes
asked Sep 6, 2018 by anonymous

2 Answers

0 votes
answered Sep 6, 2018 by Rithik Raj (220 points)

void swap(int *xp, int *yp)

{

    int temp = *xp;

    *xp = *yp;

    *yp = temp;

}

void bubbleSort(int arr[], int n)

{

   int i, j;

   for (i = 0; i < n-1; i++)     

       

       for (j = 0; j < n-i-1; j++)

           if (arr[j] > arr[j+1])

              swap(&arr[j], &arr[j+1]);

}

void printArray(int arr[], int size)

{

    int i;

    for (i=0; i < size; i++)

        printf("%d ", arr[i]);

    printf("n");

}

int main()

{

    int arr[] = {64, 34, 25, 12, 22, 11, 90};

    int n = sizeof(arr)/sizeof(arr[0]);

    bubbleSort(arr, n);

    printf("Sorted array: \n");

    printArray(arr, n);

    return 0;

}

0 votes
answered Jan 25, 2019 by Jyothi_Rk
Hi,

This code accepts 5 integers, copies it to another array(because in the question, it is not mentioned to change the order of the array elements).later it sorts the temp array in ascending order & displays both in ascending and descending order.

#include <stdio.h>

void main()
{
    int arr[5],temp[5],i,min,j=0,index;
    printf("Enter 5 intergers\n");
    for(i=0;i<5;i++)
    {
        scanf("%d",&arr[i]);
    }
    for(i=0;i<5;i++)
    {
        temp[i]=arr[i];
    }
   
    while(j<5)
    {
        min=temp[j];
        for(i=j+1;i<5;i++)
        {
            if(temp[i]<min)
            {
                min=temp[i];
                index=i;
            }
        }
        if(temp[j] != min)
        {
            temp[j]=temp[j]+temp[index];
            temp[index]=temp[j]-temp[index];
            temp[j]=temp[j]-temp[index];
        }
        j++;
    }
    
    printf("Ascending order\n");
    for(i=0;i<5;i++)
          printf("%d\t",temp[i]);
          printf("\n");
    printf("Descending order\n");
    for(i=4;i>=0;i--)
          printf("%d\t",temp[i]);
}
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...