Skip to content
Home » C Programs » Insertion Sort Program in C Using For Loop

Insertion Sort Program in C Using For Loop

Simple insertion sort program in c using for loop. In this program, we can execute the c program for beginners to understand the sorting method in c.

For Loop Definition

In the C programming language, the for loop is used to iterate statements or parts of a program numerous times. It is commonly used to traverse data structures such as an array and a linked list. 

A for-loop (or simply for loop) is a control flow statement in computer science that specifies iteration and allows code to be executed repeatedly. When the number of iterations is known before entering the loop, for-loops are commonly utilised.

Insertion Sort Definition

Insertion sort is a sorting method in which elements are moved to the correct spot one at a time. In other words, with the movement of higher-ranked items, an insertion sort aids in the construction of the final sorted list, one item at a time.

Insertion Sort Program in C Using For Loop

//insertion sort program in c using for loop
#include <stdio.h>
int main()
{
int n, i, j, temp;
int arr[64];
printf("Enter the number\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
for (i = 1 ; i <= n - 1; i++)
{
j = i;
while ( j > 0 && arr[j-1] > arr[j])
{	        
temp     = arr[j];
arr[j]   = arr[j-1];
arr[j-1] = temp;
j--;
}
}
printf("Ascending Order\n");
for (i = 0; i <= n - 1; i++)
{
printf("%d\n", arr[i]);
}
return 0;
}

Enter the number
3
Enter 3 integers
45
23
56
Ascending Order
23
45
56