Monday, April 14, 2014

Sorting array elements in ascending order


Let us today help you with the code to sort an array of elements elements provided by the user in ascending order. The code is given below step by step for your better understanding.

Step 1:

   #include<stdio.h>
   #include<conio.h>

   void main()
   {
      clrscr();


      getch();
   }

This step is nothing but defining the basic C programming syntax.

Step 2:

   int arr[5],temp,i,j;

In this step we declared 2 variables( variables should be declared above clrscr() ), first is an array of size 5 which will be used to store user inputs and an "temp" variable that we will use to temporarily store value, you can name it anything you like.

Step 3:

   printf("Enter any 5 numbers\n");

   for(i=0;i<5;i++)
   {
      scanf("%d",&arr[i]);
   }

In Step 3 we have written the code to accept 5 integer values from users.

Step 4:

   for(i=0;i<5;i++)
   {
        for(j=i+1;j<5;j++)
        {
            if(arr[i]>arr[j])
            {
                 temp=i;
                 i=j;
                 j=temp;
            }
        }
   }

This is the main step as it does all the sorting of array elements in ascending order entered by the user.

Step 5:

   printf("Your numbers have been sorted in ascending order\n\n");  

   for(i=0;i<5;i++)
   {
        printf("%d\n",arr[i]);
   }

This is the final step which display the array values which has been sorted.
Yes that's it, we hope that you liked our post if you did link our post with your social networks and do comment.

Happy Programming !

3 comments :

  1. why do we have to declare a int temp? what is it use for?

    ReplyDelete
    Replies
    1. "temp" is just a name it can be anything, this will be used to hold the value of the variable which is being replaced with new value so that this value in temp can be re-assigned to the next variable

      Delete
  2. This comment has been removed by the author.

    ReplyDelete