Quantcast
Channel: Algorithm – The Crazy Programmer
Viewing all 56 articles
Browse latest View live

Depth First Search (DFS) Program in C

$
0
0
In this tutorial you will learn about Depth First Search (DFS) program in C with algorithm.
Most of graph problems involve traversal of a graph. Traversal of a graph means visiting each node and visiting exactly once. There are two types of traversal in graphs i.e. Depth First Search (DFS) and Breadth First Search (BFS).
 
It is like tree. Traversal can start from any vertex, say Vi . Vi is visited and then all vertices adjacent to Vi are traversed recursively using DFS. Since, a graph can have cycles. We must avoid revisiting a node. To do this, when we visit a vertex V, we mark it visited. A node that has already been marked as visited should not be selected for traversal. Marking of visited vertices can be done with the help of a global array visited[ ]. Array visited[ ] is initialized to false (0).
 

Depth First Search (DFS) Algorithm

n ← number of nodes
Initialize visited[ ] to false (0)
for(i=0;i<n;i++)
	visited[i] = 0;

void DFS(vertex i) [DFS starting from i]
{
	visited[i]=1;
	for each w adjacent to i
		if(!visited[w])
			DFS(w);
}

 

Depth First Search (DFS) Traversal of a Graph [Algorithm and Program]

The graph shown above is taken as input in both the programs mentioned below:

Depth First Search (DFS) Program in C [Adjacency Matrix]

#include<stdio.h>
 
void DFS(int);
int G[10][10],visited[10],n;    //n is no of vertices and graph is sorted in array G[10][10]
 
void main()
{
    int i,j;
    printf("Enter number of vertices:");
   
	scanf("%d",&n);
 
    //read the adjecency matrix
	printf("\nEnter adjecency matrix of the graph:");
   
	for(i=0;i<n;i++)
       for(j=0;j<n;j++)
			scanf("%d",&G[i][j]);
 
    //visited is initialized to zero
   for(i=0;i<n;i++)
        visited[i]=0;
 
    DFS(0);
}
 
void DFS(int i)
{
    int j;
	printf("\n%d",i);
    visited[i]=1;
	
	for(j=0;j<n;j++)
       if(!visited[j]&&G[i][j]==1)
            DFS(j);
}

 

C Program to implement DFS traversal on a graph represented using an adjacency matrix

Depth First Search (DFS) Program in C [Adjacency List]

#include<stdio.h>
 
typedef struct node
{
    struct node *next;
    int vertex;
}node;
 
node *G[20];   
//heads of linked list
int visited[20];
int n;
void read_graph(); 
//create adjacency list
void insert(int,int);  
//insert an edge (vi,vj) in te adjacency list
void DFS(int);
 
void main()
{
    int i;
    read_graph();
    //initialised visited to 0
   
	for(i=0;i<n;i++)
        visited[i]=0;
 
    DFS(0);
}
 
void DFS(int i)
{
    node *p;
   
	printf("\n%d",i);
    p=G[i];
    visited[i]=1;
    while(p!=NULL)
    {
       i=p->vertex;
       
	   if(!visited[i])
            DFS(i);
        p=p->next;
    }
}
 
void read_graph()
{
    int i,vi,vj,no_of_edges;
    printf("Enter number of vertices:");
   
	scanf("%d",&n);
 
    //initialise G[] with a null
   
	for(i=0;i<n;i++)
    {
        G[i]=NULL;
        //read edges and insert them in G[]
       
		printf("Enter number of edges:");
       	scanf("%d",&no_of_edges);
 
       	for(i=0;i<no_of_edges;i++)
        {
        	printf("Enter an edge(u,v):");
			scanf("%d%d",&vi,&vj);
			insert(vi,vj);
        }
    }
}
 
void insert(int vi,int vj)
{
    node *p,*q;
    
	//acquire memory for the new node
	q=(node*)malloc(sizeof(node));
    q->vertex=vj;
    q->next=NULL;
 
    //insert the node in the linked list number vi
    if(G[vi]==NULL)
        G[vi]=q;
    else
    {
        //go to end of the linked list
        p=G[vi];
       
		while(p->next!=NULL)
        	p=p->next;
        p->next=q;
    }
}
 
C Program to implement DFS traversal on a graph represented using an adjacency list
 
If you found anything incorrect or have doubts regarding above Depth First Search (DFS) program in C tutorial then comment below.

The post Depth First Search (DFS) Program in C appeared first on The Crazy Programmer.


C Program for Shortest Job First (SJF) Scheduling Algorithm

$
0
0
Here you will get C program for shortest job first (sjf) scheduling algorithm.
 
In shortest job first scheduling algorithm, the processor selects the waiting process with the smallest execution time to execute next.

 
Below I have shared the C program for this algorithm.

#include<stdio.h>

void main()
{
    int bt[20],p[20],wt[20],tat[20],i,j,n,total=0,pos,temp;
    float avg_wt,avg_tat;
    printf("Enter number of process:");
    scanf("%d",&n);

    printf("\nEnter Burst Time:\n");
    for(i=0;i<n;i++)
    {
        printf("p%d:",i+1);
        scanf("%d",&bt[i]);
        p[i]=i+1;           //contains process number
    }

    //sorting burst time in ascending order using selection sort
    for(i=0;i<n;i++)
    {
        pos=i;
        for(j=i+1;j<n;j++)
        {
            if(bt[j]<bt[pos])
                pos=j;
        }

        temp=bt[i];
        bt[i]=bt[pos];
        bt[pos]=temp;

        temp=p[i];
        p[i]=p[pos];
        p[pos]=temp;
    }

    wt[0]=0;            //waiting time for first process will be zero

    //calculate waiting time
    for(i=1;i<n;i++)
    {
        wt[i]=0;
        for(j=0;j<i;j++)
            wt[i]+=bt[j];

        total+=wt[i];
    }

    avg_wt=(float)total/n;      //average waiting time
    total=0;

    printf("\nProcess\t    Burst Time    \tWaiting Time\tTurnaround Time");
    for(i=0;i<n;i++)
    {
        tat[i]=bt[i]+wt[i];     //calculate turnaround time
        total+=tat[i];
        printf("\np%d\t\t  %d\t\t    %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);
    }

    avg_tat=(float)total/n;     //average turnaround time
    printf("\n\nAverage Waiting Time=%f",avg_wt);
    printf("\nAverage Turnaround Time=%f\n",avg_tat);
}

 

Output

C Program for Shortest Job First (SJF) Scheduling Algorithm

The post C Program for Shortest Job First (SJF) Scheduling Algorithm appeared first on The Crazy Programmer.

Huffman Coding Algorithm With Example

$
0
0
Huffman coding algorithm was invented by David Huffman in
1952. It is an algorithm which works with integer length codes. A Huffman tree
represents Huffman codes for the character that might appear in a text file.
Unlike to ASCII or Unicode, Huffman code uses different number of bits to
encode letters. If the number of occurrence of any character is more, we use fewer
numbers of bits. Huffman coding is a method for the construction of minimum redundancy
codes.
Huffman tree can be achieved by using compression technique.
Data compression have lot of advantages such as it minimizes cost, time,
bandwidth, storage space for transmitting data from one place to another.
In regular text file each character would take up 1 byte (8
bits) i.e. there are 16 characters (including white spaces and punctuations)
which normally take up 16 bytes. In the ASCII code there are 256 characters and
this leads to the use of 8 bits to represent each character but in any test
file we do not have use all 256 characters. For example, in any English language
text, generally the character ‘e’ appears more than the character ‘z’. To achieve
compression, we can often use a shorter bit string to represent more frequently
occurring characters. We do not have to represent all 256 characters, unless
they all appear in the document. The data encoding schemes broadly categorized
in two categories.

Fixed Length Encoding Scheme

Fixed length encoding scheme compresses our data by packing
it into the minimum number of bits i.e. needed to represent all possible values
of our data. The fixed length code can store maximum 224,000 bits data.

Variable Length Encoding Scheme

In variable length encoding scheme we map source symbol to
variable number of bits. It allows source to be compressed and decompressed
with zero error.

Construction of Huffman Code

A greedy algorithm constructs an optimal prefix code called
Huffman code. The algorithm builds the tree T corresponding to the optimal code
in a bottom-up manner. It begins with a set of |C| leaves (C is the number of
characters) and perform |C| – 1 ‘merging’ operations to create the final tree.
In the Huffman algorithm ‘n’ denotes the number of set of characters, z denotes
the parent node and x & y are the left & right child of z respectively.
Huffman (C)
1. n=|C|
2. Q=C
3. for i=1 to n-1
4. do
5. z=allocate_Node()
6. x=left[z]=Extract_Min(Q)
7. y=right[z]=Extract_Min(Q)
8. f[z]=f[x]+f[y]
9. Insert(Q,z)
10. return Extract_Min(Q)

Analysis

The Q is initialized as a priority queue with the character C.
Q=C can be performed by using Build_Heap in O(n) time.
For loop takes
(|n|-1) times because each heap operation requires O(log n) time.
Hence the total running time of Huffman code on the set of n
characters is O(n log n).

Method

The following general procedure is applied for construction
a Huffman tree:
Search for the two nodes having the lowest frequency, which
are not yet assigned to a parent node.
Couple these nodes together to a new interior node.
Add both the frequencies and assign this value to the new
interior node.
The procedure has to be repeated until all nodes are
combined together in a root node.

Huffman Coding Example

Construct a Huffman tree by using these nodes.
Value
A
B
C
D
E
F
Frequency
5
25
7
15
4
12

Solution:

Step 1: According
to the Huffman coding we arrange all the elements (values) in ascending order
of the frequencies.
Value
E
A
C
F
D
B
Frequency
4
5
7
12
15
25
Step 2: Insert
first two elements which have smaller frequency.
Huffman Coding Algorithm With Example
Value
C
EA
F
D
B
Frequency
7
9
12
15
25
Step 3: Taking
next smaller number and insert it at correct place.
Huffman Coding Algorithm With Example
Value
F
D
CEA
B
Frequency
12
15
16
25
Step 4: Next
elements are F and D so we construct another subtree for F and D.
Huffman Coding Algorithm With ExampleHuffman Coding Algorithm With Example
Value
CEA
B
FD
Frequency
16
25
27
Step 5: Taking
next value having smaller frequency then add it with CEA and insert it at
correct place.
Huffman Coding Algorithm With Example
Value
FD
CEAB
Frequency
27
41
Step 6: We have
only two values hence we can combined by adding them.
Huffman Coding Algorithm With Example
Huffman Tree

Value
FDCEAB
Frequency
68
Now the list contains only one element i.e. FDCEAB having
frequency 68 and this element (value) becomes the root of the Huffman tree.
If you find anything missing or incorrect in above tutorial
then please mention it by commenting below.

The post Huffman Coding Algorithm With Example appeared first on The Crazy Programmer.

C/C++ Program for First Come First Served (FCFS) Scheduling Algorithm

$
0
0

Here you will get C/C++ program for first come first served (fcfs) scheduling algorithm.

What is First Come First Served (FCFS) Scheduling Algorithm?

First Come First Served (FCFS) is a Non-Preemptive scheduling algorithm. FIFO (First In First Out) strategy assigns priority to process in the order in which they request the processor. The process that requests the CPU first is allocated the CPU first. This is easily implemented with a FIFO queue for managing the tasks. As the process come in, they are put at the end of the queue. As the CPU finishes each task, it removes it from the start of the queue and heads on to the next task.

Also Read: C Program for Shortest Job First (SJF) Scheduling Algorithm

 

C Program

#include<stdio.h>

int main()
{
    int n,bt[20],wt[20],tat[20],avwt=0,avtat=0,i,j;
    printf("Enter total number of processes(maximum 20):");
    scanf("%d",&n);

    printf("\nEnter Process Burst Time\n");
    for(i=0;i<n;i++)
    {
        printf("P[%d]:",i+1);
        scanf("%d",&bt[i]);
    }

    wt[0]=0;    //waiting time for first process is 0

    //calculating waiting time
    for(i=1;i<n;i++)
    {
        wt[i]=0;
        for(j=0;j<i;j++)
            wt[i]+=bt[j];
    }

    printf("\nProcess\t\tBurst Time\tWaiting Time\tTurnaround Time");

    //calculating turnaround time
    for(i=0;i<n;i++)
    {
        tat[i]=bt[i]+wt[i];
        avwt+=wt[i];
        avtat+=tat[i];
        printf("\nP[%d]\t\t%d\t\t%d\t\t%d",i+1,bt[i],wt[i],tat[i]);
    }

    avwt/=i;
    avtat/=i;
    printf("\n\nAverage Waiting Time:%d",avwt);
    printf("\nAverage Turnaround Time:%d",avtat);

    return 0;
}

 

C++ Program

#include<iostream>

using namespace std;

int main()
{
    int n,bt[20],wt[20],tat[20],avwt=0,avtat=0,i,j;
    cout<<"Enter total number of processes(maximum 20):";
    cin>>n;

    cout<<"\nEnter Process Burst Time\n";
    for(i=0;i<n;i++)
    {
        cout<<"P["<<i+1<<"]:";
        cin>>bt[i];
    }

    wt[0]=0;    //waiting time for first process is 0

    //calculating waiting time
    for(i=1;i<n;i++)
    {
        wt[i]=0;
        for(j=0;j<i;j++)
            wt[i]+=bt[j];
    }

    cout<<"\nProcess\t\tBurst Time\tWaiting Time\tTurnaround Time";

    //calculating turnaround time
    for(i=0;i<n;i++)
    {
        tat[i]=bt[i]+wt[i];
        avwt+=wt[i];
        avtat+=tat[i];
        cout<<"\nP["<<i+1<<"]"<<"\t\t"<<bt[i]<<"\t\t"<<wt[i]<<"\t\t"<<tat[i];
    }

    avwt/=i;
    avtat/=i;
    cout<<"\n\nAverage Waiting Time:"<<avwt;
    cout<<"\nAverage Turnaround Time:"<<avtat;

    return 0;
}

 

C/C++ Program for First Come First Served (FCFS) Scheduling Algorithm
Comment below if you found anything incorrect or missing in above fcfs program in C and C++.

The post C/C++ Program for First Come First Served (FCFS) Scheduling Algorithm appeared first on The Crazy Programmer.

C/C++ Program for Priority Scheduling Algorithm

$
0
0

Here you will get C and C++ program for priority scheduling algorithm.

What is Priority Scheduling Algorithm?

In priority scheduling algorithm each process has a priority associated with it and as each process hits the queue, it is stored in based on its priority so that process with higher priority are dealt with first. It should be noted that equal priority processes are scheduled in FCFS order.

Also Read: C Program for Shortest Job First (SJF) Scheduling Algorithm

 

To prevent high priority processes from running indefinitely the scheduler may decrease the priority of the currently running process at each clock tick (i.e., at each clock interrupt). If this action causes its priority to drop below that of the next highest process, a process switch occurs. Alternatively, each process may be assigned a maximum time quantum that it is allowed to run. When this quantum is used up, the next highest priority process is given a chance to run.
 

Limitations

The problem occurs when the operating system gives a particular task a very low priority, so it sits in the queue for a larger amount of time, not being dealt with by the CPU. If this process is something the user needs, there could be a very long wait, this process is known as “Starvation” or “Infinite Blocking”.
 

Solution

Many operating systems use a technique called “aging”, in which a low priority process slowly gains priority over time as it sits in the queue. Even if, the priority of the process is low, there is a surety of its execution.
 

C Program

#include<stdio.h>

int main()
{
    int bt[20],p[20],wt[20],tat[20],pr[20],i,j,n,total=0,pos,temp,avg_wt,avg_tat;
    printf("Enter Total Number of Process:");
    scanf("%d",&n);

    printf("\nEnter Burst Time and Priority\n");
    for(i=0;i<n;i++)
    {
        printf("\nP[%d]\n",i+1);
        printf("Burst Time:");
        scanf("%d",&bt[i]);
        printf("Priority:");
        scanf("%d",&pr[i]);
        p[i]=i+1;           //contains process number
    }

    //sorting burst time, priority and process number in ascending order using selection sort
    for(i=0;i<n;i++)
    {
        pos=i;
        for(j=i+1;j<n;j++)
        {
            if(pr[j]<pr[pos])
                pos=j;
        }

        temp=pr[i];
        pr[i]=pr[pos];
        pr[pos]=temp;

        temp=bt[i];
        bt[i]=bt[pos];
        bt[pos]=temp;

        temp=p[i];
        p[i]=p[pos];
        p[pos]=temp;
    }

    wt[0]=0;	//waiting time for first process is zero

    //calculate waiting time
    for(i=1;i<n;i++)
    {
        wt[i]=0;
        for(j=0;j<i;j++)
            wt[i]+=bt[j];

        total+=wt[i];
    }

    avg_wt=total/n;      //average waiting time
    total=0;

    printf("\nProcess\t    Burst Time    \tWaiting Time\tTurnaround Time");
    for(i=0;i<n;i++)
    {
        tat[i]=bt[i]+wt[i];     //calculate turnaround time
        total+=tat[i];
        printf("\nP[%d]\t\t  %d\t\t    %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);
    }

    avg_tat=total/n;     //average turnaround time
    printf("\n\nAverage Waiting Time=%d",avg_wt);
    printf("\nAverage Turnaround Time=%d\n",avg_tat);

	return 0;
}

 

C++ Program

#include<iostream>

using namespace std;

int main()
{
    int bt[20],p[20],wt[20],tat[20],pr[20],i,j,n,total=0,pos,temp,avg_wt,avg_tat;
    cout<<"Enter Total Number of Process:";
    cin>>n;

    cout<<"\nEnter Burst Time and Priority\n";
    for(i=0;i<n;i++)
    {
        cout<<"\nP["<<i+1<<"]\n";
        cout<<"Burst Time:";
        cin>>bt[i];
        cout<<"Priority:";
        cin>>pr[i];
        p[i]=i+1;           //contains process number
    }

    //sorting burst time, priority and process number in ascending order using selection sort
    for(i=0;i<n;i++)
    {
        pos=i;
        for(j=i+1;j<n;j++)
        {
            if(pr[j]<pr[pos])
                pos=j;
        }

        temp=pr[i];
        pr[i]=pr[pos];
        pr[pos]=temp;

        temp=bt[i];
        bt[i]=bt[pos];
        bt[pos]=temp;

        temp=p[i];
        p[i]=p[pos];
        p[pos]=temp;
    }

    wt[0]=0;            //waiting time for first process is zero

    //calculate waiting time
    for(i=1;i<n;i++)
    {
        wt[i]=0;
        for(j=0;j<i;j++)
            wt[i]+=bt[j];

        total+=wt[i];
    }

    avg_wt=total/n;      //average waiting time
    total=0;

    cout<<"\nProcess\t    Burst Time    \tWaiting Time\tTurnaround Time";
    for(i=0;i<n;i++)
    {
        tat[i]=bt[i]+wt[i];     //calculate turnaround time
        total+=tat[i];
        cout<<"\nP["<<p[i]<<"]\t\t  "<<bt[i]<<"\t\t    "<<wt[i]<<"\t\t\t"<<tat[i];
    }

    avg_tat=total/n;     //average turnaround time
    cout<<"\n\nAverage Waiting Time="<<avg_wt;
    cout<<"\nAverage Turnaround Time="<<avg_tat;

    return 0;
}

 

Output

C/C++ Program for Priority Scheduling Algorithm

The post C/C++ Program for Priority Scheduling Algorithm appeared first on The Crazy Programmer.

Selection Sort in C & C++ – Program & Algorithm

$
0
0
In this tutorial I will explain about algorithm for selection sort in C and C++ using program example. 

 

One of the simplest techniques is a selection sort. As the name suggests, selection sort is the selection of an element and keeping it in sorted order. In selection sort, the strategy is to find the smallest number in the array and exchange it with the value in first position of array. Now, find the second smallest element in the remainder of array and exchange it with a value in the second position, carry on till you have reached the end of array. Now all the elements have been sorted in ascending order.

 

 
 

Algorithm for Selection Sort in C & C++

Let ARR is an array having N elements
1. Read ARR
2. Repeat step 3 to 6 for I=0 to N-1
3. Set MIN=ARR[I] and Set LOC=I
4. Repeat step 5 for J=I+1 to N
5. If MIN>ARR[J], then
                (a) Set MIN=ARR[J]
                (b) Set LOC=J
                [End of if]
  [End of step 4 loop]
6. Interchange ARR[I] and ARR[LOC] using temporary variable
 [End of step 2 outer
loop]
7. Exit
 

Program for Selection Sort in C

#include<stdio.h>

int main()
{
    int i,j,n,loc,temp,min,a[30];
    printf("Enter the number of elements:");
    scanf("%d",&n);
    printf("\nEnter the elements\n");

    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }

    for(i=0;i<n-1;i++)
    {
        min=a[i];
        loc=i;
        for(j=i+1;j<n;j++)
        {
            if(min>a[j])
            {
                min=a[j];
                loc=j;
            }
        }

        temp=a[i];
        a[i]=a[loc];
        a[loc]=temp;
    }

    printf("\nSorted list is as follows\n");
    for(i=0;i<n;i++)
    {
        printf("%d ",a[i]);
    }

    return 0;
}

 

Program for Selection Sort in C++

#include<iostream>

using namespace std;

int main()
{
    int i,j,n,loc,temp,min,a[30];
    cout<<"Enter the number of elements:";
    cin>>n;
    cout<<"\nEnter the elements\n";

    for(i=0;i<n;i++)
    {
        cin>>a[i];
    }

    for(i=0;i<n-1;i++)
    {
        min=a[i];
        loc=i;
        for(j=i+1;j<n;j++)
        {
            if(min>a[j])
            {
                min=a[j];
                loc=j;
            }
        }

        temp=a[i];
        a[i]=a[loc];
        a[loc]=temp;
    }

    cout<<"\nSorted list is as follows\n";
    for(i=0;i<n;i++)
    {
        cout<<a[i]<<" ";
    }

    return 0;
}

 

C/C++ Program and Algorithm for Selection Sort

 

Complexity for Selection Sort in C & C++

The time complexity for selection sort program in C and C++ for both worst case and average case is O (n2) because the number of comparisons for both cases is same.

The post Selection Sort in C & C++ – Program & Algorithm appeared first on The Crazy Programmer.

Insertion Sort in C & C++ – Program & Algorithm

$
0
0
In this tutorial I will explain about algorithm for insertion sort in C and C++ using program example. The insertion sort inserts each element in proper place. The strategy behind the insertion sort is similar to the process of sorting a pack of cards. You can take a card, move it to its location in sequence and move the remaining cards left or right as needed.
 
In insertion sort, we assume that first element A[0] in pass 1 is already sorted. In pass 2 the next second element A[1] is compared with the first one and inserted into its proper place either before or after the first element. In pass 3 the third element A[2] is inserted into its proper place and so on.
 

Algorithm for Insertion Sort in C & C++

Let ARR is an array with N elements
1. Read ARR
2. Repeat step 3 to 8 for I=1 to N-1
3. Set Temp=ARR[I]
4. Set J=I-1
5. Repeat step 6 and 7 while Temp<ARR[J] AND J>=0
6. Set ARR[J+1]=ARR[J] [Moves element forward]
7. Set J=J-1
 [End of step 5 inner
loop]
8. Set ARR[J+1]=Temp [Insert element in proper place]
 [End of step 2 outer
loop]
9. Exit                              
 

Program for Insertion Sort in C

#include<stdio.h>

int main()
{
    int i,j,n,temp,a[30];
    printf("Enter the number of elements:");
    scanf("%d",&n);
    printf("\nEnter the elements\n");

    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }

    for(i=1;i<=n-1;i++)
    {
        temp=a[i];
        j=i-1;

        while((temp<a[j])&&(j>=0))
        {
            a[j+1]=a[j];    //moves element forward
            j=j-1;
        }

        a[j+1]=temp;    //insert element in proper place
    }

    printf("\nSorted list is as follows\n");
    for(i=0;i<n;i++)
    {
        printf("%d ",a[i]);
    }

    return 0;
}

 

Program for Insertion Sort in C++

#include<iostream>

using namespace std;

int main()
{
    int i,j,n,temp,a[30];
    cout<<"Enter the number of elements:";
    cin>>n;
    cout<<"\nEnter the elements\n";

    for(i=0;i<n;i++)
    {
        cin>>a[i];
    }

    for(i=1;i<=n-1;i++)
    {
        temp=a[i];
        j=i-1;

        while((temp<a[j])&&(j>=0))
        {
            a[j+1]=a[j];    //moves element forward
            j=j-1;
        }

        a[j+1]=temp;    //insert element in proper place
    }

    cout<<"\nSorted list is as follows\n";
    for(i=0;i<n;i++)
    {
        cout<<a[i]<<" ";
    }

    return 0;
}

 
C/C++ Program and Algorithm for Insertion Sort

 

Complexity of Insertion Sort in C & C++

There is 1 comparison during pass 1 for proper place. There are 2 comparisons during pass 2 for proper place. There are 3 comparisons during pass 3 for proper place, and so on accordingly.
 
F(n) = 1 + 2 + 3 + . . . . + (n-1) = n (n-1)/2 = O(n2)
 
Hence complexity for insertion sort program in C and C++ is O(n2).

The post Insertion Sort in C & C++ – Program & Algorithm appeared first on The Crazy Programmer.

C Program for N Queens Problem Using Backtracking

$
0
0

N Queens Problem is a famous puzzle in which n-queens are to be placed on a nxn chess board such that no two queens are in the same row, column or diagonal. In this tutorial I am sharing the C program to find solution for N Queens problem using backtracking. Below animation shows the solution for 8 queens problem using backtracking.

Also Read: C Program for Tower of Hanoi Problem

 

8 Queens Problem Using Backtracking
8 Queens Problem Using Backtracking

 

C Program for N Queens Problem Using Backtracking

#include<stdio.h>
#include<math.h>

int board[20],count;

int main()
{
 int n,i,j;
 void queen(int row,int n);

 printf(" - N Queens Problem Using Backtracking -");
 printf("\n\nEnter number of Queens:");
 scanf("%d",&n);
 queen(1,n);
 return 0;
}

//function for printing the solution
void print(int n)
{
 int i,j;
 printf("\n\nSolution %d:\n\n",++count);

 for(i=1;i<=n;++i)
  printf("\t%d",i);

 for(i=1;i<=n;++i)
 {
  printf("\n\n%d",i);
  for(j=1;j<=n;++j) //for nxn board
  {
   if(board[i]==j)
    printf("\tQ"); //queen at i,j position
   else
    printf("\t-"); //empty slot
  }
 }
}

/*funtion to check conflicts
If no conflict for desired postion returns 1 otherwise returns 0*/
int place(int row,int column)
{
 int i;
 for(i=1;i<=row-1;++i)
 {
  //checking column and digonal conflicts
  if(board[i]==column)
   return 0;
  else
   if(abs(board[i]-column)==abs(i-row))
    return 0;
 }

 return 1; //no conflicts
}

//function to check for proper positioning of queen
void queen(int row,int n)
{
 int column;
 for(column=1;column<=n;++column)
 {
  if(place(row,column))
  {
   board[row]=column; //no conflicts so place queen
   if(row==n) //dead end
    print(n); //printing the board configuration
   else //try queen with next position
    queen(row+1,n);
  }
 }
}

 

Output

C Program for N Queens Problem Using Backtracking

The post C Program for N Queens Problem Using Backtracking appeared first on The Crazy Programmer.


C Program for Longest Common Subsequence Problem

$
0
0
In this post I am sharing C program for Longest Common Subsequence Problem.
LCS problem is a dynamic programming approach in which we find the longest subsequence which is common in between two given strings. A subsequence is a sequence which appears in the same order but not necessarily contiguous. For example ACF, AFG, AFGHD, FGH are some subsequences of string ACFGHD. So for a string of length n there can be total 2^n subsequences. The LCS algorithm is widely used in bioinformatics.

 

 

For string ACFGHD and ABFHD, the longest common subsequence is AFHD. The function that is used to find the longest common subsequence of two strings is given below.

 

Longest Common Subsequence Problem

 

Below I have shared the C program for longest common subsequence problem and a video tutorial that will help you understand LCS algorithm easily.

 

C Program for Longest Common Subsequence Problem

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

int i,j,m,n,c[20][20];
char x[20],y[20],b[20][20];

void print(int i,int j)
{
                if(i==0 || j==0)
                                return;
                if(b[i][j]=='c')
                {
                                print(i-1,j-1);
                                printf("%c",x[i-1]);
                }
                else if(b[i][j]=='u')
                                print(i-1,j);
                else
                                print(i,j-1);
}

void lcs()
{
                m=strlen(x);
                n=strlen(y);
                for(i=0;i<=m;i++)
                                c[i][0]=0;
                for(i=0;i<=n;i++)
                                c[0][i]=0;
                                
                //c, u and l denotes cross, upward and downward directions respectively
                for(i=1;i<=m;i++)
                                for(j=1;j<=n;j++)
                                {
                                                if(x[i-1]==y[j-1])
                                                {
                                                                c[i][j]=c[i-1][j-1]+1;
                                                                b[i][j]='c';
                                                }
                                                else if(c[i-1][j]>=c[i][j-1])
                                                {
                                                                c[i][j]=c[i-1][j];
                                                                b[i][j]='u';
                                                }
                                                else
                                                {
                                                                c[i][j]=c[i][j-1];
                                                                b[i][j]='l';
                                                }
                                }
}
 
int main()
{
                printf("Enter 1st sequence:");
                scanf("%s",x);
                printf("Enter 2nd sequence:");
                scanf("%s",y);
                printf("\nThe Longest Common Subsequence is ");
                lcs();
                print(m,n);
		return 0;
}

Output

C Program for Longest Common Subsequence Problem


The post C Program for Longest Common Subsequence Problem appeared first on The Crazy Programmer.

Round Robin Scheduling Program in C

$
0
0

In this tutorial you will learn about round robin scheduling program in C.

Process scheduling is an important component for process management. In a multi-user and a time-sharing system, response time is one of the most important objective to be accomplished.

There are many scheduling algorithms in C for process management such as:

1. First Come First Serve
2. Shortest Job First
3. Priority Scheduling
4. Round Robin Scheduling

However, this tutorial will get you clear with understanding of Round Robin Scheduling program in C.

 

Round Robin Scheduling Algorithm

1. The queue structure in ready queue is of First In First Out (FIFO) type.

2. A fixed time is allotted to every process that arrives in the queue. This fixed time is known as time slice or time quantum.

3. The first process that arrives is selected and sent to the processor for execution. If it is not able to complete its execution within the time quantum provided, then an interrupt is generated using an automated timer.

4. The process is then stopped and is sent back at the end of the queue. However, the state is saved and context is thereby stored in memory. This helps the process to resume from the point where it was interrupted.

5. The scheduler selects another process from the ready queue and dispatches it to the processor for its execution. It is executed until the time Quantum does not exceed.

6. The same steps are repeated until all the process are finished.

The round robin algorithm is simple and the overhead in decision making is very low. It is the best scheduling algorithm for achieving better and evenly distributed response time.

 

Example

Lets take one example to understand it.

Time Quantum = 2

 

Process Burst Time Execution Time
P1 0 9
P2 1 5
P3 2 3
P4 3 4

 

Process Arrival Time Burst Time (x) Turnaround Time(t) Normalized Turnaround Time(t/x) Waiting Time
P1 0 9 21 2.34 12
P2 1 5 17 3.4 12
P3 2 3 11 3.67 8
P4 3 4 12 3 8

Average Turnaround Time = 15.25
Average Normalized Turnaround Time = 3.10
Average Waiting Time = 10

 

Round Robin Scheduling Program in C

#include<stdio.h> 

int main() 
{ 

  int count,j,n,time,remain,flag=0,time_quantum; 
  int wait_time=0,turnaround_time=0,at[10],bt[10],rt[10]; 
  printf("Enter Total Process:\t "); 
  scanf("%d",&n); 
  remain=n; 
  for(count=0;count<n;count++) 
  { 
    printf("Enter Arrival Time and Burst Time for Process Process Number %d :",count+1); 
    scanf("%d",&at[count]); 
    scanf("%d",&bt[count]); 
    rt[count]=bt[count]; 
  } 
  printf("Enter Time Quantum:\t"); 
  scanf("%d",&time_quantum); 
  printf("\n\nProcess\t|Turnaround Time|Waiting Time\n\n"); 
  for(time=0,count=0;remain!=0;) 
  { 
    if(rt[count]<=time_quantum && rt[count]>0) 
    { 
      time+=rt[count]; 
      rt[count]=0; 
      flag=1; 
    } 
    else if(rt[count]>0) 
    { 
      rt[count]-=time_quantum; 
      time+=time_quantum; 
    } 
    if(rt[count]==0 && flag==1) 
    { 
      remain--; 
      printf("P[%d]\t|\t%d\t|\t%d\n",count+1,time-at[count],time-at[count]-bt[count]); 
      wait_time+=time-at[count]-bt[count]; 
      turnaround_time+=time-at[count]; 
      flag=0; 
    } 
    if(count==n-1) 
      count=0; 
    else if(at[count+1]<=time) 
      count++; 
    else 
      count=0; 
  } 
  printf("\nAverage Waiting Time= %f\n",wait_time*1.0/n); 
  printf("Avg Turnaround Time = %f",turnaround_time*1.0/n); 
  
  return 0; 
}

 

Output

Round Robin Scheduling Program in C

 

If you found anything incorrect or have any doubts regarding above round robin scheduling program in C then comment below.

The post Round Robin Scheduling Program in C appeared first on The Crazy Programmer.

Banker’s Algorithm in C

$
0
0

Here you will get program for banker’s algorithm in C.

The banker’s algorithm  which is also known as avoidance algorithm is a deadlock detection algorithm. It was developed by Edsger Dijkstra. It is designed to check the safe state whenever a resource is requested. It takes analogy of bank, where customer request to withdraw cash. Based on some data the cash is lent to the customer. The banker can’t give more cash than what the customer has requested for, and the total available cash.  As this algorithm uses bank analogy so named as banker’s algorithm

Banker’s Algorithm in C

The basic data structures used to implement this algorithm are given below.

Let n be the total number of processes and m be the total number of resource types in the system.

Available: A vector of length m. It shows number of available resources of each type. If Available[i] = k, then k instances of resource Ri are available.

Max: An n×m matrix that contain maximum demand of each process. If Max[i,j] = k, then process Pi can request maximum k instances of resource type Rj.

Allocation: An n×m matrix that contain number of resources of each type currently allocated to each process. If Allocation[i,j] = k, then Pi is currently allocated k instances of resource type Rj.

Need: An n×m matrix that shows the remaining resource need of each process. If Need[i,j] = k, then process Pi may need k more instances of resource type Rj to complete the task.

Program for Banker’s Algorithm in C

#include <stdio.h>

int current[5][5], maximum_claim[5][5], available[5];
int allocation[5] = {0, 0, 0, 0, 0};
int maxres[5], running[5], safe = 0;
int counter = 0, i, j, exec, resources, processes, k = 1;

int main()
{
	printf("\nEnter number of processes: ");
    	scanf("%d", &processes);

    	for (i = 0; i < processes; i++) 
	{
        	running[i] = 1;
        	counter++;
    	}

    	printf("\nEnter number of resources: ");
    	scanf("%d", &resources);

    	printf("\nEnter Claim Vector:");
    	for (i = 0; i < resources; i++) 
	{ 
	        scanf("%d", &maxres[i]);
    	}

   	printf("\nEnter Allocated Resource Table:\n");
    	for (i = 0; i < processes; i++) 
	{
	        for(j = 0; j < resources; j++) 
		{
  			scanf("%d", &current[i][j]);
        	}
    	}

    	printf("\nEnter Maximum Claim Table:\n");
    	for (i = 0; i < processes; i++) 
	{
        	for(j = 0; j < resources; j++) 
		{
            		scanf("%d", &maximum_claim[i][j]);
        	}
    	}

	printf("\nThe Claim Vector is: ");
    	for (i = 0; i < resources; i++) 
	{
	        printf("\t%d", maxres[i]);
	}

    	printf("\nThe Allocated Resource Table:\n");
    	for (i = 0; i < processes; i++) 
	{
	        for (j = 0; j < resources; j++) 
		{
            		printf("\t%d", current[i][j]);
        	}
		printf("\n");
    	}

    	printf("\nThe Maximum Claim Table:\n");
    	for (i = 0; i < processes; i++) 
	{
        	for (j = 0; j < resources; j++) 
		{
		        printf("\t%d", maximum_claim[i][j]);
        	}
        	printf("\n");
    	}

    	for (i = 0; i < processes; i++) 
	{
        	for (j = 0; j < resources; j++) 
		{
            		allocation[j] += current[i][j];
        	}
    	}

    	printf("\nAllocated resources:");
    	for (i = 0; i < resources; i++) 
	{
        	printf("\t%d", allocation[i]);
    	}

    	for (i = 0; i < resources; i++) 
	{
	        available[i] = maxres[i] - allocation[i];
	}

    	printf("\nAvailable resources:");
    	for (i = 0; i < resources; i++) 
	{
        	printf("\t%d", available[i]);
    	}
    	printf("\n");

    	while (counter != 0) 
	{
        	safe = 0;
        	for (i = 0; i < processes; i++) 
		{
            		if (running[i]) 
			{
                		exec = 1;
                		for (j = 0; j < resources; j++) 
				{
                    			if (maximum_claim[i][j] - current[i][j] > available[j]) 
					{
                        			exec = 0;
                        			break;
                    			}
                		}
                		if (exec) 
				{
                    			printf("\nProcess%d is executing\n", i + 1);
                    			running[i] = 0;
                    			counter--;
                    			safe = 1;

                    			for (j = 0; j < resources; j++) 
					{
                        			available[j] += current[i][j];
                    			}
			                break;
                		}
            		}
        	}
        	if (!safe) 
		{
            		printf("\nThe processes are in unsafe state.\n");
            		break;
        	} 
		else 
		{
            		printf("\nThe process is in safe state");
            		printf("\nAvailable vector:");

            		for (i = 0; i < resources; i++) 
			{
                		printf("\t%d", available[i]);
            		}

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

If you found anything incorrect in above program for banker’s algorithm in C then comment below.

Source: https://en.wikipedia.org/wiki/Banker%27s_algorithm

The post Banker’s Algorithm in C appeared first on The Crazy Programmer.

Counting Sort in C

$
0
0
Here you will learn about counting sort in C

 

Counting sort algorithm is a sorting algorithm which do not involve comparison between elements of an array. In this tutorial I am sharing counting sort program in C. Steps that I am doing to sort the elements are given below.

1. First of all I am reading n elements in array a[]. While reading the array elements I have also calculated the maximum element.

2. Now the actual sorting is done in counting_sort() function. Here I am counting the occurrence of each element in the array a[] and then storing it at the index equal to the value of that element. For example occurrence of element 5 will be stored at index 5, occurrence of element 9 will be stored at index 9 and so on.

3. As the value at each index in count[] array is the occurrence of that index or element, so the elements are printed in ascending order by printing each index number of times equal to its corresponding value.

Also Read: Merge Sort in C

Counting Sort Algorithm, Counting Sort Program in C, Counting Sort Example
Counting Sort Example – Image Source

I have also added a video tutorial below that will help you to understand the counting sort algorithm easily. If you are facing any problem then ask it in the comment section.

Program for Counting Sort in C

#include<stdio.h>

void counting_sort(int a[],int n,int max)
{
     int count[50]={0},i,j;
     
     for(i=0;i<n;++i)
      count[a[i]]=count[a[i]]+1;
      
     printf("\nSorted elements are:");
     
     for(i=0;i<=max;++i)
      for(j=1;j<=count[i];++j)
       printf("%d ",i);
}

int main()
{
    int a[50],n,i,max=0;
    printf("Enter number of elements:");
    scanf("%d",&n);
    printf("\nEnter elements:");
                  
    for(i=0;i<n;++i)
    {
     scanf("%d",&a[i]);
     if(a[i]>max)
      max=a[i];
    }
     
    counting_sort(a,n,max);
    return 0;
}

 

Output

Counting Sort Algorithm, Counting Sort Program in C, Counting Sort Example
If you found any mistake or anything missing in above tutorial for counting sort in C then please mention it by commenting below.

The post Counting Sort in C appeared first on The Crazy Programmer.

Producer Consumer Problem in C

$
0
0

Here you will learn about producer consumer problem in C.

Producer consumer problem is also known as bounded buffer problem. In this problem we have two processes, producer and consumer, who share a fixed size buffer. Producer work is to produce data or items and put in buffer. Consumer work is to remove data from buffer and consume it. We have to make sure that producer do not produce data when buffer is full and consumer do not remove data when buffer is empty.

Also Read: Banker’s Algorithm in C

The producer should go to sleep when buffer is full. Next time when consumer removes data it notifies the producer and producer starts producing data again. The consumer should go to sleep when buffer is empty. Next time when producer add data it notifies the consumer and consumer starts consuming data. This solution can be achieved using semaphores.

producer consumer problem in c

Image Source

You can watch below video to learn more about this problem.

Producer Consumer Problem in C

Below is the program to implement this problem.

#include<stdio.h>

int mutex=1,full=0,empty=3,x=0;

int main()
{
	int n;
	void producer();
	void consumer();
	int wait(int);
	int signal(int);
	printf("\n1.Producer\n2.Consumer\n3.Exit");
	while(1)
	{
		printf("\nEnter your choice:");
		scanf("%d",&n);
		switch(n)
		{
			case 1:	if((mutex==1)&&(empty!=0))
						producer();
					else
						printf("Buffer is full!!");
					break;
			case 2:	if((mutex==1)&&(full!=0))
						consumer();
					else
						printf("Buffer is empty!!");
					break;
			case 3:
					exit(0);
					break;
		}
	}
	
	return 0;
}

int wait(int s)
{
	return (--s);
}

int signal(int s)
{
	return(++s);
}

void producer()
{
	mutex=wait(mutex);
	full=signal(full);
	empty=wait(empty);
	x++;
	printf("\nProducer produces the item %d",x);
	mutex=signal(mutex);
}

void consumer()
{
	mutex=wait(mutex);
	full=wait(full);
	empty=signal(empty);
	printf("\nConsumer consumes item %d",x);
	x--;
	mutex=signal(mutex);
}

 

Output

1.Producer
2.Consumer
3.Exit
Enter your choice:1

Producer produces the item 1
Enter your choice:2

Consumer consumes item 1
Enter your choice:2
Buffer is empty!!
Enter your choice:1

Producer produces the item 1
Enter your choice:1

Producer produces the item 2
Enter your choice:1

Producer produces the item 3
Enter your choice:1
Buffer is full!!
Enter your choice:3

The post Producer Consumer Problem in C appeared first on The Crazy Programmer.

LRU Page Replacement Algorithm in C

$
0
0

Here you will get program for lru page replacement algorithm in C.

Least Recently Used (LRU) page replacement algorithm works on the concept that the pages that are heavily used in previous instructions are likely to be used heavily in next instructions. And the page that are used very less are likely to be used less in future. Whenever a page fault occurs, the page that is least recently used is removed from the memory frames. Page fault occurs when a referenced page in not found in the memory frames.

Also Read: LRU Page Replacement Algorithm in C

Below program shows how to implement this algorithm in C.

Program for LRU Page Replacement Algorithm in C

#include<stdio.h>

int findLRU(int time[], int n){
	int i, minimum = time[0], pos = 0;

	for(i = 1; i < n; ++i){
		if(time[i] < minimum){
			minimum = time[i];
			pos = i;
		}
	}
	
	return pos;
}

int main()
{
    int no_of_frames, no_of_pages, frames[10], pages[30], counter = 0, time[10], flag1, flag2, i, j, pos, faults = 0;
	printf("Enter number of frames: ");
	scanf("%d", &no_of_frames);
	
	printf("Enter number of pages: ");
	scanf("%d", &no_of_pages);
	
	printf("Enter reference string: ");
	
    for(i = 0; i < no_of_pages; ++i){
    	scanf("%d", &pages[i]);
    }
    
	for(i = 0; i < no_of_frames; ++i){
    	frames[i] = -1;
    }
    
    for(i = 0; i < no_of_pages; ++i){
    	flag1 = flag2 = 0;
    	
    	for(j = 0; j < no_of_frames; ++j){
    		if(frames[j] == pages[i]){
	    		counter++;
	    		time[j] = counter;
	   			flag1 = flag2 = 1;
	   			break;
   			}
    	}
    	
    	if(flag1 == 0){
			for(j = 0; j < no_of_frames; ++j){
	    		if(frames[j] == -1){
	    			counter++;
	    			faults++;
	    			frames[j] = pages[i];
	    			time[j] = counter;
	    			flag2 = 1;
	    			break;
	    		}
    		}	
    	}
    	
    	if(flag2 == 0){
    		pos = findLRU(time, no_of_frames);
    		counter++;
    		faults++;
    		frames[pos] = pages[i];
    		time[pos] = counter;
    	}
    	
    	printf("\n");
    	
    	for(j = 0; j < no_of_frames; ++j){
    		printf("%d\t", frames[j]);
    	}
	}
	
	printf("\n\nTotal Page Faults = %d", faults);
    
    return 0;
}

Output

Enter number of frames: 3
Enter number of pages: 6
Enter reference string: 5 7 5 6 7 3

5 -1 -1
5 7 -1
5 7 -1
5 7 6
5 7 6
3 7 6

Total Page Faults = 4

Video Tutorial

Comment below if you have doubts or found anything incorrect in above lru page replacement algorithm in C.

The post LRU Page Replacement Algorithm in C appeared first on The Crazy Programmer.

Optimal Page Replacement Algorithm in C

$
0
0

Here you will get program for optimal page replacement algorithm in C.

Optimal page replacement algorithm says that if page fault occurs then that page should be removed that will not be used for maximum time in future.

It is also known as clairvoyant replacement algorithm or Bélády’s optimal page replacement policy.

Also Read: LRU Page Replacement Algorithm in C

Video Tutorial

Below program shows how to implement this algorithm in C.

Program for Optimal Page Replacement Algorithm in C

#include<stdio.h>
 
int main()
{
    int no_of_frames, no_of_pages, frames[10], pages[30], temp[10], flag1, flag2, flag3, i, j, k, pos, max, faults = 0;
    printf("Enter number of frames: ");
    scanf("%d", &no_of_frames);
    
    printf("Enter number of pages: ");
    scanf("%d", &no_of_pages);
    
    printf("Enter page reference string: ");
    
    for(i = 0; i < no_of_pages; ++i){
        scanf("%d", &pages[i]);
    }
    
    for(i = 0; i < no_of_frames; ++i){
        frames[i] = -1;
    }
    
    for(i = 0; i < no_of_pages; ++i){
        flag1 = flag2 = 0;
        
        for(j = 0; j < no_of_frames; ++j){
            if(frames[j] == pages[i]){
                   flag1 = flag2 = 1;
                   break;
               }
        }
        
        if(flag1 == 0){
            for(j = 0; j < no_of_frames; ++j){
                if(frames[j] == -1){
                    faults++;
                    frames[j] = pages[i];
                    flag2 = 1;
                    break;
                }
            }    
        }
        
        if(flag2 == 0){
        	flag3 =0;
        	
            for(j = 0; j < no_of_frames; ++j){
            	temp[j] = -1;
            	
            	for(k = i + 1; k < no_of_pages; ++k){
            		if(frames[j] == pages[k]){
            			temp[j] = k;
            			break;
            		}
            	}
            }
            
            for(j = 0; j < no_of_frames; ++j){
            	if(temp[j] == -1){
            		pos = j;
            		flag3 = 1;
            		break;
            	}
            }
            
            if(flag3 ==0){
            	max = temp[0];
            	pos = 0;
            	
            	for(j = 1; j < no_of_frames; ++j){
            		if(temp[j] > max){
            			max = temp[j];
            			pos = j;
            		}
            	}            	
            }
			
			frames[pos] = pages[i];
			faults++;
        }
        
        printf("\n");
        
        for(j = 0; j < no_of_frames; ++j){
            printf("%d\t", frames[j]);
        }
    }
    
    printf("\n\nTotal Page Faults = %d", faults);
    
    return 0;
}

Output

Enter number of frames: 3
Enter number of pages: 10
Enter page reference string: 2 3 4 2 1 3 7 5 4 3

2 -1 -1
2 3 -1
2 3 4
2 3 4
1 3 4
1 3 4
7 3 4
5 3 4
5 3 4
5 3 4

Comment below if you have doubts or found anything incorrect in above optimal page replacement algorithm in C.

The post Optimal Page Replacement Algorithm in C appeared first on The Crazy Programmer.


Caesar Cipher in C and C++ [Encryption & Decryption]

$
0
0

Get program for caesar cipher in C and C++ for encryption and decryption.

What is Caesar Cipher?

It is one of the simplest encryption technique in which each character in plain text is replaced by a character some fixed number of positions down to it.

For example, if key is 3 then we have to replace character by another character that is 3 position down to it. Like A will be replaced by D, C will be replaced by F and so on.

For decryption just follow the reverse of encryption process.

Caesar Cipher in C and C++ [Encryption & Decryption]

Below I have shared program to implement caesar cipher in C and C++.

Program for Caesar Cipher in C

Encryption

#include<stdio.h>

int main()
{
	char message[100], ch;
	int i, key;
	
	printf("Enter a message to encrypt: ");
	gets(message);
	printf("Enter key: ");
	scanf("%d", &key);
	
	for(i = 0; message[i] != '\0'; ++i){
		ch = message[i];
		
		if(ch >= 'a' && ch <= 'z'){
			ch = ch + key;
			
			if(ch > 'z'){
				ch = ch - 'z' + 'a' - 1;
			}
			
			message[i] = ch;
		}
		else if(ch >= 'A' && ch <= 'Z'){
			ch = ch + key;
			
			if(ch > 'Z'){
				ch = ch - 'Z' + 'A' - 1;
			}
			
			message[i] = ch;
		}
	}
	
	printf("Encrypted message: %s", message);
	
	return 0;
}

Output

Enter a message to encrypt: axzd
Enter key: 4
Encrypted message: ebdh

Decryption

#include<stdio.h>

int main()
{
	char message[100], ch;
	int i, key;
	
	printf("Enter a message to decrypt: ");
	gets(message);
	printf("Enter key: ");
	scanf("%d", &key);
	
	for(i = 0; message[i] != '\0'; ++i){
		ch = message[i];
		
		if(ch >= 'a' && ch <= 'z'){
			ch = ch - key;
			
			if(ch < 'a'){
				ch = ch + 'z' - 'a' + 1;
			}
			
			message[i] = ch;
		}
		else if(ch >= 'A' && ch <= 'Z'){
			ch = ch - key;
			
			if(ch < 'A'){
				ch = ch + 'Z' - 'A' + 1;
			}
			
			message[i] = ch;
		}
	}
	
	printf("Decrypted message: %s", message);
	
	return 0;
}

Output

Enter a message to decrypt: ebdh
Enter key: 4
Decrypted message: axzd

Program for Caesar Cipher in C++

Encryption

#include<iostream>

using namespace std;

int main()
{
	char message[100], ch;
	int i, key;
	
	cout << "Enter a message to encrypt: ";
	cin.getline(message, 100);
	cout << "Enter key: ";
	cin >> key;
	
	for(i = 0; message[i] != '\0'; ++i){
		ch = message[i];
		
		if(ch >= 'a' && ch <= 'z'){
			ch = ch + key;
			
			if(ch > 'z'){
				ch = ch - 'z' + 'a' - 1;
			}
			
			message[i] = ch;
		}
		else if(ch >= 'A' && ch <= 'Z'){
			ch = ch + key;
			
			if(ch > 'Z'){
				ch = ch - 'Z' + 'A' - 1;
			}
			
			message[i] = ch;
		}
	}
	
	cout << "Encrypted message: " << message;
	
	return 0;
}

Output

Enter a message to encrypt: asd zf
Enter key: 3
Encrypted message: dvg ci

Decryption

#include<iostream>

using namespace std;

int main()
{
	char message[100], ch;
	int i, key;
	
	cout << "Enter a message to decrypt: ";
	cin.getline(message, 100);
	cout << "Enter key: ";
	cin >> key;
	
	for(i = 0; message[i] != '\0'; ++i){
		ch = message[i];
		
		if(ch >= 'a' && ch <= 'z'){
			ch = ch - key;
			
			if(ch < 'a'){
				ch = ch + 'z' - 'a' + 1;
			}
			
			message[i] = ch;
		}
		else if(ch >= 'A' && ch <= 'Z'){
			ch = ch - key;
			
			if(ch > 'a'){
				ch = ch + 'Z' - 'A' + 1;
			}
			
			message[i] = ch;
		}
	}
	
	cout << "Decrypted message: " << message;
	
	return 0;
}

Output

Enter a message to decrypt: az GjK
Enter key: 2
Decrypted message: yx EhI

Comment below if you have doubts or found anything incorrect in above program for caesar cipher in C and C++.

The post Caesar Cipher in C and C++ [Encryption & Decryption] appeared first on The Crazy Programmer.

Best Fit Algorithm in C and C++

$
0
0

Here you will learn about best fit algorithm in C and C++ with program example.

Memory Management is one of the services provided by OS which is needed for Optimized memory usage of the available memory in a Computer System.

For this purpose OS uses 3 methods:-

  1. First Fit
  2. Best Fit
  3. Worst Fit

In this section we will talk about Best Fit Memory Management Scheme.

What is Best Fit Memory Management Scheme?

Best fit uses the best memory block based on the Process memory request. In best fit implementation the algorithm first selects the smallest block which can adequately fulfill the memory request by the respective process.
Because of this memory is utilized optimally but as it compares the blocks with the requested memory size it increases the time requirement and hence slower than other methods. It suffers from Internal Fragmentation which simply means that the memory block size is greater than the memory requested by the process, then the free space gets wasted.

Once we encounter a process that requests a memory which is higher than block size we stop the algorithm.

Best Fit Algorithm

  1. Get no. of Processes and no. of blocks.
  2. After that get the size of each block and process requests.
  3. Then select the best memory block that can be allocated using the above definition.
  4. Display the processes with the blocks that are allocated to a respective process.
  5. Value of Fragmentation is optional to display to keep track of wasted memory.
  6. Stop.

Program for Best Fit Algorithm in C

#include<stdio.h>

void main()
{
	int fragment[20],b[20],p[20],i,j,nb,np,temp,lowest=9999;
	static int barray[20],parray[20];
	
	printf("\n\t\t\tMemory Management Scheme - Best Fit");
	printf("\nEnter the number of blocks:");
	scanf("%d",&nb);
	printf("Enter the number of processes:");
	scanf("%d",&np);
	
	printf("\nEnter the size of the blocks:-\n");
	for(i=1;i<=nb;i++)
    {
		printf("Block no.%d:",i);
        scanf("%d",&b[i]);
    }
	
	printf("\nEnter the size of the processes :-\n");
	for(i=1;i<=np;i++)
    {
        printf("Process no.%d:",i);
        scanf("%d",&p[i]);
    }
	
	for(i=1;i<=np;i++)
	{
		for(j=1;j<=nb;j++)
		{
			if(barray[j]!=1)
			{
				temp=b[j]-p[i];
				if(temp>=0)
					if(lowest>temp)
					{
						parray[i]=j;
						lowest=temp;
					}
			}
		}
		
		fragment[i]=lowest;
		barray[parray[i]]=1;
		lowest=10000;
	}
	
	printf("\nProcess_no\tProcess_size\tBlock_no\tBlock_size\tFragment");
	for(i=1;i<=np && parray[i]!=0;i++)
		printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,p[i],parray[i],b[parray[i]],fragment[i]);
}

Program for Best Fit Algorithm in C++

#include<iostream>

using namespace std;

int main()
{
	int fragment[20],b[20],p[20],i,j,nb,np,temp,lowest=9999;
	static int barray[20],parray[20];
	cout<<"\n\t\t\tMemory Management Scheme - Best Fit";
	cout<<"\nEnter the number of blocks:";
	cin>>nb;
	cout<<"Enter the number of processes:";
	cin>>np;
	
	cout<<"\nEnter the size of the blocks:-\n";
	for(i=1;i<=nb;i++)
    {
        cout<<"Block no."<<i<<":";
        cin>>b[i];
    }
	
	cout<<"\nEnter the size of the processes :-\n";
	for(i=1;i<=np;i++)
    {
        cout<<"Process no. "<<i<<":";
        cin>>p[i];
    }
	
	for(i=1;i<=np;i++)
	{
		for(j=1;j<=nb;j++)
		{
			if(barray[j]!=1)
			{
				temp=b[j]-p[i];
				if(temp>=0)
					if(lowest>temp)
					{
						parray[i]=j;
						lowest=temp;
					}
			}
		}
		
		fragment[i]=lowest;
		barray[parray[i]]=1;
		lowest=10000;
	}
	
	cout<<"\nProcess_no\tProcess_size\tBlock_no\tBlock_size\tFragment";
	for(i=1;i<=np && parray[i]!=0;i++)
		cout<<"\n"<<i<<"\t\t"<<p[i]<<"\t\t"<<parray[i]<<"\t\t"<<b[parray[i]]<<"\t\t"<<fragment[i];
	
	return 0;
}

Output

Best Fit Algorithm in C and C++

Comment below if you have any doubts related to above best fit algorithm in C and C++.

The post Best Fit Algorithm in C and C++ appeared first on The Crazy Programmer.

First Fit Algorithm in C and C++

$
0
0

Here you will learn about first fit algorithm in C and C++ with program examples.

There are various memory management schemes in operating system like first fit, best fit and worst fit. In this section we will talk about first fit scheme.

What is First Fit Memory Management Scheme?

In this scheme we check the blocks in a sequential manner which means we pick the first process then compare it’s size with first block size if it is less than size of block it is allocated otherwise we move to second block and so on.

When first process is allocated we move on to the next process until all processes are allocated.

Also Read: Best Fit Algorithm in C and C++

First Fit Algorithm

  1. Get no. of Processes and no. of blocks.
  2. After that get the size of each block and process requests.
  3. Now allocate processes
    if(block size >= process size)
    //allocate the process
    else
    //move on to next block
  4. Display the processes with the blocks that are allocated to a respective process.
  5. Stop.

Program for First Fit Algorithm in C

#include<stdio.h>

void main()
{
	int bsize[10], psize[10], bno, pno, flags[10], allocation[10], i, j;

	for(i = 0; i < 10; i++)
	{
		flags[i] = 0;
		allocation[i] = -1;
	}
	
	printf("Enter no. of blocks: ");
	scanf("%d", &bno);
	
	printf("\nEnter size of each block: ");
	for(i = 0; i < bno; i++)
		scanf("%d", &bsize[i]);

	printf("\nEnter no. of processes: ");
	scanf("%d", &pno);
	
	printf("\nEnter size of each process: ");
	for(i = 0; i < pno; i++)
		scanf("%d", &psize[i]);
	for(i = 0; i < pno; i++)         //allocation as per first fit
		for(j = 0; j < bno; j++)
			if(flags[j] == 0 && bsize[j] >= psize[i])
			{
				allocation[j] = i;
				flags[j] = 1;
				break;
			}
	
	//display allocation details
	printf("\nBlock no.\tsize\t\tprocess no.\t\tsize");
	for(i = 0; i < bno; i++)
	{
		printf("\n%d\t\t%d\t\t", i+1, bsize[i]);
		if(flags[i] == 1)
			printf("%d\t\t\t%d",allocation[i]+1,psize[allocation[i]]);
		else
			printf("Not allocated");
	}
}

Program for First Fit Algorithm in C++

#include<iostream>

using namespace std;

int main()
{
	int bsize[10], psize[10], bno, pno, flags[10], allocation[10], i, j;

	for(i = 0; i < 10; i++)
	{
		flags[i] = 0;
		allocation[i] = -1;
	}
	
	cout<<"Enter no. of blocks: ";
	cin>>bno;
	
	cout<<"\nEnter size of each block: ";
	for(i = 0; i < bno; i++)
		cin>>bsize[i];

	cout<<"\nEnter no. of processes: ";
	cin>>pno;
	
	cout<<"\nEnter size of each process: ";
	for(i = 0; i < pno; i++)
		cin>>psize[i];
	for(i = 0; i < pno; i++)         //allocation as per first fit
		for(j = 0; j < bno; j++)
			if(flags[j] == 0 && bsize[j] >= psize[i])
			{
				allocation[j] = i;
				flags[j] = 1;
				break;
			}
	
	//display allocation details
	cout<<"\nBlock no.\tsize\t\tprocess no.\t\tsize";
	for(i = 0; i < bno; i++)
	{
		cout<<"\n"<< i+1<<"\t\t"<<bsize[i]<<"\t\t";
		if(flags[i] == 1)
			cout<<allocation[i]+1<<"\t\t\t"<<psize[allocation[i]];
		else
			cout<<"Not allocated";
	}
	
	return 0;
}

Output

First Fit Algorithm in C and C++

Comment below if have any queries or found any information incorrect in above first fit algorithm in C and C++.

The post First Fit Algorithm in C and C++ appeared first on The Crazy Programmer.

Checksum Program in C and C++

$
0
0

Here you will get checksum program in C and C++.

A checksum is a error detection method in Data Communication. It is used for errors which may have been introduced during transmission or storage. It is usually applied to an installation file after it is received from the download server.

The actual procedure which yields the checksum, given a data input is called a checksum function or checksum algorithm.

Checksum method can only detect errors but is unable to correct the error.

In this method a checksum is calculated based on the given binary strings which is sent with the data as redundant bits. This data + checksum is received at receiver end and checksum is calculated again, if checksum is 0 it means no error in data received, else there exists some error in the received data.

For the purpose of this program we are finding checksum for 2 binary strings.

Checksum Algorithm

  1. Take 2 binary input strings.
  2. Do their binary sum to find out the checksum which will be sent to the destination or to the receiver.
  3. In binary sum there are 6 cases:-
    1. If both bits are 0 and carry is 0, sum=0 and carry=0
    2. If both bits are 0 and carry is 1,sum=1 and carry=0
    3. If both bits are 1 and carry is 0,sum=0 and carry=1
    4. If both bits are 1 and carry is 1,sum=1 and carry=1
    5. If either bit is 1 and carry is 0,sum=1 and carry=0
    6. If either bit is 1 and carry is 1,sum=0 and carry=1
  4. While doing the addition we have to add the binary strings from rightmost end i.e LSB to MSB.
  5. When binary sum is done 1’s complement of it is taken by reversing 1’s to 0’s and vice versa.
  6. The resulting 1’s complement is the Checksum.
  7. Stop.

Checksum Program in C

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

int main()
{
    char a[20],b[20];
    char sum[20],complement[20];
    int i,length;
    
	printf("Enter first binary string\n");
    scanf("%s",&a);
    printf("Enter second binary string\n");
    scanf("%s",&b);
    
    if(strlen(a)==strlen(b)){
		length = strlen(a);
		char carry='0';
        
		for(i=length-1;i>=0;i--)
        {
			if(a[i]=='0' && b[i]=='0' && carry=='0')
            {
                sum[i]='0';
                carry='0';
            }
            else if(a[i]=='0' && b[i]=='0' && carry=='1')
            {
                sum[i]='1';
                carry='0';

            }
            else if(a[i]=='0' && b[i]=='1' && carry=='0')
            {
                sum[i]='1';
                carry='0';

            }
            else if(a[i]=='0' && b[i]=='1' && carry=='1')
            {
                sum[i]='0';
                carry='1';

            }
            else if(a[i]=='1' && b[i]=='0' && carry=='0')
            {
                sum[i]='1';
                carry='0';

            }
            else if(a[i]=='1' && b[i]=='0' && carry=='1')
            {
                sum[i]='0';
                carry='1';

            }
            else if(a[i]=='1' && b[i]=='1' && carry=='0')
            {
                sum[i]='0';
                carry='1';

            }
            else if(a[i]=='1' && b[i]=='1' && carry=='1')
            {
                sum[i]='1';
                carry='1';

            }
            else
                break;
        }
        
		printf("\nSum=%c%s",carry,sum);
		
		for(i=0;i<length;i++)
        {
            if(sum[i]=='0')
                complement[i]='1';
            else
                complement[i]='0';
        }
        
        if(carry=='1')
            carry='0';
        else
            carry='1';
        
		printf("\nChecksum=%c%s",carry,complement);
	}
	else {
		printf("\nWrong input strings");
	}
}

Checksum Program in C++

#include<iostream>
#include<string.h>

using namespace std;

int main()
{
    char a[20],b[20];
    char sum[20],complement[20];
    int i;
    
	cout<<"Enter first binary string\n";
    cin>>a;
    cout<<"Enter second binary string\n";
    cin>>b;
    
	if(strlen(a)==strlen(b))
    {
        char carry='0';
        int length=strlen(a);
        
		for(i=length-1;i>=0;i--)
        {
            if(a[i]=='0' && b[i]=='0' && carry=='0')
            {
                sum[i]='0';
                carry='0';
            }
            else if(a[i]=='0' && b[i]=='0' && carry=='1')
            {
                sum[i]='1';
                carry='0';

            }
            else if(a[i]=='0' && b[i]=='1' && carry=='0')
            {
                sum[i]='1';
                carry='0';

            }
            else if(a[i]=='0' && b[i]=='1' && carry=='1')
            {
                sum[i]='0';
                carry='1';

            }
            else if(a[i]=='1' && b[i]=='0' && carry=='0')
            {
                sum[i]='1';
                carry='0';

            }
            else if(a[i]=='1' && b[i]=='0' && carry=='1')
            {
                sum[i]='0';
                carry='1';

            }
            else if(a[i]=='1' && b[i]=='1' && carry=='0')
            {
                sum[i]='0';
                carry='1';

            }
            else if(a[i]=='1' && b[i]=='1' && carry=='1')
            {
                sum[i]='1';
                carry='1';

            }
            else
                break;
        }
        cout<<"\nSum="<<carry<<sum;

        for(i=0;i<length;i++)
        {
            if(sum[i]=='0')
                complement[i]='1';
            else
                complement[i]='0';
        }
        
		if(carry=='1')
            carry='0';
        else
            carry='1';
     
	    cout<<"\nChecksum="<<carry<<complement;
    }
    else
        cout<<"\nWrong input strings";
        
    return 0;
}

Output

Checksum Program in C and C++

This article is submitted by Rahul Maheshwari. You can connect with him on facebook.

Comment below if you have queries or found anything incorrect in above checksum program in C and C++.

The post Checksum Program in C and C++ appeared first on The Crazy Programmer.

Bucket Sort in C and C++

$
0
0

Here you will get program for bucket sort in C and C++.

In bucket sort algorithm the array elements are distributed into a number of buckets. Then each bucket sorted individually either using any other sorting algorithm or by recursively applying bucket sort.

Take example shown in below image.

Bucket Sort

Elements are distributed among buckets

Bucket Sort

Then, elements are sorted within each bucket

Below is the program to implement this algorithm. In this program it is assumed that the array elements are between 0 to 10.

Program for Bucket Sort in C

#include<stdio.h>

#define SIZE 10

void bucketSort(int a[], int n) {
	int i, j, k, buckets[SIZE];
	
	for(i = 0; i < SIZE; ++i)
		buckets[i] = 0;
	
	for(i = 0; i < n; ++i)
		++buckets[a[i]];
		
	for(i = 0, j = 0; j < SIZE; ++j)
		for(k = buckets[j]; k > 0; --k)
			a[i++] = j;
}

int main() {
	int i, a[] = {3, 6, 5, 1, 8, 4, 3, 1}, n = 8;
	
	printf("Before sorting:\n");
	for(i = 0; i < n; ++i)
		printf("%d ", a[i]);
	
	bucketSort(a, 8);
	
	printf("\n\nAfter sorting:\n");
	for(i = 0; i < n; ++i)
		printf("%d ", a[i]);
	
	return 0;
}

Program for Bucket Sort in C++

#include<iostream>

#define SIZE 10

using namespace std;

void bucketSort(int a[], int n) {
	int i, j, k, buckets[SIZE];
	
	for(i = 0; i < SIZE; ++i)
		buckets[i] = 0;
	
	for(i = 0; i < n; ++i)
		++buckets[a[i]];
		
	for(i = 0, j = 0; j < SIZE; ++j)
		for(k = buckets[j]; k > 0; --k)
			a[i++] = j;
}

int main() {
	int i, a[] = {3, 6, 5, 1, 8, 4, 3, 1}, n = 8;
	
	cout << "Before sorting:\n";
	for(i = 0; i < n; ++i)
		cout << a[i] << " ";
	
	bucketSort(a, 8);
	
	cout<< "\n\nAfter sorting:\n";
	for(i = 0; i < n; ++i)
		cout<< a[i] << " ";
	
	return 0;
}

Output

Before sorting:
3 6 5 1 8 4 3 1

After sorting:
1 1 3 3 4 5 6 8

The post Bucket Sort in C and C++ appeared first on The Crazy Programmer.

Viewing all 56 articles
Browse latest View live