Thursday 26 November 2015

C program for deadlock detection - Operating Systems

ALGORITHM:

1. Mark each process that has a row in the Allocation matrix of all zeros.
2. Initialize a temporary vectorW to equal the Available vector.
3. Find an indexi such that processi is currently unmarked and thei th row ofQ
is less than or equal to W . That is,Q ik Wk, for 1 … k m . If no such row is
found, terminate the algorithm.
4. If such a row is found, mark processi and add the corresponding row of the
allocation matrix to W . That is, setWk = Wk + Aik, for 1 … k m . Return
to step 3.




SOURCE CODE:
#include<stdio.h>
static int mark[20];
int i,j,np,nr;

int main()
{
int alloc[10][10],request[10][10],avail[10],r[10],w[10];

printf("\nEnter the no of process: ");
scanf("%d",&np);
printf("\nEnter the no of resources: ");
scanf("%d",&nr);
for(i=0;i<nr;i++)
{
printf("\nTotal Amount of the Resource R%d: ",i+1);
scanf("%d",&r[i]);
}




printf("\nEnter the request matrix:");

for(i=0;i<np;i++)
for(j=0;j<nr;j++)
scanf("%d",&request[i][j]);

printf("\nEnter the allocation matrix:");
for(i=0;i<np;i++)
for(j=0;j<nr;j++)
scanf("%d",&alloc[i][j]);
/*Available Resource calculation*/
for(j=0;j<nr;j++)
{
avail[j]=r[j];
for(i=0;i<np;i++)
{
avail[j]-=alloc[i][j];

}
}

//marking processes with zero allocation

for(i=0;i<np;i++)
{
int count=0;
 for(j=0;j<nr;j++)
   {
      if(alloc[i][j]==0)
        count++;
      else
        break;
    }
 if(count==nr)
 mark[i]=1;
}
// initialize W with avail

for(j=0;j<nr;j++)
    w[j]=avail[j];

//mark processes with request less than or equal to W
for(i=0;i<np;i++)
{
int canbeprocessed=0;
 if(mark[i]!=1)
{
   for(j=0;j<nr;j++)
    {
      if(request[i][j]<=w[j])
        canbeprocessed=1;
      else
         {
         canbeprocessed=0;
         break;
          }
     }
if(canbeprocessed)
{
mark[i]=1;

for(j=0;j<nr;j++)
w[j]+=alloc[i][j];
}
}
}

//checking for unmarked processes
int deadlock=0;
for(i=0;i<np;i++)
if(mark[i]!=1)
deadlock=1;


if(deadlock)
printf("\n Deadlock detected");
else
printf("\n No Deadlock possible");
}


OUTPUT:

Enter the no of process: 4
Enter the no of resources: 5

Total Amount of the Resource R1: 2
Total Amount of the Resource R2: 1
Total Amount of the Resource R3: 1
Total Amount of the Resource R4: 2
Total Amount of the Resource R5: 1

Enter the request matrix:0 1 0 0 1
0 0 1 0 1
0 0 0 0 1
1 0 1 0 1

Enter the allocation matrix:1 0 1 1 0
1 1 0 0 0
0 0 0 1 0
0 0 0 0 0

 Deadlock detected
--------------------------------


Thursday 5 November 2015

PLSQL Program to check whether a number is armstrong or not

declare
n number(5);
temp number(5);
r number(3);
s number(5);
begin
n:=&n;
temp:=n;
s:=0;
while(n>0)
loop
r:=n mod 10;
s:= s + (r*r*r);
n:=floor(n/10);
end loop;
if(temp = s) then
dbms_output.put_line(temp ||' is a Armstrong no');
else
dbms_output.put_line(temp ||' is NOT a Armstrong no');
end if;
end;

PL SQL Program to check whether a number is perfect or not

declare
n number;
i number;
tot number;
begin
n:=&n;
tot:=0;
for i in 1..n/2
loop
if(n mod i=0) then
tot:= tot+i;
end if;
end loop;
if(n=tot)then
dbms_output.put_line('Perfect no');
else
dbms_output.put_line('Not a Perfect no');
end if;
end;

Tuesday 3 November 2015

CPP Program for implementing stack as linked list - Data Structures

#include<iostream>
using namespace std;
struct node
{
int data;
struct node *link;
};
struct node *top=NULL;

void push(int val)
{
node *newnode =new node;
newnode->data=val;
newnode->link=top;
top=newnode;
}

void pop()
{
if(top==NULL)
cout<<"\nStack is empty!";
else
top=top->link;
}


void display()
{
node *temp=top;
if(temp==NULL)
cout<<"\nStack is empty!";
else
{
while(temp!=NULL)
{
  cout<<temp->data<<"\n";//to print horizontally we need to point from bottom, hence to avoid this we print vertically..
  temp=temp->link;
}
}
}

int main()
{
int choice,val;
while(1)
{
cout<<"\nSTACK LINKED LIST \n1.Push 2.Pop 3.Display 4.Exit \nEnter your choice:";
cin>>choice;
switch(choice)
{
case 1:
   cout<<"\nEnter value to Push:";cin>>val;
   push(val);
   break;
case 2:
   pop();
   break;
case 3:
   display();
   break;
case 4:
   return 0;
   break;
default:
cout<<"\nCheck ur input\n";
}
}
return 0;
}



OUTPUT:

STACK LINKED LIST
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:1

Enter value to Push:1

STACK LINKED LIST
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:1

Enter value to Push:5

STACK LINKED LIST
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:1

Enter value to Push:3

STACK LINKED LIST
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:3
3
5
1

STACK LINKED LIST
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:2

STACK LINKED LIST
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:3
5
1

STACK LINKED LIST
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:

Child parent process for sorting using fork() call - Operating Systems

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
int main()
{
pid_t pid;
int i,j;
int a[5];
printf("\nEnter 5 numbers:");
for(i=0;i<5;i++)
scanf("%d",&a[i]);
pid=fork();
if(pid==0)
{
for(i=0;i<4;i++)
for(j=i+1;j<5;j++)
{
if (a[i]>a[j])
{
int temp;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}

for(i=0;i<5;i++)
printf("%d",a[i]);
}
}

CPP Program for Single linked list - Data Structures

#include<iostream>
using namespace std;
typedef struct node
{
int data;
struct node *link;
};
node *slist=NULL;
void insBeg(int val)
{
node *newnode = new node;

newnode->data=val;
newnode->link=slist;
slist=newnode;
}
void insEnd(int val)
{

if(slist==NULL)
{
node *newnode = new node;
newnode->data=val;
newnode->link=NULL;
slist=newnode;
}
else
{
node *temp=slist;
while(temp->link!=NULL)
temp=temp->link;
node *newnode = new node;
newnode->data=val;
newnode->link=NULL;
temp->link=newnode;
}
}
int insLoc(int val,int loc)
{
node *temp=slist;

for(int i=1;i<loc;i++)
{
temp=temp->link;
if(temp==NULL)
{
cout<<"\nInvalid Location:";
return 0;
}
}
node *newnode=new node;
newnode->data=val;
newnode->link=temp->link;
temp->link=newnode;
}
int delnode(int val)
{
if(slist->link==NULL && slist->data == val)
slist=NULL;
node *temp=slist;
while(temp!=NULL)
{
node *p;
if(temp->data==val)
{
   if(temp==slist)
   slist=temp->link;
   else
   {
     p->link=temp->link;
    }
    delete temp;
     return 0;
}
else
{
p=temp;
temp=temp->link;
}
}
cout<<"\nData not found";
}

int retrive(int loc)
{
node *temp=slist;
int count=1;
while(temp!=NULL)
{
if(count==loc)
return temp->data;
temp=temp->link;
count++;
}
cout<<"Invalid location";
}
int countnode()
{
node *temp=slist;
int count=1;
while(temp->link!=NULL)
{
temp=temp->link;
count++;
}
return count;
}

void display()
{
node *temp=slist;
while(temp!=NULL)
{
cout<<temp->data<<"\t";
temp=temp->link;
}
}

int main()
{
int choice,val,loc;
do
{
cout<<"\nSINGLE LINKED LIST\n1.Insert at the Beginning \n2.Insert at end\n3.Insert at location\n4.delete\n5.retrive\n6.Count\n7.Display\n8.Exit";
cin>>choice;
switch(choice)
{
case 1:
cout<<"\nEnter the data:";cin>>val;
insBeg(val);
break;
case 2:
cout<<"\nEnter the data:";cin>>val;
insEnd(val);
break;
case 3:
cout<<"\nEnter the data,location:";cin>>val;cin>>loc;
insLoc(val,loc);
break;
case 4:
cout<<"\nEnter the data:";cin>>val;
delnode(val);
break;
case 5:
cout<<"\nEnter the location:";cin>>val;
cout<<"\nretrieved data:"<<retrive(val);
break;
case 6:
cout<<"\nNumber of nodes:";cout<<countnode();
break;
case 7:
display();
break;
case 8:
return 0;
break;
}


}while(1);
return 0;
}

Queue implemented as linked list in CPP -Data Structures

#include<iostream>
using namespace std;
struct node
{
int data;
struct node *link;
};
struct node *front=NULL,*rear=NULL;

void enqueue(int val)
{
if(front==NULL && rear==NULL)
{
node *newnode=new node;
newnode->data=val;
newnode->link=NULL;
rear=front=newnode;
}
else
{
node *newnode=new node;
newnode->data=val;
newnode->link=NULL;
rear->link=newnode;
rear=newnode;
}
}
void dequeue()
{
if(front==NULL)
cout<<"\nQUEUE IS EMPTY!";
else if (front==rear)//only one node is left
{
front=NULL;
rear=NULL;
}
else
{
front=front->link;
}
}
void display()
{
if(front==NULL)
cout<<"\nQUEUE IS EMPTY!";
else
{
node *temp=front;
while(temp!=NULL)
{
cout<<temp->data<<"\t";
temp=temp->link;
}
}
}
int main()
{
int choice,val;
while(1)
{
cout<<"\nQUEUE LINKED LIST \n1.Enqueue 2.Dequeue 3.Display 4.Exit \nEnter your choice:";
cin>>choice;
switch(choice)
{
case 1:
   cout<<"\nEnter value:";cin>>val;
   enqueue(val);
   break;
case 2:
   dequeue();
   break;
case 3:
   display();
   break;
case 4:
   return 0;
   break;
default:
cout<<"\nCheck ur input\n";
}
}
return 0;
}


OUTPUT:


QUEUE LINKED LIST
1.Enqueue 2.Dequeue 3.Display 4.Exit
Enter your choice:1
Enter value:7

QUEUE LINKED LIST
1.Enqueue 2.Dequeue 3.Display 4.Exit
Enter your choice:1
Enter value:5

QUEUE LINKED LIST
1.Enqueue 2.Dequeue 3.Display 4.Exit
Enter your choice:1
Enter value:6

QUEUE LINKED LIST
1.Enqueue 2.Dequeue 3.Display 4.Exit
Enter your choice:2

QUEUE LINKED LIST
1.Enqueue 2.Dequeue 3.Display 4.Exit
Enter your choice:3

5       6

Simple Program for implementing Queue in CPP - Data Strucures

#include<iostream>
using namespace std;
int f=0,r=0,q[10];

int enqueue(int val)
{
if(r==10)
cout<<"\nQueue overflows";
else
{
q[++r]=val;
if(f==0)
f=1;
}
return q[r];
}

void dequeue()
{
if(f==0)
cout<<"\nQueue underflow";
else
{
if(f==r)
f=r=0;
else
f++;
}
}

void display()
{
for(int i=f;i<=r;i++)
cout<<q[i]<<"  ";
}

int main()
{
int choice,val;
while(1)
{
cout<<"\n1.Enqueue 2.Dequeue 3.Display 4.Exit\nEnter your choice:";
cin>>choice;
switch(choice)
{
case 1:
cout<<"\nEnter value:";cin>>val;
enqueue(val);
break;
case 2:
dequeue();
break;
case 3:
display();
break;
case 4:
return 0;
break;
default:
cout<<"\nCheck your input";
}
}
return 0;
}





CPP program for merge sort - Data Structures

#include<iostream>           // Ref note
using namespace std;
int k[30];
void merge(int low,int mid,int high)
{
int i=low,j=mid+1,h=low;
int temp[30];           //temp is to contain the result(we may just print out inorder to avoid temp)
while(i<=mid && j<=high)         //i is for first half and j is for second half
{
   if(k[i]<=k[j])      // if first half element is lesser than second half
     {
        temp[h]=k[i];  
        i++;          
      }
    else
     {
      temp[h]=k[j];
       j++;          // increase corresponding iterative variable
     }
  h++;              // h is temp index
}
if(i>mid)          // if all first half elements are sorted and copied
{
   while(j<=high)  // copy the remaining elements from second half
    {
      temp[h]=k[j];
       j++;
       h++;
    }
}
else            // if all second half elements are copied and sorted
{
   while(i<=mid)  // copy the remaining elements of first half
   {
     temp[h]=k[i];
      i++;
      h++;
   }
}
i=low;
while(i<=high)  // just copying
{
k[i]=temp[i];
i++;
}


}

void mergesort(int low,int high)//this function splits the array into two until reaches single element and then merge
{
int mid;
if(low<high)
{
mid=(low+high)/2;
mergesort(low,mid);         //first half
mergesort(mid+1,high);      //second half
merge(low,mid,high);        //sort and merge the two halves
}
}


int main()
{
int n,i;
cout<<"\nEnter no of elements:";cin>>n;
cout<<"\nEnter the elements:";
for(i=1;i<=n;i++)
cin>>k[i];
mergesort(1,n);
cout<<"\nAfter sorting:";
for(i=1;i<=n;i++)
cout<<k[i]<<"\t";
return 0;
}

CPP Program for converting infix expression into postfix expression - Data Structures

#include<iostream>
using namespace std;
char s[100],top=-1;
void push(char val)
{
s[++top]=val;
}
char pop()
{char cc;
cc=s[top];
top--;
return cc;
}

int isempty()
{
if(top==-1)
return 1;
}

int priority(char toptok)
{
if(toptok=='*'||toptok=='/')
return 2;
else if(toptok=='+'||toptok=='-')
return 1;
return 0;
}

int main()
{
char a[20],c,tptk,t;
int i=0;
cout<<"\nEnter the infix:";
cin>>a;
cout<<"\nPostfix:";
while(a[i]!='\0')
{
c=a[i];
if(c=='(')
push('(');
else if(c==')')
{
    c=pop();
  while(c!='(')
   {
     
      cout<<c;
       c=pop();
    }
}
else if(c=='*'||c=='/'||c=='+'||c=='-')
{
tptk=s[top];
while(!isempty() && priority(c)<=priority(tptk))
{t=pop();
 cout<<t;
  tptk=s[top];
}
push(c);
}
else
cout<<c;
i++;
}

while(!isempty())
{
c=pop();
cout<<c;
}
return 0;
}


OUTPUT:
Enter the infix:(a+b)*(c-d)/e

Postfix:ab+cd-*e/


Enter the infix:2+4

Postfix:24+

HeapSort program in CPP - Data Structures

#include<iostream>
using namespace std;
int k[20],heapsize;

void adjust(int i)
{
int left=2*i;
int right=2*i+1;
int largest,temp;
if(left<=heapsize && k[left]>k[i])
largest=left;
else
largest=i;
if(right<=heapsize && k[largest]<k[right])
largest=right;
if(largest!=i)
{
temp=k[i];
k[i]=k[largest];
k[largest]=temp;
adjust(largest);
}
}


void heapify(int n)
{
heapsize=n;
int i=n/2;
while(i>=1)
{
adjust(i);
i--;
}
}


void heapsort(int n)
{
int q=n;
heapify(n);
while(q>=2)
{
int temp=k[1];
k[1]=k[q];
k[q]=temp;
heapsize--;
adjust(1);
q--;
}
}


int main()
{
int n;
cout<<"\nEnter no of elements:";cin>>n;
cout<<"\nEnter elements:";
for(int i=1;i<=n;i++)
cin>>k[i];
heapsort(n);
for(int i=1;i<=n;i++)
cout<<k[i];
return 0;
}

OUTPUT:


Enter no of elements:6

Enter elements:4 1 5 3 2 6
123456



Conversion of General tree to binary Program in CPP - Data Structures











SOURCE CODE:

#include<iostream>
using namespace std;
struct node
{
char data;
struct node *left;
struct node *right;
};
struct node *head;

struct info
{
int level;
struct node *loc;
};
int nlev;
char nname;
info s[100];
int top=-1;

info push(info c)
{
top++;
s[top]=c;

return s[top];
}

void pop()
{
top--;
}

info peek()
{
return s[top];
}

void preorder(node *root)
{
if(root!=NULL)
{
cout<<root->data<<" ";
preorder(root->left);
preorder(root->right);
}
}
void inorder(node *root)
{
if(root!=NULL)
{
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}
}
int main()
{
char c;
int i=0;
cout<<"\nGENERAL TREE TO BINARY TREE\n Note: Input must be the preorder sequence of the general tree";
node *newnode = new node;
head=newnode;
head->left=NULL;
head->right=NULL;
info a;
a.level=-1;
a.loc=head;
push(a);
do
{
cout<<"\nEnter the level,name:";
cin>>nlev;
cin>>nname;
node* newnode=new node;
newnode->left=newnode->right=NULL;
newnode->data=nname;
info Pred=peek();
if(Pred.level< nlev)         //if different levels add to left -1<0,0<1,1<2
{ Pred.loc->left=newnode;}
else
{               //if levels match or lesser  2<1,1<1
    while(Pred.level>nlev)
    {
     pop();               //popped until we get a sibling
     Pred=peek();
     }
    if(Pred.level<nlev)  
    {
    cout<<"\nError in input.Mixed Level numbers\n";
    return 0;
    }
   Pred.loc->right=newnode;   //sibling added to the right
   pop(); //pop added node
}
a.level=nlev;
a.loc=newnode;
push(a);
cout<<"\nDo you wanna continue(y/n)?:";
cin>>c;
}while(c=='y');
cout<<"\nBinary Tree\nPreorder:";
preorder(head);
cout<<"\ninorder:";
inorder(head);
return 0;
}



OUTPUT:

GENERAL TREE TO BINARY TREE
 Note: Input must be the preorder sequence of the general tree


Enter the level,name:0 a

Do you wanna continue(y/n)?:y

Enter the level,name:1 b

Do you wanna continue(y/n)?:y

Enter the level,name:2 e

Do you wanna continue(y/n)?:y

Enter the level,name:1 c

Do you wanna continue(y/n)?:y

Enter the level,name:1 d

Do you wanna continue(y/n)?:y

Enter the level,name:2 f

Do you wanna continue(y/n)?:y

Enter the level,name:2 g

Do you wanna continue(y/n)?:y

Enter the level,name:2 h

Do you wanna continue(y/n)?:n

Binary Tree
Preorder: a b e c d f g h
inorder:   e b c f g h d a

Double linked list program in CPP - Data Structures

#include<iostream>
using namespace std;
typedef struct node
{
int data;
struct node *plink;
struct node *slink;
};
node *slist=NULL;
int insBeg(int val)
{
node *newnode=new node;
newnode->data=val;
newnode->plink=NULL;
newnode->slink=slist;
slist=newnode;
return 0;
}
void insEnd(int val)
{
if(slist==NULL)
{
node *newnode=new node;
newnode->data=val;
newnode->plink=NULL;
newnode->slink=NULL;
slist=newnode;
}
else
{
node *temp=slist;
while(temp->slink!=NULL)
temp=temp->slink;
node *newnode =new node;
newnode->data=val;
newnode->plink=temp;
newnode->slink=NULL;
temp->slink=newnode;
}
}
int insLoc(int val,int loc)
{
node *temp=slist;
for(int i=1;i<loc;i++)
{
temp=temp->slink;
if(temp==NULL)
{
cout<<"\nINVALID LOCATION";
return 0;
}
}
node *newnode=new node;
newnode->data=val;
newnode->plink=temp;
newnode->slink=temp->slink;
temp->slink->plink=newnode;
temp->slink=newnode;
}

int delnode(int val)
{
if(slist->slink==NULL && slist->data==val)
{
slist=NULL;
return 0;
}
node *temp=slist;
while(temp!=NULL)
{
if(temp->data==val)
{
   if(temp==slist)
      {
      slist=temp->slink;
      slist->plink=NULL;
      }
    else if(temp->slink==NULL)
      temp->plink->slink=NULL;
     else
      {
       temp->plink->slink=temp->slink;
       temp->slink->plink=temp->plink;
      }
     delete temp;
     return 0;
}
temp=temp->slink;
}
cout<<"\nData not found";
return 0;
}
int retrieve(int loc)
{
node *temp=slist;
int count=1;
while(temp!=NULL)
 {
 if(count==loc)
  return temp->data;
temp=temp->slink;
if(temp==slist)
break;
count++;
}
cout<<"\nInvalid location";
return 0;
}
int count()
{
node *temp=slist;
int count=0;
while(temp!=NULL)
{
temp=temp->slink;
count++;
if(temp==slist)
break;
}
return count;
}
void display()
{
node *temp=slist;
while(temp!=NULL)
{
cout<<temp->data<<"\t";
temp=temp->slink;
}
}


int main()
{
int choice,val,loc;
while(1)
{
cout<<"\nDOUBLE LINKED LIST\n1.Insert at the Beginning \n2.Insert at end\n3.Insert at location\n4.delete\n5.retrive\n6.Count\n7.Display\n8.Exit\nEnter choice:";
cin>>choice;
switch(choice)
{
case 1:
cout<<"\nEnter the data:";cin>>val;
insBeg(val);
break;
case 2:
cout<<"\nEnter the data:";cin>>val;
insEnd(val);
break;
case 3:
cout<<"\nEnter the data,location:";cin>>val;cin>>loc;
insLoc(val,loc);
break;
case 4:
cout<<"\nEnter the data:";cin>>val;
delnode(val);
break;
case 5:
cout<<"\nEnter the location:";cin>>loc;
cout<<"\nretrieved data:"<<retrieve(loc);
break;
case 6:
cout<<"\nNumber of nodes:";cout<<count();
break;
case 7:
display();
break;
case 8:
return 0;
break;
}


}
return 0;
}



OUTPUT:
DOUBLE LINKED LIST
1.Insert at the Beginning
2.Insert at end
3.Insert at location
4.delete
5.retrieve
6.Count
7.Display
8.Exit

Enter choice:1
Enter the data:10

Enter choice:2
Enter the data:30

Enter choice:2
Enter the data:20

Enter choice:3
Enter the data,location:15 2

Enter choice:7
10      30      15      20

Enter choice:4
Enter the data:30

Enter choice:5
Enter the location:2
retrieved data:15

Enter choice:6
Number of nodes:3

Enter choice:7
10      15      20

Linux Shell program function to find the sum of digits of a number

function sum()
{
echo "enter n"
read n
sum=0
while [ $n -gt 0 ]
do
sum=`expr $sum + $n % 10 `
n=`expr $n / 10`
done
echo -n "sum of digits:"
echo $sum
}
sum


OUTPUT:
enter n 231
sum of digits:6

Linux Shell program to compare two strings

echo enter s1
read s1
echo enter s2
read s2
if test [s1-eq s2 ]
then
echo "Same"
else
echo "Not"
fi


OUTPUT:
enter s1 Marshal
enter s2 marshal

Not

Linux Shell program to reverse a number

echo "enter a number:"
read n
while [ $n -gt 0 ]
do
echo -n `expr $n % 10 `
n=`expr $n / 10 `
done


OUTPUT:
enter a number: 345
543

Linux Shell program function to read and print a string

function Print
{
echo $1
}

echo "Enter name:"
read name

Print $name



OUTPUT:
Enter name: Pravin
Pravin

Linux Shell program to count the no. of vowels in a file

echo enter filename
read filename
egrep [^aeiou] $filename |wc -l > vowcount
cat vowcount

Linux Shell program to check access mode of a file

if [ -r /$PWD/new2 ]
then
   echo “new2 exists and is executable. Exiting.”
elif [ -x /bin/bash ]
then
   echo “/bin/bash exists and is executable. Exiting.”
elif [ -x /bin/sh ]
 then
   echo “/bin/sh exists and is executable. Exiting.”
else
   echo “Found no executable program.”
fi

Linux program to check access rights - Linux - C program

#include<errno.h>
#include<fcntl.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/stat.h>

int main()
{

if(access("new",R_OK)==0)
printf("\nIt is readable");

if(access("new",W_OK)==0)
printf("\nIt is writable");
if(access("new",X_OK)==0)
printf("\nIt is executable");
return 0;
}


OUTPUT;
It is readable
It is writable

Sunday 1 November 2015

Quick sort program in C - Data Structures

#include<stdio.h>
int a[20];

int partition(int p, int r)
{
int x=a[r];
    int i=p-1;
    int j;
    for(j=p; j<=r-1;j++)
    {
    if(a[j]<=x)
    {
    i++;
    int temp=a[i];
    a[i]=a[j];
    a[j]=temp;
       }
    }
int temp=a[i+1];
a[i+1]=a[r];
a[r]=temp;
return i+1;
}
void quicksort(int p,int r)
{
if(p<r)
{
int q=partition(p,r);
quicksort(p,q-1);
quicksort(q+1,r);
}
}

void main()
{
int n,i;
printf("\n Enter no of elements");
scanf("%d",&n);
printf("\nEnter elements:");
for( i=1;i<=n;i++)
scanf("%d",&a[i]);
quicksort(1,n);
    printf("\n After sorting:");
    for( i=1;i<=n;i++)
    printf("%d ",a[i]);
}

Bit Stuffing in Computer Networks - Java Program - Client Server

/* In the user data, if 5 consecutive 1s come ,we include 0 after it and send the code to server where
the inversion operation takes place and data are read.. */



CLIENT:

import java.util.Scanner;
import java.util.Arrays;
import java.net.*;
import java.io.*;

class BitStuffCli
{
public static char convert(int i)
{
if(i==1)
return '1';
else
return '0';
}

public static void main(String args[]) throws Exception
{
int a[]=new int[100];
int b[]=new int[120];
int count=0;
int n,i,j;
Scanner in=new Scanner(System.in);
System.out.println("Enter no of bits:");
n=in.nextInt();
System.out.println("Enter the bits:");
for( i=0;i<n;i++)
a[i]=in.nextInt();

for(i=0,j=0;i<n;i++,j++)
{
b[j]=a[i];
if(a[i]==1)
count++;
else
count=0;
if(count==5)
{
j++;
b[j]=0;
count=0;
}
}
String s=new String();
System.out.println("\nSent as:");
for(i=0;i<j;i++)
{
System.out.print(b[i]);
s+=convert(b[i]);
}


Socket socket = new Socket("localhost",1234);
OutputStream ostream = socket.getOutputStream();
ostream.write(s.getBytes());
}
}

SERVER:

import java.util.Scanner;
import java.util.Arrays;
import java.net.*;
import java.io.*;

class BitStuffSer
{
public static int reconvert(char c)
if(c=='1')
return 1;
else 
return 0;

}
public static void main(String args[]) throws Exception
{
int i,j,count,n;
int b[]=new int[120];
int c[]=new int[100];
byte bytes[]=new byte[1000];
ServerSocket ss = new ServerSocket(1234);
Socket socket = new Socket();
socket=ss.accept();
InputStream istream = socket.getInputStream();
istream.read(bytes);
String s = new String(bytes);
    s=s.trim();
System.out.println("Received as:"+s);
n=s.length();
for(i=0;i<n;i++)
{
b[i]=reconvert(s.charAt(i));
}
 
for(i=0,j=0,count=0;j<n;i++,j++)
{
c[i]=b[j];
if(b[j]==1)
count++;
else
count=0;
if(count==5)
{
j++;
count=0;
}
}
System.out.println("\nOriginal bits:");
for(j=i,i=0;i<j;i++)

System.out.print(c[i]);
}
}


OUTPUT:
C:\Marsh\cn>java BitStuffCli
Enter no of bits:
12
Enter the bits:
1 1 0 1 1 1 1 1 0 1 0 1

Sent as:
1101111100101


C:\Marsh\cn>java BitStuffSer
Received as:1101111100101

Original bits:
110111110101



C program for simulation of Paging Technique Operating Systems

#include<stdio.h>
void main()
{
int memsize=15;
int pagesize,nofpage;
int p[100];
int frameno,offset;
int logadd,phyadd;
int i;
int choice=0;
printf("\nYour memsize is %d ",memsize);
printf("\nEnter page size:");
scanf("%d",&pagesize);

nofpage=memsize/pagesize;

for(i=0;i<nofpage;i++)
{
printf("\nEnter the frame of page%d:",i+1);
scanf("%d",&p[i]);
}

do
{
printf("\nEnter a logical address:");
scanf("%d",&logadd);
frameno=logadd/pagesize;
offset=logadd%pagesize;
phyadd=(p[frameno]*pagesize)+offset;
printf("\nPhysical address is:%d",phyadd);
printf("\nDo you want to continue(1/0)?:");
scanf("%d",&choice);
}while(choice==1);
}

OUTPUT:
Your memsize is 15
Enter page size:5

Enter the frame of page1:2

Enter the frame of page2:4

Enter the frame of page3:7

Enter a logical address:3

Physical address is:13
Do you want to continue(1/0)?:1

Enter a logical address:1

Physical address is:11
Do you want to continue(1/0)?:0

Producer Consumer Problem - C Program - Operating Systems

#include<stdio.h>
#include<semaphore.h>
#include<pthread.h>


sem_t prodlock;
sem_t conslock;
int product;


void *producer()
{
int i=1;
int item=1;
while(i<=5)
{
sem_wait(&prodlock);

product=item;
printf("\nProduced:%d",product);
sem_post(&conslock);
item++;
i++;

}
}

void *consumer()
{
int i=1;
while(i<=5)
{
sem_wait(&conslock);
printf("\nConsumed:%d",product);
sem_post(&prodlock);
i++;
}
}


void main()
{
pthread_t pid;
pthread_t cid;
pthread_attr_t *attr=NULL;
sem_init(&prodlock,0,1);
sem_init(&conslock,0,0);
if(pthread_create(&pid,attr,producer,NULL)!=0)
{
printf("\nError in creating Producer thread");
}
if(pthread_create(&cid,attr,consumer,NULL)!=0)
{
printf("\nError in creating Consumer thread");
}

pthread_join(pid,NULL);
pthread_join(cid,NULL);
}

OUTPUT:

Produced:1
Consumed:1
Produced:2
Consumed:2
Produced:3
Consumed:3
Produced:4
Consumed:4
Produced:5
Consumed:5

Priority Based CPU Scheduling - C Program - Operating Systems

#include<stdio.h>
struct process
{
char name;
int at,bt,ct,wt,tt,priority;
int processed;
float ntt;
}p[10];
int n;
void sortByArrival()
{
struct process temp;
int i,j;
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
{
if(p[i].at>p[j].at)
{
temp=p[i];
p[i]=p[j];
p[j]=temp;
}
}
}

void main()
{
int i,j,time=0,sum_bt=0,largest;
char c;
        float avgwt=0;
 printf("Enter no of processes:");
 scanf("%d",&n);
 for(i=0,c='A';i<n;i++,c++)
 {
 p[i].name=c;
 printf("\nEnter the arrival time , burst time, priority of process%c: ",p[i].name);
 scanf("%d%d%d",&p[i].at,&p[i].bt,&p[i].priority);
 p[i].processed=0;
 sum_bt+=p[i].bt;

}
sortByArrival();
p[9].priority=-9999;
printf("\nName\tArrival Time\tBurst Time\tPriority\t WT \t TT \t NTT");
  for(time=p[0].at;time<sum_bt;)
  {
    largest=9;
    for(i=0;i<n;i++)
    {
      if(p[i].at<=time && p[i].processed!=1 && p[i].priority>p[largest].priority)
        largest=i;
     }
      time+=p[largest].bt;
 p[largest].ct=time;
          p[largest].wt=p[largest].ct-p[largest].at-p[largest].bt;
     p[largest].tt=p[largest].ct-p[largest].at;
     p[largest].ntt=((float)p[largest].tt/p[largest].bt);
    p[largest].processed=1;
    avgwt+=p[largest].wt;
printf("\n%c\t\t%d\t\t%d\t\t%d\t%d\t%d\t%f",p[largest].name,p[largest].at,p[largest].bt,p[largest].priority,p[largest].wt,p[largest].tt,p[largest].ntt);
}
printf("\nAverage waiting time:%f\n",avgwt/n);
}

OUTPUT:

Enter no of processes:5

Enter the arrival time , burst time, priority of processA: 0 3 2

Enter the arrival time , burst time, priority of processB: 2 6 3

Enter the arrival time , burst time, priority of processC: 4 4 1

Enter the arrival time , burst time, priority of processD: 6 5 4

Enter the arrival time , burst time, priority of processE: 8 2 2

Name    Arrival Time    Burst Time      Priority         WT      TT      NTT
A               0                            3               2                     0       3       1.000000
B               2                            6               3                     1       7       1.166667
D               6                            5               4                     3       8       1.600000
E               8                             2               2                    6       8       4.000000
C               4                             4               1                  12      16      4.000000
Average waiting time:4.400000


HRRN CPU Scheduling - C Program - Operating Systems

#include<stdio.h>
struct process
{
char name;
int at,bt,ct,wt,tt;
int completed;
float ntt;
}p[10];
int n;

void sortByArrival()
{
struct process temp;
int i,j;
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
{
if(p[i].at>p[j].at)
{
temp=p[i];
p[i]=p[j];
p[j]=temp;
}
}
}
void main()
{
int i,j,time,sum_bt=0;
char c;
        float avgwt=0;
 printf("Enter no of processes:");
 scanf("%d",&n);
 for(i=0,c='A';i<n;i++,c++)
 {
 p[i].name=c;
 printf("\nEnter the arrival time and burst time of process%c: ",p[i].name);
 scanf("%d%d",&p[i].at,&p[i].bt);
 p[i].completed=0;
 sum_bt+=p[i].bt;

}
sortByArrival();

printf("\nName\tArrival Time\tBurst Time\tWaiting Time\tTurnAround Time\t Normalized TT");
  for(time=p[0].at;time<sum_bt;)
  {
 
   float hrr=-9999;
   int loc;
  for(i=0;i<n;i++)
  {
 
   if(p[i].at<=time && p[i].completed!=1)
            {
              float temp=(p[i].bt + (time-p[i].at))/p[i].bt;
              if(hrr < temp)
               {
                hrr=temp;
                loc=i;
               }
         
   }
   }
 
 
   time+=p[loc].bt;
   p[loc].wt=time-p[loc].at-p[loc].bt;
   p[loc].tt=time-p[loc].at;
   p[loc].ntt=((float)p[loc].tt/p[loc].bt);
   p[loc].completed=1;
   avgwt+=p[loc].wt;
printf("\n%c\t\t%d\t\t%d\t\t%d\t\t%d\t\t%f",p[loc].name,p[loc].at,p[loc].bt,p[loc].wt,p[loc].tt,p[loc].ntt);
  }

printf("\nAverage waiting time:%f\n",avgwt/n);
}

OUTPUT:

Enter no of processes:5

Enter the arrival time and burst time of processA: 0 3

Enter the arrival time and burst time of processB: 2 6

Enter the arrival time and burst time of processC: 4 4

Enter the arrival time and burst time of processD: 6 5

Enter the arrival time and burst time of processE: 8 2

Name    Arrival Time    Burst Time      Waiting Time    TurnAround Time  Normalized TT
A               0                        3                             0               3                             1.000000
B               2                        6                             1               7                             1.166667
C               4                        4                             5               9                             2.250000
E               8                        2                             5               7                             3.500000
D               6                       5                              9               14                          2.800000
Average waiting time:4.000000



FCFS CPU Scheduling - C Program - Operating Systems

#include<stdio.h>
struct process
{
char name;
int at,bt,ct,tt;
float ntt;
}p[10];
int n;
void sortByArrival()
{
struct process temp;
int i,j;
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
{
if(p[i].at>p[j].at)
{
temp=p[i];
p[i]=p[j];
p[j]=temp;
}
}
}

void main()
{
int i,j,time=0;
char c;
 printf("Enter no of processes:");
 scanf("%d",&n);
 for(i=0,c='A';i<n;i++,c++)
 {
 p[i].name=c;
 printf("\nEnter the arrival time of process%d: ",i+1);
 scanf("%d",&p[i].at);
 printf("\nEnter the burst time of process%d: ",i+1);
 scanf("%d",&p[i].bt);
}

sortByArrival();

printf("\nName\tArrival Time\tBurst Time\tTurnAround Time\t  Normalized TT");

for(i=0;i<n;i++)
{
time+=p[i].bt;
p[i].ct=time;
p[i].tt=p[i].ct-p[i].at;
p[i].ntt=((float)p[i].tt/p[i].bt);
printf("\n%c\t\t%d\t\t%d\t\t%d\t\t%f",p[i].name,p[i].at,p[i].bt,p[i].tt,p[i].ntt);
}
}



OUTPUT:
Enter no of processes:5

Enter the arrival time of process1: 0

Enter the burst time of process1: 3

Enter the arrival time of process2: 2

Enter the burst time of process2: 6

Enter the arrival time of process3: 4

Enter the burst time of process3: 4

Enter the arrival time of process4: 6

Enter the burst time of process4: 5

Enter the arrival time of process5: 8

Enter the burst time of process5: 2

Name    Arrival Time    Burst Time      TurnAround Time   Normalized TT
A               0                                3               3               1.000000
B               2                                6               7               1.166667
C               4                                4               9               2.250000
D               6                               5               12              2.400000
E               8                                2               12              6.000000

Shortest Job First - CPU Scheduling - Operating Systems

#include<stdio.h>
struct process
{
char name;
int at,bt,ct,wt,tt;
int processed;
float ntt;
}p[10];
int n;

void sortByArrival()
{
struct process temp;
int i,j;
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
{
if(p[i].at>p[j].at)
{
temp=p[i];
p[i]=p[j];
p[j]=temp;
}
}
}
void main()
{
int i,j,time,sum_bt=0,smallest;
char c;
        float avgwt=0;
 printf("Enter no of processes:");
 scanf("%d",&n);
 for(i=0,c='A';i<n;i++,c++)
 {
 p[i].name=c;
 printf("\nEnter the arrival time of process%c: ",p[i].name);
 scanf("%d",&p[i].at);
 printf("\nEnter the burst time of process%c: ",p[i].name);
 scanf("%d",&p[i].bt);
 p[i].processed=0;
 sum_bt+=p[i].bt;

}
sortByArrival();
p[9].bt=9999;
printf("\nName\tArrival Time\tBurst Time\tWaiting Time\tTurnAround Time\t Normalized TT");
  for(time=p[0].at;time<sum_bt;)
  {
    smallest=9;
    for(i=0;i<n;i++)
    {
      if(p[i].at<=time && p[i].processed!=1 && p[i].bt<p[smallest].bt)
        smallest=i;
    }
      time+=p[smallest].bt;
 p[smallest].ct=time;
          p[smallest].wt=time-p[smallest].at-p[smallest].bt;
     p[smallest].tt=p[smallest].wt+p[smallest].bt;
     p[smallest].ntt=((float)p[smallest].tt/p[smallest].bt);
    p[smallest].processed=1;
    avgwt+=p[smallest].wt;
printf("\n%c\t\t%d\t\t%d\t\t%d\t\t%d\t\t%f",p[smallest].name,p[smallest].at,p[smallest].bt,p[smallest].wt,p[smallest].tt,p[smallest].ntt);
}
printf("\nAverage waiting time:%f\n",avgwt/n);
}




OUTPUT:


Enter no of processes:5

Enter the arrival time of processA: 0 3

Enter the arrival time of processB: 2 6

Enter the arrival time of processC: 4 4

Enter the arrival time of processD: 6 5

Enter the arrival time of processE: 8 2

Name    Arrival Time    Burst Time      Waiting Time    TurnAround Time  Normalized TT
A                0                            3                        0               3                   1.000000
B                2                            6                        1               7                   1.166667
E                8                            2                        1               3                   1.500000
C               4                            4                        7               11                  2.750000
D               6                            5                        9               14                  2.800000
Average waiting time:3.600000

Round Robin CPU Scheduling - C Program - Operating Systems

/* Round Robin algorithm for CPU scheduling ( considering arrival time  and maintains a queue
as well)
Ref. Operating Systems by william stallings */

#include<stdio.h>
struct process
{
char name;
int at,bt,wt,tt,rt;
int completed;
float ntt;
}p[10];
int n;
int q[100];  //queue
int front=-1,rear=-1;
void enqueue(int i)
{
if(rear==100)
{
printf("overflow");
return 0;
}rear++;
q[rear]=i;
if(front==-1)
front=0;

}

int dequeue()
{
if(front==-1)
{
printf("underflow");
return 0;
} int temp=q[front];
if(front==rear)
front=rear=-1;
else
front++;
return temp;
}
int isInQueue(int i)
{int k;
for(k=front;k<=rear;k++)
{
if(q[k]==i)
return 1;
}
return 0;

}void sortByArrival()
{
struct process temp;
int i,j;
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
{
if(p[i].at>p[j].at)
{
temp=p[i];
p[i]=p[j];
p[j]=temp;
}
}
}

void main()
{
int i,j,time=0,sum_bt=0,tq;
char c;
        float avgwt=0;
 printf("Enter no of processes:");
 scanf("%d",&n);
 for(i=0,c='A';i<n;i++,c++)
 {
 p[i].name=c;
 printf("\nEnter the arrival time and burst time of process %c: ",p[i].name);
 scanf("%d%d",&p[i].at,&p[i].bt);
 p[i].rt=p[i].bt;
 p[i].completed=0;
 sum_bt+=p[i].bt;

}

printf("\nEnter the time quantum:");
scanf("%d",&tq);

sortByArrival();
enqueue(0);          // enqueue the first process
printf("Process execution order: ");
for(time=p[0].at;time<sum_bt;)       // run until the total burst time reached
{   i=dequeue();

if(p[i].rt<=tq)
{                          // for processes having remaining time with less than or equal time quantum
                     
time+=p[i].rt;
p[i].rt=0;
p[i].completed=1;        
   printf(" %c ",p[i].name);
            p[i].wt=time-p[i].at-p[i].bt;
            p[i].tt=time-p[i].at;    
            p[i].ntt=((float)p[i].tt/p[i].bt);
            for(j=0;j<n;j++)                // enqueue the processes which have come while scheduling
            {
            if(p[j].at<=time && p[j].completed!=1&& isInQueue(j)!=1)
            {
            enqueue(j);
           
            }
           }
        }
   else               // more than time quantum
   {
    time+=tq;
    p[i].rt-=tq;
    printf(" %c ",p[i].name);
    for(j=0;j<n;j++)             //enqueue the processes which have come scheduling first
            {
            if(p[j].at<=time && p[j].completed!=1&&i!=j&& isInQueue(j)!=1)
              {
            enqueue(j);
           
            }
           }
           enqueue(i);   // then enqueue the uncompleted process
         
   }

 
 
}

printf("\nName\tArrival Time\tBurst Time\tWaiting Time\tTurnAround Time\t Normalized TT");
for(i=0;i<n;i++)
{avgwt+=p[i].wt;
printf("\n%c\t\t%d\t\t%d\t\t%d\t\t%d\t\t%f",p[i].name,p[i].at,p[i].bt,p[i].wt,p[i].tt,p[i].ntt);
}
printf("\nAverage waiting time:%f\n",avgwt/n);
}


     


 OUTPUT:
Enter no of processes:5

Enter the arrival time and burst time of process A: 0 3

Enter the arrival time and burst time of process B: 2 6

Enter the arrival time and burst time of process C: 4 4

Enter the arrival time and burst time of process D: 6 5

Enter the arrival time and burst time of process E: 8 2

Enter the time quantum:4
Process execution order:  A  B  C  D  B  E  D
Name    Arrival Time    Burst Time      Waiting Time    TurnAround Time  Normalized TT
A               0                              3              0                           3                 1.000000
B               2                             6               9                           15                 2.500000
C               4                             4               3                            7                  1.750000
D               6                             5               9                          14                 2.800000
E               8                             2               9                           11                 5.500000
Average waiting time:6.000000

--------------------------------
Process exited after 16.79 seconds with return value 31
Press any key to continue . . .

C Program for Banker's Algorithm for deadlock avoidance - Operating Systems

#include<stdio.h>
static int visited[20];
int i,j,np,nr;



int canbeprocessed(int x[],int y[],int z[],int avail[])
{
for(j=0;j<nr;j++)
if(x[j]>avail[j])
return 0;
for(j=0;j<nr;j++)
{
avail[j]+=y[j];
y[j]=z[j]=0;
}
return 1;
}


int safe(int request[10][10],int avail[10],int alloc[10][10],int claim[10][10])
{
int count=0;
printf("\nSafe State Sequence: ");
while(count<np)
{
for(i=0;i<np;i++)
{
    if((visited[i]==0) && canbeprocessed(request[i],alloc[i],claim[i],avail))
    {
    count++;
    visited[i]=1;
    printf("P%d\t",i+1);
    break;        //if found break loop
    }
}
if(i==np) // all processes found to be not suitable for execution
return 0;
}
return 1;
}



int main()
{
int alloc[10][10],claim[10][10],request[10][10],avail[10],r[10];

printf("\nEnter the no of process: ");
scanf("%d",&np);
printf("\nEnter the no of resources: ");
scanf("%d",&nr);
for(i=0;i<nr;i++)
{
printf("\nTotal Amount of the Resource R%d: ",i+1);
scanf("%d",&r[i]);
}
printf("\nEnter the allocation matrix:");

for(i=0;i<np;i++)
for(j=0;j<nr;j++)
scanf("%d",&alloc[i][j]);

printf("\nEnter the claim matrix:");

for(i=0;i<np;i++)
for(j=0;j<nr;j++)
scanf("%d",&claim[i][j]);

for(i=0;i<np;i++)
for(j=0;j<nr;j++)
request[i][j]=claim[i][j]-alloc[i][j];
/*Available Resource calculation*/
for(j=0;j<nr;j++)
{
avail[j]=r[j];
for(i=0;i<np;i++)
{
avail[j]-=alloc[i][j];

}
}
/*Available Resource Calculation ends*/
if(safe(request,avail,alloc,claim))
printf("\n\nConclusion: System is in safe state ");
else
printf("\n\nConclusion: The system cannot acheive safe state" );
return 0;
}

Dining Philosopher Program in C - Operating Systems

 # include<stdio.h>
# include<pthread.h>
# include<semaphore.h>

sem_t fork[100];
int n;

void *phil_job(int no)
{
printf("\nPhilosopher %d is thinking",no+1);

sem_wait(&fork[no]);
sem_wait(&fork[(no+1)%n]);

printf("\nPhilosopher %d started eating",no+1);
sleep(1);
printf("\nPhilosopher %d finished eating",no+1);
sem_post(&fork[(no+1)%n]);
sem_post(&fork[no]);
}


void main()
{

int i;
pthread_t phil_thread[100];

printf("\nEnter the number of philosopher :");
scanf("%d",&n);

for(i=0;i<n;++i)
if(sem_init(&fork[i],0,1)==-1)
{
perror("semaphore initialization failed");
exit(1);
}

for(i=0;i<n;++i)
{
if(pthread_create(&phil_thread[i],NULL,phil_job,(int*) i)!=0)
{
perror("semaphore creation failed");
exit(1);
}

}



for(i=0;i<n;++i)
if(pthread_join(phil_thread[i],NULL)!=0)
{
perror("semaphore join failed");
exit(1);
}



printf("\n \n thread join succesfull\n");

for(i=0;i<n;++i)
if(sem_destroy(&fork[i])==-1)
{
perror("semaphore destruction failed");
exit(1);

}
}


OUTPUT:

Enter the number of philosopher :5

Philosopher 1 is thinking
Philosopher 2 is thinking
Philosopher 1 started eating
Philosopher 4 is thinking
Philosopher 4 started eating
Philosopher 3 is thinking
Philosopher 5 is thinking
Philosopher 4 finished eating
Philosopher 1 finished eating
Philosopher 3 started eating
Philosopher 5 started eating
Philosopher 3 finished eating
Philosopher 2 started eating
Philosopher 5 finished eating
Philosopher 2 finished eating

 thread join succesfull



Simulation of Disk scheduling algorithms - Operating Systems

This is a single c program to simulate 5 important disk scheduling algorithms in operating systems
1.FCFS
2.SSTF
3.Scan
4.CScan
5.Look

SOURCE CODE:

#include<stdio.h>
#include<math.h>
int req[30],sreq[30];
int n,endrange;
int startpos,headpos;
int totst;
int i,j;
int choice;


void getData()
{
printf("\nEnter no. of requests:");
scanf("%d",&n);
printf("\nEnter the requests:");
for(i=0;i<n;i++)
scanf("%d",&req[i]);
printf("\n Enter the end range of head:");
scanf("%d",&endrange);
printf("\n Enter the initial position of head:");
scanf("%d",&startpos);
}

void dispTotSeekTime()
{
printf("\nTotal seek time is %d",totst);
}

void initialize()
{
totst=0;
headpos=startpos;
printf("%d ",headpos);
}

void sortRequest()
{
for(i=0;i<n;i++)
sreq[i]=req[i];
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(sreq[i]>sreq[j])
{
int temp=sreq[i];
sreq[i]=sreq[j];
sreq[j]=temp;
}
}


void fcfs()
{
initialize();
for(i=0;i<n;i++)
{
totst+=abs(headpos-req[i]);
headpos=req[i];
printf("-> %d",headpos);
}
dispTotSeekTime();
}

void sstf()
{
initialize();
int visit[30];
for(i=0;i<n;i++)
visit[i]=0;
for(i=0;i<n;i++)
{
int min=endrange;
int loc;
     for(j=0;j<n;j++)
      {
        if(visit[j]==0)
         {
           if(abs(headpos-req[j])<min)
            {
              min=abs(headpos-req[j]);
              loc=j;
            }
         }
       }
totst+=min;
printf(" -> %d",req[loc]);
visit[loc]=1;
headpos=req[loc];
}
dispTotSeekTime();
}

void scan()
{
initialize();
sortRequest();
for(i=0;i<n;i++)
{
 if(headpos<sreq[i])
   {
    for(j=i-1;j>=0;j--)
      {
       totst+=abs(headpos-sreq[j]);
       headpos=sreq[j];
       printf(" -> %d",headpos);
      }
      if(choice==4)
      {
      totst+=abs(headpos-0);
      headpos=0;
      printf(" -> 0");
      }
      break;
   }
}
for(;i<n;i++)
{
totst+=abs(headpos-sreq[i]);
headpos=sreq[i];
printf(" -> %d",headpos);
}

dispTotSeekTime();
}
void cscan()
{
initialize();
sortRequest();
for(i=0;i<n;i++)
{
 if(headpos<sreq[i])
   {
    for(j=i-1;j>=0;j--)
      {
       totst+=abs(headpos-sreq[j]);
       headpos=sreq[j];
       printf(" -> %d",headpos);
      }
   
      totst+=abs(headpos-0);
      headpos=0;
      printf(" -> 0");
      headpos=endrange;
      printf(" -> %d",headpos);
      break;
   
   
   }
}
for(j=n-1;j>=i;j--)
{
totst+=abs(headpos-sreq[j]);
headpos=sreq[j];
printf(" -> %d",headpos);
}

dispTotSeekTime();
}

int main()
{

printf("\n Simulation of Disk Scheduling Algorithms ");
while(1)
{
printf("\n1.Enter data\n2.FCFS\n3.SSTF\n4.Scan\n5.C-Scan\n6.Look\n7.Exit\nEnter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
getData();
break;
case 2:
fcfs();
break;
case 3:
sstf();
break;
case 4:
case 6:
scan();
break;
case 5:
cscan();
break;
default:
return 0;
break;
}
}
}



Simulation of Page replacement algorithms in C - Operating Systems

This is a single c program which covers the 5 important page replacement algorithms in virtual memory chapter of operating system.
1.FIFO
2.Optimal
3.LRU
4.LFU
5.Second chance

SOURCE CODE:
#include<stdio.h>
int n,nf;
int in[100];
int p[50];
int hit=0;
int i,j,k;
int pgfaultcnt=0;
int bn;

void getData()
{
printf("\nEnter length of page reference sequence:");
scanf("%d",&n);
printf("\nEnter the page reference sequence:");
for(i=0;i<n;i++)
scanf("%d",&in[i]);
printf("\nEnter no of frames:");
scanf("%d",&nf);
}

void initialize()
{
pgfaultcnt=0;
bn=0;
for(i=0;i<nf;i++)
p[i]=9999;              // 9999 is used to represent empty frame
}

//function to check whether page fault occurs or not
int isHit(int data)
{
hit=0;
   for(j=0;j<nf;j++)
     {
       if(p[j]==data)
         {
          hit=1;
          break;
         }
     
     }

return hit;            
}

//function which returns the index of the page which is set
int getHitIndex(int data)
{
int hitind;
for(k=0;k<nf;k++)
{
if(p[k]==data)
{
hitind=k;
break;
}
}
return hitind;
}

void dispPages()
{
for (k=0;k<nf;k++)
{
if(p[k]!=9999)      //display except 9999
printf(" %d",p[k]);
}

}

void dispPgFaultCnt(){
printf("\nTotal no of page faults:%d",pgfaultcnt);
}

void fifo()
{
initialize();

for(i=0;i<n;i++)
{
printf("\nFor %d :",in[i]);

if(isHit(in[i])==0)
{
  p[bn]=in[i];          
  bn++;
  pgfaultcnt++;
  dispPages();
  if(bn==nf)                      // to treat as a circular queue
  bn=0;
}
else
printf("No page fault");
}
dispPgFaultCnt();
}




void optimal()
{
initialize();
int near[50];

for(i=0;i<n;i++)
{
printf("\nFor %d :",in[i]);

    if(isHit(in[i])==0)
    {
       pgfaultcnt++;
           if(bn<nf)                          // there are spaces to insert new pages
              {
                p[bn]=in[i];
                 bn++;
              }
           else                                // any page must be replaced
              {          
               for(j=0;j<nf;j++)
                 {  
                   int pg=p[j];
                   int found=0;
                   for(k=i;k<n;k++)
                   {
         
                     if(pg==in[k])
                    {
                      near[j]=k;
                      found=1;
                      break;
                    }
         
                  }
              if(!found)
              near[j]=9999;
                }
            int max=-9999;
            int repindex;
             for(j=0;j<nf;j++)
             {
               if(near[j]>max)          
              {
               max=near[j];
               repindex=j;
              }
             }
            p[repindex]=in[i];
         }

dispPages();
   }
else
printf("No page fault");
}
dispPgFaultCnt();
}

void lru()
{
initialize();

int least[50];
for(i=0;i<n;i++)
{

printf("\nFor %d :",in[i]);

if(isHit(in[i])==0)
{

for(j=0;j<nf;j++)
       {
         int pg=p[j];
         int found=0;
        for(k=i-1;k>=0;k--)
         {
           if(pg==in[k])
            {
             least[j]=k;
             found=1;
             break;
            }
         
         }
        if(!found)
          least[j]=-9999;
       }
  int min=9999;
  int repindex;
for(j=0;j<nf;j++)
{
if(least[j]<min)
  {
    min=least[j];
    repindex=j;
  }
}
p[repindex]=in[i];
pgfaultcnt++;

dispPages();
}
else
printf("No page fault!");
}
dispPgFaultCnt();
}

void lfu()
{
int usedcnt[100];
int least,repin,sofarcnt=0;
initialize();
for(i=0;i<nf;i++)
usedcnt[i]=0;

for(i=0;i<n;i++)
{

printf("\n For %d :",in[i]);
if(isHit(in[i]))
{
int hitind=getHitIndex(in[i]);
usedcnt[hitind]++;
printf("No page fault!");
}
else
{
pgfaultcnt++;
          if(bn<nf)
           { p[bn]=in[i];
             usedcnt[bn]++;
             bn++;
           }
          else
          { least=9999;
             for(k=0;k<nf;k++)
                 if(usedcnt[k]<least)
                  { least=usedcnt[k]; repin=k; }
            p[repin]=in[i];
            sofarcnt=0;
            for(k=0;k<=i;k++)
            if(in[i]==in[k])
            sofarcnt++;
            usedcnt[repin]=sofarcnt;
          }

 dispPages();
}



}
dispPgFaultCnt();
}

void secondchance()
{
int usedbit[50];
int victimptr=0;
initialize();
for(i=0;i<nf;i++)
usedbit[i]=0;
for(i=0;i<n;i++)
{
printf("\nFor %d:",in[i]);
 if(isHit(in[i]))
{
    printf("No page fault!");
     int hitindex=getHitIndex(in[i]);
     if(usedbit[hitindex]==0)
        usedbit[hitindex]=1;
}
else
{
      pgfaultcnt++;
      if(usedbit[victimptr]==1)
        {
          do
           {
            usedbit[victimptr]=0;
            victimptr++;
             if(victimptr==nf)
              victimptr=0;
           }while(usedbit[victimptr]!=0);
        }
     if(usedbit[victimptr]==0)
      {
       p[victimptr]=in[i];
       usedbit[victimptr]=1;
       victimptr++;
      }
     dispPages();
 
}
if(victimptr==nf)
victimptr=0;
}
dispPgFaultCnt();
}
       



int main()
{
int choice;
while(1)
{
printf("\nPage Replacement Algorithms\n1.Enter data\n2.FIFO\n3.Optimal\n4.LRU\n5.LFU\n6.Second Chance\n7.Exit\nEnter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
    getData();
    break;
case 2:
     fifo();
     break;
case 3:
    optimal();
    break;
case 4:
    lru();
    break;
case 5:
    lfu();
    break;
case 6:
    secondchance();
    break;
default:
    return 0;
    break;
}
}
}