Sort Array Elements

CCBeginner
Practice Now

Introduction

This lab will guide you through a step-by-step process for sorting array elements in ascending order.

Create a new file

Create a new C program file named main.c in the ~/project/ directory. This will be where you will write your code.

Declare variables

Start by declaring the necessary variables that you will use when sorting the array:

#include <stdio.h>

int main()
{
    int n, i, j, temp, arr[100];
  • n stores the number of elements
  • arr will be the array that will hold the elements
  • i and j are loop counters
  • temp is a temporary variable used for swapping elements

Input array elements

Ask the user to enter the number of elements they want to sort and then prompt them to input each element:

    printf("Enter the number of elements you want to sort (max 100): ");
    scanf("%d", &n);
    printf("Enter %d integers: \n", n);
    for(i = 0; i < n; i++)
        scanf("%d", &arr[i]);

Sort the array elements

Use a nested for loop to sort the array:

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

Display the sorted array elements

Display the sorted array elements:

    printf("Sorted list in ascending order:\n");
    for(i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");

Compile and run the program

Compile and run the program to ensure that it works correctly.

Full code in main.c

#include <stdio.h>

int main()
{
    int n, i, j, temp, arr[100];

    printf("Enter the number of elements you want to sort (max 100): ");
    scanf("%d", &n);
    printf("Enter %d integers: \n", n);
    for(i = 0; i < n; i++)
        scanf("%d", &arr[i]);

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

    printf("Sorted list in ascending order:\n");
    for(i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");

    return 0;
}

Summary

In this lab, you've learned how to sort array elements in ascending order using a C program. Now you can use this knowledge to sort arrays with your own code.

Other C Tutorials you may like