w3resource logo


C Programming Exercises

C Exercises: Sort the elements of an array

Secondary Nav

C Variable Type : Exercise-6 with Solution

Write a C program to sort the elements of an array.

Expected Output :

Input the number of elements to be stored in the array :5               
Input 6 elements in the array :                                         
element - 0 : 15                                                        
element - 1 : 26                                                        
element - 2 : 42                                                        
element - 3 : 82                                                        
element - 4 : 35                                                        
                                                                        
After sorting the array are :                                           
15                                                                      
26                                                                      
35                                                                      
42                                                                      
82             

C Code:

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

	int comparetor (const void * x, const void * y)
	{
		return ( *(int*)x - *(int*)y );
	}
	int main ()
	{
	int my_array[100];
	int n,i;
       printf("\nInput the number of elements to be stored in the array :");
       scanf("%d",&n);
       printf("Input %d elements in the array :\n",n+1);
       for(i=0;i<n;i++)
        {
	      printf("element - %d : ",i);
	      scanf("%d",&my_array[i]);
	    }		
		qsort (my_array, n, sizeof(int), comparetor );
       printf("\nAfter sorting the array are :\n");
		for (i=0; i<n; i++)
			printf ("%d \n",my_array[i]);
		return 0;
	}

Solution

#include<stdio.h>
#include<stdlib.h>
	int comparetor (const void * x, const void * y)
	{
		return ( *(int*)x - *(int*)y );
	}

	int main ()
	{
	int my_array[100];
	int n,i;
       printf("\nInput the number of elements to be stored in the array :");
       scanf("%d",&n);
       printf("Input %d elements in the array :\n",n+1);
       for(i=0;i<n;i++)
        {
	      printf("element - %d : ",i);
	      scanf("%d",&my_array[i]);
	    }		
		qsort (my_array, n, sizeof(int), comparetor );
       printf("\nAfter sorting the array are :\n");
		for (i=0; i<n; i++)
			printf ("%d \n",my_array[i]);
		return 0;
	}

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program