Written: August 14, 2026 · Updated: August 15, 2026
Sorting teaches comparison, swapping, and why off-by-one bugs love nested loops.
This walkthrough keeps the logic small and readable so you can type it, run it, and then change one input at a time to see what happens.
What you will build
You will fill a small integer array, then use a simple selection-style swap pass so each position keeps the next smallest value.
- Read n and the array elements
- For each index i, scan the rest of the array for a smaller value
- Swap when you find one
- Print the array after sorting
Working C example
include <stdio.h>
int main(void) {
int n, i, j, temp;
int a[100];
printf("Enter count (1-100): ");
if (scanf("%d", &n) != 1 || n < 1 || n > 100) return 1;
for (i = 0; i < n; i++) {
if (scanf("%d", &a[i]) != 1) return 1;
}
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (a[j] < a[i]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("Ascending: ");
for (i = 0; i < n; i++) printf("%d ", a[i]);
printf("\n");
return 0;
}
How the logic works
Read the program top to bottom: includes and main first, then the statements that change variables, then the print that proves the result.
If your output looks wrong, print the variables before and after the critical lines. That single habit catches most beginner bugs faster than rewriting the whole file.
Verify with duplicates and already-sorted input. If those pass, your comparisons are probably solid.
Keep learning
If this walkthrough on Sort an Array in Ascending Order in C helped, open the code again and change one input or assumption. Small experiments beat rereading the same example.
Want more step-by-step tutorials like this? Browse blog.xqa.io — and tell us which topic you want next.