C Program to print Floyd’s triangle

Floyd’s triangle is the right angled triangular array of natural numbers. Here we used the nested For loop to print the Floyd’s triangle.
Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include<stdio.h>


int main(){
int i,j,n,k=1;

printf("Enter the range: ");
scanf("%d",&n);

printf("FLOYD'S TRIANGLEnn");
for(i=1;i<=n;i++){
for(j=1;j<=i;j++,k++)
printf(" %d",k);
printf("n");
}

return 0;
}
Read more Similar C Programs
Learn C Programming

Number System

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

(c) www.c-program-example.com

C Program to calculate the total execution time of a program.

C Program to calculate the total execution time of a program. Here we used the “time.h” preprocessor. In this program we used the clock_t variables start and end , They starts the time counter and ends the counter. Execution time of a program is useful to calculate the efficiency of the program.
Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include<stdio.h>
#include<time.h>

int main()
{
int i;
double total_time;
clock_t start, end;

start = clock();//time count starts

srand(time(NULL));
for (i = 0; i < 25000; i++)
{
printf("random_number[%d]= %dn", i + 1, rand());
}
end = clock();//time count stops
total_time = ((double) (end - start)) / CLK_TCK;//calulate total time
printf("nTime taken to print 25000 random number is: %f", total_time);
return 0;
}
Read more Similar C Programs
Learn C Programming

Number System

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

(c) www.c-program-example.com

C Program to sort the string, using shell sort technique.

C Program to sort the string, using shell sort technique. Shell sort is the one of the oldest sorting technique, quite well for all types of arrays in c. The shell sort is a “diminishing increment sort”, better known as a “comb sort” to the unwashed programming masses. The algorithm makes multiple passes through the list, and each time sorts a number of equally sized sets using the insertion sort . The size of the set to be sorted gets larger with each pass through the list, until the set consists of the entire list. This sets the insertion sort up for an almost-best case run each iteration with a complexity that approaches O(n) . Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
void shell_sort(char *chars, int c) {

register int i, j, space, k;
char x, a[5];

a[0]=9; a[1]=5; a[2]=3; a[3]=2; a[4]=1;

for(k=0; k < 5; k++) {
space = a[k];
for(i=space; i < c; ++i) {
x = chars[i];
for(j=i-space; (x < chars[j]) && (j >= 0); j=j-space)
chars[j+space] = chars[j];
chars[j+space] = x;
}
}
}

int main() {
char string[300];
printf("Enter a string:");
gets(string);
shell_sort(string, strlen(string));
printf("The sorted string is: %s.n", string);
return 0;
}
Read more Similar C Programs
Array In C

Sorting Techniques

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

(c) www.c-program-example.com

Merge Sort in C – Program with Example and Complexity

Merge sort is a classic divide and conquer sorting algorithm. It splits an array in half, recursively sorts each half, then merges the two sorted halves back together. Unlike bubble sort or insertion sort, merge sort guarantees O(n log n) performance in all cases — best, average, and worst.

It is the algorithm of choice when stable sorting is required or when sorting linked lists, and it forms the basis of many standard library sort implementations.

How Merge Sort Works — Step by Step

The algorithm has two phases:

  1. Divide: Split the array into two halves. Recursively split each half until you have single-element arrays (a single element is always sorted).
  2. Conquer (Merge): Merge pairs of sorted subarrays back together, comparing elements one by one and placing the smaller one first.

Example: Sorting [38, 27, 43, 3, 9, 82, 10]

Divide phase:
[38, 27, 43, 3, 9, 82, 10]
     /                \
[38, 27, 43]        [3, 9, 82, 10]
   /     \            /          \
[38]  [27, 43]    [3, 9]      [82, 10]
       /    \      /   \       /    \
     [27]  [43]  [3]   [9]  [82]  [10]

Merge phase (building back up):
[27, 43]  →  merge [27] and [43]
[3, 9]    →  merge [3] and [9]
[10, 82]  →  merge [10] and [82]
[27, 38, 43]  →  merge [38] and [27, 43]
[3, 9, 10, 82]  →  merge [3, 9] and [10, 82]
[3, 9, 10, 27, 38, 43, 82]  →  final merge

C Program for Merge Sort

#include <stdio.h>
#include <stdlib.h>

void merge(int arr[], int left, int mid, int right) {
    int i, j, k;
    int n1 = mid - left + 1;
    int n2 = right - mid;

    int *L = (int *)malloc(n1 * sizeof(int));
    int *R = (int *)malloc(n2 * sizeof(int));

    for (i = 0; i < n1; i++)
        L[i] = arr[left + i];
    for (j = 0; j < n2; j++)
        R[j] = arr[mid + 1 + j];

    i = 0;
    j = 0;
    k = left;

    while (i < n1 && j < n2) {
        if (L[i] <= R[j])
            arr[k++] = L[i++];
        else
            arr[k++] = R[j++];
    }

    while (i < n1)
        arr[k++] = L[i++];

    while (j < n2)
        arr[k++] = R[j++];

    free(L);
    free(R);
}

void merge_sort(int arr[], int left, int right) {
    if (left < right) {
        int mid = left + (right - left) / 2;
        merge_sort(arr, left, mid);
        merge_sort(arr, mid + 1, right);
        merge(arr, left, mid, right);
    }
}

int main() {
    int n, i;

    printf("Enter number of elements: ");
    scanf("%d", &n);

    int arr[n];
    printf("Enter %d elements:\n", n);
    for (i = 0; i < n; i++)
        scanf("%d", &arr[i]);

    printf("Before sorting: ");
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);

    merge_sort(arr, 0, n - 1);

    printf("\nAfter merge sort: ");
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);

    printf("\n");
    return 0;
}

Code Explanation

  • merge_sort(arr, left, right): The recursive divide step. Calculates mid = left + (right - left) / 2 (this form avoids integer overflow vs (left+right)/2), then recurses on each half before merging.
  • merge(arr, left, mid, right): The conquer step. Creates two temporary arrays L[] and R[] holding copies of each half, then merges them back into arr[] in sorted order by comparing the front elements of each temp array.
  • Leftover elements: After one half is exhausted, the remaining elements in the other half are already sorted and copied directly — the two while loops at the end handle this.
  • malloc / free: Dynamic memory is used so the function works for any subarray size, not just a fixed maximum.

Sample Input and Output

Enter number of elements: 6
Enter 6 elements:
64 34 25 12 22 11

Before sorting: 64 34 25 12 22 11
After merge sort: 11 12 22 25 34 64

Time and Space Complexity

Case Time Complexity Space Complexity
Best case O(n log n) O(n)
Average case O(n log n) O(n)
Worst case O(n log n) O(n)

Merge sort is one of the few sorting algorithms with guaranteed O(n log n) in all cases. The space complexity is O(n) because the merge step needs temporary arrays to hold the two halves. This makes merge sort less suitable for memory-constrained environments compared to in-place sorts like heap sort or quick sort.

The log n factor comes from the number of times you can halve the array (depth of the recursion tree). At each level, you do O(n) work for the merging, giving O(n log n) total.

Merge Sort vs Other Sorting Algorithms

Algorithm Best Average Worst Space Stable
Merge Sort O(n log n) O(n log n) O(n log n) O(n) Yes
Quick Sort O(n log n) O(n log n) O(n²) O(log n) No
Heap Sort O(n log n) O(n log n) O(n log n) O(1) No
Insertion Sort O(n) O(n²) O(n²) O(1) Yes
Bubble Sort O(n) O(n²) O(n²) O(1) Yes

When to use merge sort: when you need a stable sort, when sorting linked lists (merge sort is optimal for linked lists since it doesn’t require random access), or when you need guaranteed worst-case performance.

Applications of Merge Sort

  • External sorting: Sorting data too large to fit in memory — files are split into chunks, each sorted, then merged. Hard disk sorting uses this approach.
  • Sorting linked lists: Merge sort is preferred over quick sort for linked lists since it does not require random index access.
  • Counting inversions: The merge step can count how many elements are out of order — useful in recommendation systems and order statistics.
  • Standard libraries: Java’s Arrays.sort() for objects and Python’s sort() (Timsort) are based on merge sort.

Related Programs


As an Amazon Associate we earn from qualifying purchases.

Further Reading

The definitive reference for C — The C Programming Language by Brian Kernighan and Dennis Ritchie. Covers every concept on this site: pointers, arrays, structs, file I/O, and the standard library. Worth having on your desk.

Insertion Sort in C – Program, Algorithm and Complexity

Insertion sort is one of the simplest sorting algorithms and works exactly the way you sort a hand of playing cards. You take one card at a time and insert it into its correct position among the cards already sorted in your hand. It sorts the array one element at a time, building the sorted portion from left to right.

While not efficient for large datasets, insertion sort has a key advantage: it performs in O(n) time on nearly-sorted arrays, making it the algorithm of choice for small arrays or as the final step in more complex sorts like Timsort.

How Insertion Sort Works — Step by Step

Start from the second element. For each element, compare it backward through the sorted portion and shift elements right until you find its correct position.

Example: Sorting [12, 11, 13, 5, 6]

Pass 1: key = 11
  [12, 11, 13, 5, 6]
   12 > 11 → shift right
  [11, 12, 13, 5, 6]

Pass 2: key = 13
  13 > 12 → already in place
  [11, 12, 13, 5, 6]

Pass 3: key = 5
  13 > 5 → shift, 12 > 5 → shift, 11 > 5 → shift
  [5, 11, 12, 13, 6]

Pass 4: key = 6
  13 > 6 → shift, 12 > 6 → shift, 11 > 6 → shift
  [5, 6, 11, 12, 13]  ← sorted

C Program for Insertion Sort

#include <stdio.h>

void insertion_sort(int arr[], int n) {
    int i, j, key;
    for (i = 1; i < n; i++) {
        key = arr[i];
        j = i - 1;
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            j--;
        }
        arr[j + 1] = key;
    }
}

int main() {
    int n, i;

    printf("Enter number of elements: ");
    scanf("%d", &n);

    int arr[n];
    printf("Enter %d elements:\n", n);
    for (i = 0; i < n; i++)
        scanf("%d", &arr[i]);

    printf("Before sorting: ");
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);

    insertion_sort(arr, n);

    printf("\nAfter insertion sort: ");
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);

    printf("\n");
    return 0;
}

Code Explanation

  • Outer loop (i = 1 to n-1): Picks one unsorted element at a time as the key. The subarray arr[0..i-1] is always already sorted at the start of each pass.
  • key = arr[i]: Saves the current element before shifting begins — it would be overwritten otherwise.
  • Inner while loop: Scans left through the sorted portion. Every element larger than key shifts one position right, creating a gap for key to be placed.
  • arr[j + 1] = key: Places key in its correct sorted position — either at the start of the array or just after the last element that is smaller than it.

Sample Input and Output

Enter number of elements: 6
Enter 6 elements:
64 25 12 22 11 90

Before sorting: 64 25 12 22 11 90
After insertion sort: 11 12 22 25 64 90

Time and Space Complexity

Case Time Complexity When it occurs
Best case O(n) Array is already sorted — inner loop never executes
Average case O(n²) Elements in random order
Worst case O(n²) Array is sorted in reverse order — maximum shifts every pass

Space complexity: O(1) — insertion sort is an in-place algorithm. It uses only one extra variable (key) regardless of input size. This makes it memory-efficient compared to merge sort, which requires O(n) extra space.

The O(n) best-case performance is a genuine advantage. Algorithms like merge sort and heap sort always take O(n log n) even on sorted data — insertion sort skips all unnecessary work when the data is already in order.

Insertion Sort vs Other Sorting Algorithms

Algorithm Best Average Worst Space Stable Adaptive
Insertion Sort O(n) O(n²) O(n²) O(1) Yes Yes
Merge Sort O(n log n) O(n log n) O(n log n) O(n) Yes No
Quick Sort O(n log n) O(n log n) O(n²) O(log n) No No
Heap Sort O(n log n) O(n log n) O(n log n) O(1) No No
Bubble Sort O(n) O(n²) O(n²) O(1) Yes Yes
Selection Sort O(n²) O(n²) O(n²) O(1) No No

Adaptive means the algorithm runs faster on partially sorted input. Both insertion sort and bubble sort are adaptive — insertion sort is usually preferred because it does fewer swaps.

When to Use Insertion Sort

  • Small arrays (n < 20): The overhead of recursive algorithms like merge sort and quick sort outweighs their theoretical advantage for tiny inputs. Most standard library implementations switch to insertion sort below a threshold (e.g., Java uses 47 elements, Python’s Timsort uses 32–64).
  • Nearly sorted data: If only a few elements are out of place, insertion sort detects this and runs close to O(n).
  • Online sorting: When elements arrive one at a time and must be kept sorted after each insertion (e.g., a live leaderboard).
  • Linked lists: Insertion sort is efficient on linked lists because shifting is replaced by pointer updates.

Related Programs


As an Amazon Associate we earn from qualifying purchases.

Further Reading

The definitive reference for C — The C Programming Language by Brian Kernighan and Dennis Ritchie. Covers every concept on this site: pointers, arrays, structs, file I/O, and the standard library. Worth having on your desk.

C Program to sort a linked list.

Data structures using C, Linked list is a data structure in which the objects are arranged in a linear order. In this program, we sort the list elements in ascending order. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/




#include <stdio.h>
#include <stdlib.h>
#define NULL 0

struct linked_list
{
int number;
struct linked_list *next;
};
typedef struct linked_list node;

main ()
{
int n;
node *head = NULL;
void print(node *p);
node *insert_Sort(node *p, int n);

printf("Input the list of numbers.n");
printf("At end, type -999.n");
scanf("%d",&n);

while(n != -999)
{
if(head == NULL) /* create 'base' node */
{
head = (node *)malloc(sizeof(node));
head ->number = n;
head->next = NULL;

}

else /* insert next item */
{
head = insert_Sort(head,n);
}
scanf("%d", &n);
}
printf("n");
print(head);
print("n");
}
node *insert_Sort(node *list, int x)
{
node *p1, *p2, *p;
p1 = NULL;
p2 = list; /* p2 points to first node */

for( ; p2->number < x ; p2 = p2->next)
{
p1 = p2;

if(p2->next == NULL)
{
p2 = p2->next; /* p2 set to NULL */
break; /* insert new node at end */
}
}

/* key node found */
p = (node *)malloc(sizeof(node)); /* space for new node */
p->number = x; /* place value in the new node */
p->next = p2; /* link new node to key node */
if (p1 == NULL)
list = p; /* new node becomes the first node */
else
p1->next = p; /* new node inserted after 1st node */
return (list);
}
void print(node *list)
{
if (list == NULL)
printf("NULL");
else
{
printf("%d-->",list->number);
print(list->next);
}
return;
}
Read more Similar C Programs
Data Structures

Learn C Programming

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

(c) www.c-program-example.com

C Program to reverse the first n characters in a file.

C Program to reverse the first n characters in a file using the command line arguments. Here we read the file name and n are specified on the command line. If file exists, it reverse the n characters, else it gives the error message. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/


#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <process.h>

void main(int argc, char *argv[])
{
char a[15];
char s[20];
char n;
int k;
int j=0;
int i;
int len;
FILE *fp;

if(argc!=3)
{
puts("Improper number of arguments.");
exit(0);
}
fp = fopen(argv[1],"r");
if(fp == NULL)
{
puts("File cannot be opened.");
exit(0);
}

k=*argv[2]-48;
n = fread(a,1,k,fp);
a[n]='';
len=strlen(a);
for(i=len-1;i>=0;i--)
{
s[j]=a[i];
printf("%c",s[j]);
j=j+1;
}
s[j+1]='';
getch();
}/*(Note: The file name and n are specified on the command line.)*/

Read more Similar C Programs
File operations

Learn C Programming

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

(c) www.c-program-example.com

C program which copies one file contents to another file.

C Program which copies one file contents to another file. Here we read the one file and copies the characters to another file which are existed in the disc. Here we read the file names from the command line.Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/



#include <stdio.h>
#include <conio.h>
#include <process.h>

void main(int argc, char *argv[])
{
FILE *fs,*ft;
char ch;
clrscr();
if(argc!=3)
{
puts("Invalid number of arguments.");
exit(0);
}
fs = fopen(argv[1],"r");
if(fs==NULL)
{
puts("Source file cannot be opened.");
exit(0);
}
ft = fopen(argv[2],"w");
if (ft==NULL)
{
puts("Target file cannot be opened.");
fclose(fs);
exit(0);
}
while(1)
{
ch=fgetc(fs);
if (ch==EOF)
break;
else
fputc(ch,ft);
}
fclose(fs);
fclose(ft);
getch();
}

Read more Similar C Programs
File operations

Learn C Programming

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

(c) www.c-program-example.com

C Program to generate random numbers.

C Program to generate random numbers. Random Numbers are numbers which are produced by a process and its outcome is unpredictable.The function srand() is used to seed the random sequence. The rand() function shall compute a sequence of pseudo-random integers in the range [0, {RAND_MAX}] with a period of at least 2^32.
Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

main() {
int i, num;
printf("Enter how many random numbers you want?n");
scanf("%d", &num);
//The function srand() is used to seed the random sequence.
//srand() will generate a specific "random" sequence over and over again.
srand(time(NULL));
//The rand() function shall compute a sequence of pseudo-random
//integers in the range [0, {RAND_MAX}] with a period of at least 2^32.
for (i = 0; i < num; i++) {
printf("random_number[%d]= %dn", i + 1, rand());
}

printf("A number between 0 and 99: %dn", rand() % 100);

printf("A number between 0 and 9: %dn", rand() % 10);

return 0;
}
Read more Similar C Programs
Learn C Programming

Number System

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

(c) www.c-program-example.com

C Program to show Sleep() function example.

This C program demonstrates the sleep() function, which pauses (delays) the execution of your program for a set amount of time. This is handy for animations, retry loops, timed messages, or simply slowing a program down so you can watch what it does. Because the function differs between operating systems, this tutorial gives you one portable program that works on Windows, Linux and macOS.

Important: The Units Are Different!

A very common mistake is getting the time unit wrong. They are not the same across systems:

Function Header Platform Unit
Sleep(ms) <windows.h> Windows milliseconds
sleep(sec) <unistd.h> Linux / macOS seconds
usleep(us) <unistd.h> Linux / macOS microseconds

So Sleep(1000) on Windows waits one second (1000 ms), while sleep(1) on Linux also waits one second. (Older tutorials that call this “microseconds” are simply wrong.)

The Program (Portable)

#include <stdio.h>

#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif

int main(void)
{
    printf("Message before the pause...\n");
    fflush(stdout);   /* force output to appear before we sleep */

#ifdef _WIN32
    Sleep(2000);      /* Windows: milliseconds -> 2000 ms = 2 seconds */
#else
    sleep(2);         /* Linux / macOS: seconds */
#endif

    printf("Message after a 2-second pause.\n");
    return 0;
}

How the Program Works

  • The #ifdef _WIN32 block picks the right header and function for the platform automatically, so the same source compiles everywhere.
  • fflush(stdout) forces the first message to print before the pause — otherwise it might sit in the output buffer until the program ends.
  • The program prints a message, waits two seconds, then prints again. This replaces the old version that used the Windows-only <windows.h> and getch() and would not compile on Linux or macOS.

Sample Output

Message before the pause...
(2 second pause)
Message after a 2-second pause.

For a deeper understanding of the standard library and system calls, The C Programming Language by Kernighan and Ritchie is the classic reference — find it on Amazon.

This post contains affiliate links. If you buy through them, we may earn a small commission at no extra cost to you.

Related C Programs

Because timing behaviour depends on your system, run this on a real local setup — see our guide to a complete C development environment.