Q:

program to sort array elements in ascending order

0

program to sort array elements in ascending order

In this program, we are reading an array of integers and sorting array elements in ascending order.

Example:

    Input array elements are:
    50, 10, 20, 40, 30

    Output:
    Sorted array elements are:
    10, 20, 30, 40, 50

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

/*program to sort array elements in ascending order. */
#include <stdio.h>

/** funtion :   readArray() 
    input   :   arr ( array of integer ), size 
    to read ONE-D integer array from standard input device (keyboard). 
**/
void readArray(int arr[], int size)
{
    int i = 0;

    printf("\nEnter elements : \n");

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

/** funtion :   printArray() 
    input   :   arr ( array of integer ), size 
    to display ONE-D integer array on standard output device (moniter). 
**/
void printArray(int arr[], int size)
{
    int i = 0;

    printf("\nElements are : ");

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

void sortArray(int arr[], int size)
{
    int i = 0, j = 0, temp;

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

int main()
{
    int arr[5];

    readArray(arr, 5);

    printf("\nBefore Sorting");
    printArray(arr, 5);

    sortArray(arr, 5);

    printf("\nAfter Sorting");
    printArray(arr, 5);

    return 0;
}

Output:

Enter elements : 
Enter arr[0] : 12 
Enter arr[1] : 10 
Enter arr[2] : 67 
Enter arr[3] : 88 
Enter arr[4] : 10 

Before Sorting 
Elements are : 
	arr[0] : 12 
	arr[1] : 10 
	arr[2] : 67 
	arr[3] : 88 
	arr[4] : 10 

After Sorting 
Elements are : 
	arr[0] : 10 
	arr[1] : 10 
	arr[2] : 12 
	arr[3] : 67 
	arr[4] : 88 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

One Dimensional Array Programs / Examples in C programming language

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to reverse array elements... >>
<< C program to find a number from array elements...