Showing posts with label cprogram. Show all posts
Showing posts with label cprogram. Show all posts

Monday, 15 August 2016

C Program for Matrix Rotation






SOURCE CODE:

#include<stdio.h>

void main()
{
int a[10][10],b[10][10],T[4];   // a for original matrix  and b to store intermediate result 
int i,j,k,t,n,m,beg,end;
printf("Enter the size of the matrix:");
scanf("%d",&n);

for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
b[i][j]=a[i][j];
}
printf("\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
printf(" %2d  ",b[i][j]);
printf("\n");
}
beg=0;end=n-1;
t=0;                                // t for number of square rotations
m=n;
while(t<(m/2))
{

T[0]=a[beg][beg];                  // T is to store the values at corners
T[1]=a[beg][end];
T[2]=a[end][end];
T[3]=a[end][beg];

i=beg;j=beg+1;
  for(k=0;k<n-2;k++)               // 4 fors for 4 rotations
     { 
     b[i][j+1]=a[i][j];
       j++;
      }

j=end;
i=beg+1;
  for(k=0;k<n-2;k++)
     {
      b[i+1][j]=a[i][j];
       i++;
      }

i=end;
j=end-1;
  for(k=0;k<n-2;k++)
    {
     b[i][j-1]=a[i][j];
     j--;
    }

 i=end-1;
 j=beg;
   for(k=0;k<n-2;k++)
    {
     b[i-1][j]=a[i][j];
      i--;
    }
b[beg][beg+1]=T[0];          //adding corner elements at rotated positions
b[beg+1][end]=T[1];
b[end][end-1]=T[2];
b[end-1][beg]=T[3];
beg++;                      //moving to inner squares
end--;
n=n-2;
for(i=beg;i<n;i++)
for(j=beg;j<n;j++)
a[i][j]=b[i][j];
t++;
}
printf("\nAfter rotation:\n\n");
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
printf(" %2d ",b[i][j]);
printf("\n");
}


}
  

OUTPUT:

Enter the size of the matrix:5
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25

  1   2   3   4   5
  6   7   8   9  10
 11  12  13  14  15
 16  17  18  19  20
 21  22  23  24  25

After rotation:

  6   1   2   3   4
 11  12   7   8   5
 16  17  13   9  10
 21  18  19  14  15
 22  23  24  25  20

--------------------------------







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
--------------------------------


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]);
}
}

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

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+

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 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]);
}

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