C Program to perform complex numbers operations using structure.

C Program to perform complex numbers operations using structure. Complex numbers are numbers which contains two parts, real part and imaginary part. Complex numbers are written as a+ib, a is the real part and b is the imaginary part. We used the structure in C to define the real part and imaginary part of the complex number.
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<math.h>

void arithmetic(int opern);

struct comp
{
double realpart;
double imgpart;
};

void main()
{
int opern;
clrscr();
printf("nn ttt***** MAIN MENU *****");
printf("nn Select your option: n 1 : ADDn 2 : MULTIPLYn 0 : EXIT nntt Enter your Option [ ]bb");

scanf("%d",&opern);

switch(opern)
{
case 0:
exit(0);
case 1:
case 2:
arithmetic(opern);
default:
main();
}

}

void arithmetic(int opern)
{

struct comp w1, w2, w;

printf("n Enter two Complex Numbers (x+iy):n Real Part of First Number:");
scanf("%lf",&w1.realpart);
printf("n Imaginary Part of First Number:");
scanf("%lf",&w1.imgpart);
printf("n Real Part of Second Number:");
scanf("%lf",&w2.realpart);
printf("n Imaginary Part of Second Number:");
scanf("%lf",&w2.imgpart);


switch(opern)
{

/*addition of complex number*/
case 1:
w.realpart = w1.realpart+w2.realpart;
w.imgpart = w1.imgpart+w2.imgpart;
break;

/*multiplication of complex number*/
case 2:
w.realpart=(w1.realpart*w2.realpart)-(w1.imgpart*w2.imgpart);
w.imgpart=(w1.realpart*w2.imgpart)+(w1.imgpart*w2.realpart);
break;
}


if (w.imgpart>0)
printf("n Answer = %lf+%lfi",w.realpart,w.imgpart);
else
printf("n Answer = %lf%lfi",w.realpart,w.imgpart);
getch();
main();
}
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!


List of C Programs
(c) www.c-program-example.com

C Program to convert a Roman numeral to its decimal equivalent.

C Program to convert a Roman numeral to its decimal equivalent. Roman numbers are the oldest number system used in ancient Rome. They use the combination of letters from Latin alphabet to represent the system. We used the if-else and for statements to solve this problem. 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<stdlib.h>

void main()
{

int *a,len,i,j,k;
char *rom;

clrscr();

printf("Enter the Roman Numeral:");
scanf("%s",rom);

len=strlen(rom);

for(i=0;i<len;i++)
{
if(rom[i]=='I')
a[i]=1;
else if(rom[i]=='V')
a[i]=5;
else if(rom[i]=='X')
a[i]=10;
else if(rom[i]=='L')
a[i]=50;
else if(rom[i]=='C')
a[i]=100;
else if(rom[i]=='D')
a[i]=500;
else if(rom[i]=='M')
a[i]=1000;
else
{
printf("nInvalid Value");
getch();
exit(0);
}
}
k=a[len-1];
for(i=len-1;i>0;i--)
{
if(a[i]>a[i-1])
k=k-a[i-1];
else if(a[i]==a[i-1] || a[i]<a[i-1])
k=k+a[i-1];
}
printf("nIts Decimal Equivalent is:");
printf("%d",k);
getch();
}
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!


List of C Programs
(c) www.c-program-example.com

C program to find the 2’s complement of a binary number.

C Program to calculate the 2’s complement of a binary number. 2’s complement of a number is obtained by scanning it from right to left and complementing all the bits after the first appearance of a 1. Thus 2’s complement of 11100 is 00100. 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>

void complement (char *a);
void main()
{
char a[16];
int i;
clrscr();
printf("Enter the binary number");
gets(a);
for(i=0;a[i]!=''; i++)
{
if (a[i]!='0' && a[i]!='1')
{
printf("The number entered is not a binary number. Enter the correct number");
exit(0);
}
}
complement(a);
getch();
}
void complement (char *a)
{
int l, i, c=0;
char b[16];
l=strlen(a);
for (i=l-1; i>=0; i--)
{
if (a[i]=='0')
b[i]='1';
else
b[i]='0';
}
for(i=l-1; i>=0; i--)
{
if(i==l-1)
{
if (b[i]=='0')
b[i]='1';
else
{
b[i]='0';
c=1;
}
}
else
{
if(c==1 && b[i]=='0')
{
b[i]='1';
c=0;
}
else if (c==1 && b[i]=='1')
{
b[i]='0';
c=1;
}
}
}
b[l]='';
printf("The 2's complement is %s", b);
}



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 delete n Characters from a given position in a given string.

C Strings:
C Program to delete the n characters from a given position from a given string. Here we use the gets() and puts() functions to read and write the string. delchar() function reads the character string and checks the length and position, then using strcpy() function it replaces the original string.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>

void delchar(char *x,int a, int b);

void main()
{
char string[10];
int n,pos,p;
clrscr();

puts("Enter the string");
gets(string);
printf("Enter the position from where to delete");
scanf("%d",&pos);
printf("Enter the number of characters to be deleted");
scanf("%d",&n);
delchar(string, n,pos);
getch();
}

// Function to delete n characters
void delchar(char *x,int a, int b)
{
if ((a+b-1) <= strlen(x))
{
strcpy(&x[b-1],&x[a+b-1]);
puts(x);
}
}


Read more Similar C Programs
Learn C Programming

C Strings

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 insert a sub-string in to given main string from a given position.

C Strings:
C Program to insert a sub-string in to given main string from a given position. In this program we read two strings and replace the second string in the given position of the first string.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>

void main()
{
char a[10];
char b[10];
char c[10];
int p=0,r=0,i=0;
int t=0;
int x,g,s,n,o;
clrscr();

puts("Enter First String:");
gets(a);
puts("Enter Second String:");
gets(b);
printf("Enter the position where the item has to be inserted: ");
scanf("%d",&p);
r = strlen(a);
n = strlen(b);
i=0;

// Copying the input string into another array
while(i <= r)
{
c[i]=a[i];
i++;
}
s = n+r;
o = p+n;

// Adding the sub-string
for(i=p;i<s;i++)
{
x = c[i];
if(t<n)
{
a[i] = b[t];
t=t+1;
}
a[o]=x;
o=o+1;
}

printf("%s", a);
getch();
}
Read more Similar C Programs
Learn C Programming

C Strings

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 find the distance traveled at regular intervals of time given .

C program to find the distance traveled at regular intervals of time given the values of ‘u’ and ‘a’. The program should provide the flexibility to the user to select his own time intervals and repeat the calculations for different values of ‘u’ and ‘a’. 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 <math.h>

void main() {
int tim_intrval, counter, time;
float accl, distance = 0, velos;
clrscr();
printf(
"<===========PROGRAM TO CALCULATE TOTAL DISTANCE TRAVELED BY A VECHIAL===========>");
printf("nnntNO OF TIME INTERVALS : ");
scanf("%d", &tim_intrval);

for (counter = 1; counter <= tim_intrval; counter++) {
printf("nttAT T%d TIME(sec) : ", counter);
scanf("%d", &time);
printf("ttVELOCITY AT %d sec (m/sec) : ", time);
scanf("%f", &velos);
printf("ttACCLERATION AT %d sec (m/sec^2): ", time);
scanf("%f", &accl);
distance += (velos * time + (accl * pow(time, 2)) / 2);
}

printf(
"nnntTOTAL DISTANCE TRAVELLED BY VEHICLE IN %d INTERVALS OF TIME : %f",
tim_intrval, distance);
getch();
}
Read more Similar C Programs
Learn C Programming

C Strings

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 Implement Heap Sort — Algorithm, Tree Visualization, and Complexity

Heap Sort is a comparison-based sorting algorithm that uses a binary heap data structure. Its standout property: it is guaranteed O(n log n) in all cases — best, average, and worst — while using only O(1) extra memory. No Quick Sort worst-case surprises, no Merge Sort extra array.

Key Concept — The Max-Heap

A max-heap is a complete binary tree where every parent is greater than or equal to its children. Stored as an array, the relationships are:

  • Parent of node i: (i - 1) / 2
  • Left child of i: 2 * i + 1
  • Right child of i: 2 * i + 2
Array:  [10,  5,  3,  4,  1]
Index:    0   1   2   3   4

Tree view:
       10          ← root = largest element
      /  \
     5    3
    / \
   4   1

The root of a max-heap is always the largest element — Heap Sort exploits this to extract elements in descending order.

Algorithm — Two Phases

  1. Build max-heap — rearrange the unsorted array into a valid max-heap. O(n).
  2. Extract max repeatedly — swap root (largest) to the end of the array, shrink the heap by one, restore the heap property. Repeat n-1 times. O(n log n).

Step-by-Step Example

Sort [4, 10, 3, 5, 1]:

Initial array: [4, 10, 3, 5, 1]

── Phase 1: Build Max-Heap ──
Start at last non-leaf (index 1, value 10):
  10 > children (5, 1) → no swap

Move to index 0 (value 4):
  4 < 10 → swap → [10, 4, 3, 5, 1]
  Sift 4 down: 4 < 5 → swap → [10, 5, 3, 4, 1]

Max-heap built: [10, 5, 3, 4, 1]

── Phase 2: Extract ──
Swap root with last → [1, 5, 3, 4, | 10]  sift down 1 → [5, 4, 3, 1, | 10]
Swap root with last → [1, 4, 3, | 5, 10]  sift down 1 → [4, 1, 3, | 5, 10]
Swap root with last → [3, 1, | 4, 5, 10]  sift down 3 → [3, 1, | 4, 5, 10]
Swap root with last → [1, | 3, 4, 5, 10]

Final: [1, 3, 4, 5, 10] ✓

C Program — Heap Sort

#include <stdio.h>

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

/* Restore max-heap property at index i in a heap of size n */
void sift_down(int arr[], int n, int i) {
    int largest = i;
    int left    = 2 * i + 1;
    int right   = 2 * i + 2;

    if (left  < n && arr[left]  > arr[largest]) largest = left;
    if (right < n && arr[right] > arr[largest]) largest = right;

    if (largest != i) {
        swap(&arr[i], &arr[largest]);
        sift_down(arr, n, largest);
    }
}

/* Build a max-heap in-place — O(n) */
void build_heap(int arr[], int n) {
    for (int i = n / 2 - 1; i >= 0; i--)
        sift_down(arr, n, i);
}

void heapsort(int arr[], int n) {
    build_heap(arr, n);

    for (int i = n - 1; i > 0; i--) {
        swap(&arr[0], &arr[i]);  /* move current max to sorted end */
        sift_down(arr, i, 0);    /* restore heap over remaining elements */
    }
}

void print_array(int arr[], int n) {
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
}

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

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

    printf("Before sorting: ");
    print_array(arr, n);

    heapsort(arr, n);

    printf("After sorting:  ");
    print_array(arr, n);

    return 0;
}

Code Explanation

  • sift_down(arr, n, i) — looks at node i and its two children. If either child is larger, swaps the node with the largest child and recurses downward. This restores the max-heap property from i down to the leaves.
  • build_heap() — starts from the last non-leaf node (n/2 - 1) and calls sift_down() going backwards to index 0. Bottom-up construction is O(n) — more efficient than inserting elements one by one.
  • heapsort() — after building the heap, repeatedly swaps arr[0] (the max) with the last unsorted element, then shrinks the heap by 1 and calls sift_down() to restore the heap over the remaining elements.

Sample Output

Enter number of elements: 6
Enter 6 elements: 4 10 3 5 1 8
Before sorting: 4 10 3 5 1 8
After sorting:  1 3 4 5 8 10

Time and Space Complexity

Case Time Explanation
Best O(n log n) build_heap O(n) + n extractions × O(log n)
Average O(n log n) Same structure regardless of input
Worst O(n log n) No degenerate case — unlike Quick Sort
Space O(1) In-place — no extra array needed

Heap Sort vs Other Sorting Algorithms

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

Heap Sort's unique position: it matches Merge Sort's worst-case guarantee (always O(n log n)) while matching Quick Sort's space efficiency (O(1) extra memory). In practice Quick Sort is faster on average due to better cache behaviour, but Heap Sort is the right choice when you need a hard worst-case bound without allocating extra memory.

Real-World Applications

  • Priority queues — the heap structure itself (not just the sort) is used everywhere: OS schedulers, Dijkstra's shortest path, Huffman coding
  • Order statistics — finding the k-th largest element in O(n + k log n)
  • Embedded/real-time systems — guaranteed O(n log n) with no extra memory suits constrained environments
  • External sorting — heap-based merge in k-way merge sort

Related Sorting Programs in C


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 Implement Quick Sort — With Explanation and Complexity

Quick Sort is one of the fastest and most widely used sorting algorithms. It uses a divide-and-conquer strategy: pick a pivot element, partition the array so everything smaller than the pivot is on its left and everything larger is on its right, then recursively sort each side. The pivot ends up in its final sorted position after each partition step.

The C standard library’s qsort() function is built on Quick Sort — knowing how it works makes you a better C programmer.

Algorithm — How It Works

  1. Choose a pivot (we use the last element — Lomuto partition scheme)
  2. Rearrange the array so all elements ≤ pivot come before it, all elements > pivot come after
  3. The pivot is now in its final position
  4. Recursively apply steps 1–3 to the left and right subarrays

Step-by-Step Example

Sort [64, 34, 25, 12, 22]:

Initial:       [64, 34, 25, 12, 22]   pivot = 22

After pass 1:  [12, 22, 64, 34, 25]   22 is in final position (index 1)
                    ^-- pivot placed

Left  [12]  → already 1 element, done
Right [64, 34, 25]  pivot = 25

After pass 2:  [25, 64, 34]           25 placed, right = [64, 34]
After pass 3:  [34, 64]               34 placed

Final:         [12, 22, 25, 34, 64] ✓

C Program — Quick Sort

#include <stdio.h>

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

/* Lomuto partition: pivot = last element */
int partition(int arr[], int low, int high) {
    int pivot = arr[high];
    int i = low - 1;

    for (int j = low; j < high; j++) {
        if (arr[j] <= pivot) {
            i++;
            swap(&arr[i], &arr[j]);
        }
    }
    swap(&arr[i + 1], &arr[high]);
    return i + 1;
}

void quicksort(int arr[], int low, int high) {
    if (low < high) {
        int pi = partition(arr, low, high);
        quicksort(arr, low, pi - 1);
        quicksort(arr, pi + 1, high);
    }
}

void print_array(int arr[], int n) {
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
}

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

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

    printf("Before sorting: ");
    print_array(arr, n);

    quicksort(arr, 0, n - 1);

    printf("After sorting:  ");
    print_array(arr, n);

    return 0;
}

Code Explanation

  • partition() — scans the array with two indices. j moves forward comparing each element to the pivot; i tracks the boundary between the “smaller” and “larger” regions. When arr[j] ≤ pivot, the element belongs in the left region — swap it across the boundary and advance i. After the loop, swap the pivot from arr[high] to its final position at arr[i+1].
  • quicksort() — calls partition() to get the pivot’s final index, then recurses on the two sides. The base case low < high stops recursion when the subarray has 0 or 1 elements.
  • swap() — takes pointers so the values are exchanged in-place without copying the array.

Sample Output

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

Time and Space Complexity

Case Time Explanation
Best O(n log n) Pivot always splits array in half
Average O(n log n) Random pivot gives balanced splits on average
Worst O(n²) Pivot is always min or max — happens on already-sorted input
Space O(log n) Recursion stack depth (average); O(n) worst case

Worst case tip: The O(n²) worst case happens when the array is already sorted and you always pick the first or last element as pivot. In production code, use the “median-of-three” strategy (pick the median of first, middle, and last elements) to avoid this.

Quick Sort vs Other Sorting Algorithms

Algorithm Best Average Worst Space Stable
Quick Sort O(n log n) O(n log n) O(n²) O(log n) No
Merge Sort O(n log n) O(n log n) O(n log n) O(n) Yes
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

Quick Sort is the practical winner for most in-memory sorting: its average case matches Merge Sort, but it avoids the O(n) extra memory and has better cache behaviour due to in-place partitioning.

Real-World Applications

  • C standard library qsort() — uses a variant of Quick Sort internally
  • Database engines for in-memory result set sorting
  • Programming language runtimes (V8, CPython) for array sort
  • Any scenario needing fast average-case in-place sorting with no memory constraints

Related Sorting Programs in C


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 Implement the multiple priority queue.

A priority queue is a data structure where each element is served according to its priority rather than just the order it arrived. A multiple priority queue implements this with several separate queues — one per priority level — so that higher-priority items are always removed before lower-priority ones. This C program builds a simple menu-driven multiple priority queue with three priority levels using arrays.

How It Works

We keep an array of three queue structures (priority 1 is highest). Inserting an element adds it to the queue for its priority. Deleting always removes from the highest-priority non-empty queue first, then the next, and so on.

The Program

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

#define MAX 5      /* capacity of each priority queue */
#define LEVELS 3   /* number of priority levels */

struct pqueue {
    int front, rear;
    int items[MAX];
};

int is_empty(struct pqueue *q) { return q->front > q->rear; }
int is_full(struct pqueue *q)  { return q->rear == MAX - 1; }

void insert(struct pqueue *q)
{
    int x;
    if (is_full(q)) {
        printf("Queue overflow.\n");
        return;
    }
    printf("Enter the element to insert : ");
    scanf("%d", &x);
    q->items[++(q->rear)] = x;
}

void delete_item(struct pqueue q[])
{
    for (int i = 0; i < LEVELS; i++)
        if (!is_empty(&q[i])) {
            printf("Deleted %d (from priority %d)\n",
                   q[i].items[q[i].front++], i + 1);
            return;
        }
    printf("All queues are empty.\n");
}

void display(struct pqueue q[])
{
    for (int i = 0; i < LEVELS; i++) {
        printf("Priority %d : ", i + 1);
        if (is_empty(&q[i]))
            printf("(empty)");
        else
            for (int j = q[i].front; j <= q[i].rear; j++)
                printf("%d ", q[i].items[j]);
        printf("\n");
    }
}

int main(void)
{
    struct pqueue q[LEVELS];
    int ch, p;

    for (int i = 0; i < LEVELS; i++) {
        q[i].front = 0;
        q[i].rear = -1;
    }

    while (1) {
        printf("\n--- MENU ---\n1.Insert  2.Delete  3.Display  4.Exit\n");
        printf("Enter your choice : ");
        if (scanf("%d", &ch) != 1)
            break;

        switch (ch) {
        case 1:
            printf("Enter priority (1-%d) : ", LEVELS);
            scanf("%d", &p);
            if (p < 1 || p > LEVELS) {
                printf("Invalid priority.\n");
                break;
            }
            insert(&q[p - 1]);
            break;
        case 2: delete_item(q); break;
        case 3: display(q);     break;
        case 4: exit(0);
        default: printf("Invalid choice.\n");
        }
    }
    return 0;
}

How the Program Works

  • Each priority level is a fixed-size array queue with its own front and rear indices.
  • Insert asks for a priority (1–3) and appends the element to that queue, guarding against overflow.
  • Delete scans the queues from highest to lowest priority and removes from the first non-empty one — this is what gives the structure its priority behaviour.
  • Display prints the contents of all three queues.
  • This version cleans up the original implicit-int main(), the missing newline escapes (n instead of \n), and a stray character, and adds input validation.

Sample Output

--- MENU ---
1.Insert  2.Delete  3.Display  4.Exit
Enter your choice : 1
Enter priority (1-3) : 2
Enter the element to insert : 50

Enter your choice : 2
Deleted 50 (from priority 2)

For a thorough treatment of queues and other data structures in C, 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

Try it instantly in one of the best online C compilers, or set up a local toolchain with our complete C development environment guide.

C program to implement Towers of Hanoi and Binary Search

C Recursion:
C Program to implement Towers of Hanoi and Binary Search using the Recursion method. Recursive functions solves the complexity of the problem by calling the function again and again itself. Using recursive methods we can save execution time and memory. In this program we have two recursive functions for Binary search and the Tower of Hanoi problem. 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>
main() {
int n, a[50], key, opn, i, pos;

do {
clrscr();
printf(
" nn Press 1 -> Binary Search , 2-> Towers of Hanoi 3-> Quitn");
scanf("%d", &opn);
switch (opn) {
case 1:
printf(" How Many Elements?");
scanf("%d", &n);
printf(" Read all the elements is ASC order n");
for (i = 1; i <= n; i++)
scanf("%d", &a[i]);
printf(" Read the Key Elementn");
scanf("%d", &key);
pos = BS(a, key, 1, n);
if (pos)
printf(" Success: %d found at %d n", key, pos);
else
printf(" Falure: %d Not found in the list ! n", key);
break;
case 2:
printf("nn How Many Disks ?");
scanf("%d", &n);
printf("nn Result of Towers of Hanoi for %d Disks n", n);
tower(n, 'A', 'B', 'C');
printf("nn Note: A-> Source, B-> Intermediate, C-> Destinationn");
break;
case 3:
printf(" Terminating n");
break;
default:
printf(" Invalid Option !! Try Again !! n");
}
printf(" Press a Key. . . ");
getch();
} while (opn != 3);
}

int BS(int a[], int key, int low, int high) {
int mid;

if (low > high)
return 0; /* failure */
else {
mid = (low + high) / 2;
if (a[mid] == key)
return mid; /* Success */
if (key < a[mid])
return (BS(a, key, low, mid - 1));
return (BS(a, key, mid + 1, high));
}
}

tower(int n, char src, char intr, char dst) {
if (n > 0) {
tower(n - 1, src, dst, intr);
printf("Move disk %d from %c to %c n", n, src, dst);
tower(n - 1, intr, src, dst);
}
}

Read more Similar C Programs

Data Structures


C Recursion

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