Introduction
This lab will guide you through a step-by-step process for sorting array elements in ascending order.
This lab will guide you through a step-by-step process for sorting array elements in ascending order.
Create a new C program file named main.c
in the ~/project/
directory. This will be where you will write your code.
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 elementsarr
will be the array that will hold the elementsi
and j
are loop counterstemp
is a temporary variable used for swapping elementsAsk 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]);
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:
printf("Sorted list in ascending order:\n");
for(i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
Compile and run the program to ensure that it works correctly.
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;
}
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.