Loading

Archive for 07/01/2012 - 08/01/2012

Kruskal Algorithm C Program

C - Program to Implement Kruskals Algorithm




#include<stdio.h>
#define INFINITY 999

typedef struct Graph
{
int v1;
int v2;
int cost;
}GR;

GR G[20];
int tot_edges,tot_nodes;
void create();
void Union(int,int,int []);
void spanning_tree();
int Minimum(int);

void main()
{
clrscr();
printf("\n\t Graph Creation by adjacency Matrix");
create();
spanning_tree();
getch();
}
void create()
{
int k;
printf("\n Enter total Number of nodes:");
scanf("%d",&tot_nodes);
printf("\n Enter Total number of edges:");
scanf("%d",&tot_edges);

for(k=0;k<tot_edges;k++)
{
    printf("\n Enter Edge in(v1,v2)from :");
    scanf("%d%d",&G[k].v1,&G[k].v2);
    printf("\n Enter Curresponding Cost :");
    scanf("%d",&G[k].cost);
}
}


void spanning_tree()
{
int count,k,v1,v2,i,j,tree[10][10],pos,parent[10];
int sum;
int Find(int v2,int parent[]);
count=0;
k=0;
sum=0;
for(i=0;i<tot_nodes;i++)
    parent[i]=i;
while(count!=tot_nodes-1)
{
    pos=Minimum(tot_edges);
    if(pos==-1)
        break;
        v1=G[pos].v1;
        v2=G[pos].v2;
        i=Find(v1,parent);
        j=Find(v2,parent);
        if(i!=j)
        {
            tree[k][0]=v1;
            tree[k][1]=v2;
            k++;
            count++;
            sum+=G[pos].cost;
            Union(i,j,parent);
        }
        G[pos].cost=INFINITY;
}

if(count==tot_nodes-1)
{
    printf("\n Spanning tree is..");
    printf("\n-------------------\n");
    for(i=0;i<tot_nodes-1;i++)
    {
        printf("[%d",tree[i][0]);
        printf("-");
        printf("%d",tree[i][1]);
        printf("]");
    }
    printf("\n---------------------");
    printf("\n Cost of Spanning Tree is :=%d",sum);
    }
    else
    {
        printf("There is no Spanning Tree");
    }
}


int Minimum(int n)
{
    int i,small,pos;
    small=INFINITY;
    pos=-1;
    for(i=0;i<n;i++)
    {
        if(G[i].cost<small)
        {
            small=G[i].cost;
            pos=i;
        }
    }
    return pos;
}

int Find(int v2,int parent[])
{
    while(parent[v2]!=v2)
    {
        v2=parent[v2];
    }
    return v2;
}

void Union(int i,int j,int parent[])
{
if(i<j)
    parent[j]=i;
else
    parent[i]=j;
}

Posted in | Leave a comment

C Program for Screen/Text Editor

C - Program to Implement Screen/Text Editor


Output Screen - 

C Program for Screen Editor

Code -

#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<dos.h>

int clm=1,row=1,in[21],ci=0;
FILE * fp;
char fname[50],buf[21][78],cbuf[80];

void redisp()
{
gotoxy(60,1);
printf("        ");
gotoxy(60,1);
textcolor(4);
textbackground(2);
cprintf("Alt+f:File %d:%d",clm-2,row-1);
if(row/10==0)
cprintf("");
gotoxy(row,clm);
}

void chrc()
{
if(row<=78)
row++;
else
 {
  row=2;
   if(clm<23)
    clm++;
    if(clm==23)
     row=78;
  }
}

void dispmenu()
{
int i,val,val1;
window(1,1,80,49);
textcolor(3);
textbackground(0);
clrscr();
 gotoxy(1,2);
 printf("%c",201);
 for(i=0;i<78;i++)
  printf("%c",205);
 printf("%c",187);
 for(i=0;i<46;i++)
  printf("%c\n",186);
 printf("%c",200);
 for(i=0;i<78;i++)
   printf("%c",205);
 gotoxy(80,2);
 for(i=0;i<46;i++)
 {
  val=wherey();
  if(i==0)
   gotoxy(80,val+1);
   else
   gotoxy(80,val);
  printf("%c",186);
  }
  val=wherey();
  gotoxy(80,val);
 printf("%c",188);
 gotoxy(2,2);
 gotoxy(1,1);
 textcolor(4);
 textbackground(7);
 cprintf("  F");
 textcolor(0);
  cprintf("ile  ");
  textcolor(4);
 }
 void disp_file()
 {
  int ch=33,c=1,k=3,j=1,i,fle=0,t=0;
  char s,fnm[50],nm;

  while(ch!=27)
   {
    gotoxy(6,1);
    textcolor(4);
    textbackground(2);

    cprintf(" F");
    textcolor(0);
    cprintf("ile ");
    window(6,2,15,6);
    textcolor(4);
   if(c==1)
    textbackground(2);
    else
    textbackground(15);
   cprintf(" N");
   textcolor(0);
  cprintf("ew  ");
  textcolor(4);

      if(c==2)
    textbackground(2);
    else
    textbackground(15);
  cprintf("0");
  textcolor(0);
  cprintf("pen  ");
  textcolor(4);

    if(c==3)
    textbackground(2);
    else
    textbackground(15);
   cprintf(" S");
  textcolor(0);
  cprintf("ave  ");
  textcolor(4);

   if(c==4)
    textbackground(2);
    else
    textbackground(15);
    cprintf(" E");
    textcolor(0);
    cprintf("xit   ");
    ch=getch();
   if(ch==0)
    {
     ch=getch();
      if(ch==72)
       {
    c=c - 1;
     if(c==0)
      c=4;
    }
    if(ch==80)
    c=c+1;
    if(c==5)
    c=1;
    if(ch==27)
    {
    clrscr();
    dispmenu();
    }
    if(ch==13)
    {
     switch(c)
     {
      case 1:clrscr();
         dispmenu();
         for(i=0;i<21;i++)
          {
           for(j=0;j<79;j++)
           buf[i][j]='\0';
          }
          for(i=0;i<21;i++)
          in[i]=0;
       gotoxy(30,2);
     textcolor(15);
       printf("NONAME.txt");
      gotoxy(3,2);
      ch=27;
      break;
  case 2: clrscr();
      dispmenu();
      window(25,3,50,5);
      textcolor(0);
     textbackground(15);
     clrscr();
     gotoxy(30,35);
       printf("Enter file name:");
       textcolor(0);
       scanf("%s",fname);
     fp=fopen(fname,"r");
     for(i=0;i<21;i++)
     {
      for(j=0;j<79;j++)
    buf[i][j]='\0';
     }

    for(i=0;i<21;i++)
    in[i]=0;
   k=3;
   j=1;
     if(fp==NULL)
     {
      window(25,7,45,7);
      textcolor(4);
      textbackground(2);
      clrscr();
     printf(" File not found\n");
    window(20,9,50,9);
   textcolor(4);
   textbackground(2);
  clrscr();
  cprintf("Press any key to continue");
  getch();
  clrscr();
 dispmenu();
 }
 else
  {
   clrscr();
    dispmenu();
     while(1)
      {
       fread(&s,sizeof(s),1,fp);
     if(!feof(fp))
      {
       if(s=='\n')
        t++;
        if(s!='\n')
        {
          buf[t][in[t]]=s;
          in[t]++;
        }
       }
     if(feof(fp))
     break;
    else
     {
      if(s!='\n')
       j++;
       else
    k=k+1;
    j=1;
       gotoxy(j,k);
     printf("%c",s);
     }
    }
    fclose(fp);
     gotoxy(j+1,k);
    row=j+1;
   clm=k;
  }
  ch=27;
  break;

case 3: window(20,9,60,9);
    textcolor(4);
    textbackground(2);
    clrscr();
    fclose(fp);
    cprintf("Enter file name:");
    scanf("%s",fnm);
    fp=fopen(fnm,"w");
    for(i=0;i<21;i++)
     {
      for(j=0;j<in[i];j++)
        fwrite(&buf[i][j],sizeof(buf[i][j]),1,fp);
      if(i!=20)
      {
       s='\n';
       fwrite(&s,sizeof(s),1,fp);
      }
     }
       fclose(fp);
     for(i=0;i<21;i++)
      {
       for(j=0;j<79;j++)
    buf[i][j]='\0';
      }
      for(i=0;i<21;i++)
      in[i]=0;
     clrscr();
     dispmenu();
     if(fle==1)
      exit(0);
      else
      ch=27;
     break;
case 4: window(10,9,55,9);
    textcolor(4);
    textbackground(2);
    clrscr();
       cprintf("Do you want to save file?(y/n):");
       scanf("%c",nm);
      if(nm=='y'||nm=='Y')
    ch=3;
    fle=1;
    exit(0);
    break;
    }
       }
     }
    }
 }
 void main()
 {
  int fl=0,f=0,cp=0,cx=0;
  int c,tx,ty,i,j,sx,sy,px,py;
  int button,x,y;
  char ch;
   textbackground(0);
   clrscr();
  dispmenu();
  row=2;
  clm=3;
  while(1)
   {
    fl=0;
    gotoxy(row,clm);
    row=wherex();
    clm=wherey();
    redisp();
    ch=getch();
     c=ch;
    if(c==0||c==3||c==22||c==24)
    {
     if(c==0)
      c=getch();
    }
    if(ch==27||ch==45)
    break;
    else
    {
     if(ch==8)// if entered char is backspace
      {
      tx=wherex();
      ty=wherey();
      if(ty>=3)
      {
       if(tx>=3)
    {
     if(in[ty-3]!=0)
     {
      buf[ty-3][tx-3]='\0';
     for(i=tx-3;i<in[ty-3]-1;i++)
     buf[ty-3][i]=buf[ty-3][i+1];
       if(tx-3<in[ty-3])
       in[ty-3]--;
      buf[ty-3][in[ty-3]]='\0';
      }
     }
    else
    buf[ty-4][77]='\0';
  }
  if(row!=1||row!=80)
  {
   if((row-1)!=1)
    {
     dispmenu();
     for(j=0;j<21;j++)
      {
       for(i=0;i<in[j];i++)
    {
    gotoxy(i+2,j+3);
    printf("%c",buf[j][i]);
    }
       }
      }
      row=row - 2;
   }
  if(row==0||clm==3)
   row++;
   fl=1;
   if(row<=0 && clm>3)
   {
    row=78;
    clm--;
    gotoxy(row,clm);
   }
  }
  else if(ch==13) //if entered char is enter
  {
   if(clm!=23) { }
   if(clm==23)
    row=78;
    else
    {
     row=1;
     clm++;
    }
    fl=1;
  }
else if(ch==0||ch==3||ch==22||ch==24)
{
 if(c==72 && clm!=3) //if entered char is upward arrow
  clm=clm -1;
  if(c==80 && clm!=23) //if entered char is downward arrow
  clm=clm +1;
  if(c==75 && row!=2) //if entered char is left arrow
  row=row -1;
  if(c==77 && row!=79) //if entered char is right arrow
  row=row +1;
  if(c==33) //if entered char is Alt+f
  disp_file();
  if(c==32)
   printf("%d",c);
   fl=1;
   if(c==24)
   {
    sx=sx -2;
    sy=sy -3;
    in[sy]=0;
    for(i=0,cx=0;i<=sx-ci && cx!=1;i++)
    {
     if(buf[sy][i]!='\0')
      cx=1;
    }
    if(cx==0)
    {
     buf[sy][0]='\0';
     in[sy]=0;
    }
    else
     in[sy]=sx-ci+1;
    cp=1;
    sx=wherex();
    sy=wherey();
    clrscr();
    dispmenu();
   for(j=0;j<21;j++)
    {
     for(i=0;i<in[j];i++)
      {
       gotoxy(i+2,j+3);
    printf("%c",buf[j][i]);
      }
    }
    gotoxy(sx,sy);
 }
 if(c==22) //if entered char is Ctrl+v
 {
  if(cp==1)
   {
    px=wherex();
    py=wherey();
    clrscr();
    dispmenu();
     for(j=0;j<21;j++)
     {
      for(i=0;i<in[j];i++)
       {
    gotoxy(i+2,j+3);
    printf("%c",buf[j][i]);
       }
     }
     gotoxy(px,py);
     if(buf[py-3][px-3]=='\0')
     {
      for(i=0;i<px-2;i++)
       {
    if(buf[py-3][i]=='\0')
    {
     buf[py-3][i]=' ';
     in[py-3]++;
    }
       }
      }
   for(i=0,j=px-2;i<ci;i++,j--)
    {
     buf[py-3][j]=cbuf[i];
     in[py-3]++;
    }
   }
  }

if(c==157) //if entered char is Alt+->
{
 if(f==0)
  {
   sx=wherex();
   sy=wherey();
   f=1;
   }
   else
   {
    if(sx+1!=wherex()||sy!=wherey())
    {
     f=0;
     ci=0;
     cp=0;
     cbuf[ci]='\0';
     sx=wherex();
     sy=wherey();
     clrscr();
     dispmenu();
    for(j=0;j<21;j++)
    {
     for(i=0;i<in[j];i++)
      {
       gotoxy(i+2,j+3);
       printf("%c",buf[j][i]);
      }
    }
    gotoxy(sx,sy);
  }
  else
   {
    sx=wherex();
    sy=wherey();
   }
  }
 }
}

else if(fl!=1)
{
 tx=wherex();
 ty=wherey();
 printf("%c",ch);
 if(buf[ty-3][tx-3]=='\0' && tx-3>=0)
  {
   for(i=0;i<tx-2;i++)
    {
     if(buf[ty-3][i]=='\0')
      {
       buf[ty-3][i]=' ';
       in[ty-3]++;
       }
      }
     }
    buf[ty-3][tx-2]=ch;
    in[ty-3]++;
   }
  }
  if(c!=24 && c!=72 && c!=80 && c!=75 && c!=77 && c!=33 && c!=3 && c!=35)
  chrc();
 }
}





Posted in , , | Leave a comment

Recursive Descent Parser C - Program


C - Program to Implement Recursive Descent Parser 

 

 #include <stdio.h> 

#include <conio.h>

#include <ctype.h>

char buffer[30];//For storing the input string
int i=0;//index into the array of input string
void S();
void E();
void T();
void T1();
void F();
void A();
void E1();
 void S()
   {
      printf("\nThe Production S => A=E  is used");
      A();
      if(buffer[i]=='=')
    {
       printf("\n......Match the terminal =");
       i++;
       E();
    }
      else
    {
       printf("\nError Condition ");
       exit();
    }
    }
  void A()
    {
       if(isalpha(buffer[i]))
      {
         printf("\n......Match the terminal %c",buffer[i]);
         i++;
      }
       else
      {
         printf("\nError condition");
         exit();
      }
    }
 void E()
   {
     printf("\nThe Production E => T E1 is used");
     T();
     E1();
   }
 void  E1()
   {
      if(buffer[i]=='+')
     {
        printf("\nThe production  E1 => +T E1 is used");
        printf("\n......Match the terminal +");
        i++;
        T();
        E1();
     }
      else
     printf("\nThe production E1 => <Epsilon> is used");
   }
void T()
   {
     printf("\nThe Production T => F T1 is used");
     F();
     T1();
   }
 void  T1()
   {
      if(buffer[i]=='*')
     {
        printf("\nThe production  T1 => *F T1 is used");
        printf("\n......Match the terminal *");
        i++;
        F();
        T1();
     }
      else
     printf("\nThe production T1 => <Epsilon> is used");
   }
  void F()
    {
       if(buffer[i]=='(')
     {
        printf("\nThe production  F => (E) is used");
        printf("\n......Match the terminal (");
        i++;
        E();
        if(buffer[i]==')')
        {
           printf("\n.....Match the terminal )");
           i++;
        }
         else
        {
            printf("\nError condition");
            exit();
        }
         return;
      }
       if(buffer[i]=='a')
     {
          printf("\nThe production  F => a is used");
          printf("\n......Match the terminal a");
          i++;
          return;
     }
       if(buffer[i]=='b')
     {
          printf("\nThe production  F => b is used");
          printf("\n......Match the terminal b");
          i++;
          return;
     }
       printf("\nError condition");
       exit();
   }
void main()
 {
   clrscr();
   printf("\nEnter input string:");
   gets(buffer);
   S();
   printf("\nIt is a valid string");
   getch();
 }

 

Click Here to Download Source Code with Executable Program

Posted in , , | Leave a comment

C - Program for Fork using Orphan Process

C- Program Fork using Orphan Process

1. Count no of words when child process is executing

2. Count no of vowels when parent process is executing

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

char s[50];
void count_words();
void count_vowels();

int main(void)
{
  int pid;
  int i,j;
  printf("\nEnter a string::");
  gets(s);
  pid=fork();
  if(pid==0)
  {   
                        
        printf("\nChild Process is Executing");
        sleep(10);
    printf("\nProcess ID = %d\nParent ID = %d",getpid(),getppid());
           count_words();
        printf("\n\n");
   }
   else
   {   
         printf("\nParent Process is Executing");
         printf("\nProcess ID= %d\nParent ID= %d",getpid(),getppid());
         count_vowel();
       printf("\n\n");
    }


        return 0;
}



void count_words()
{
   int i,j,k;
   int count=1;
  
   for(i=0;i<strlen(s);i++)
   {
    if(s[i]==32)
    {
        count++;
    }
   }  
     printf("\nThe No of Words in String::%d",count);


}


void count_vowel()
{
  int i,j,k;
  int count=0;
  for(i=0;i<strlen(s);i++)
  {
    if(s[i]=='a'||s[i]=='e'||s[i]=='i'||s[i]=='o'||s[i]=='u')
    {
        count++;
    }
  }

    printf("\nThe No Vowels in String :: %d",count);
}

/*output-
 [ketan@localhost ~]$ cc fork12.c
[ketan@localhost ~]$ ./a.out

Enter a string::ketan


Parent Process is Executing
Process ID= 2701
Parent ID= 2603
The No Vowels in String :: 2


[ketan@localhost ~]$
Child Process is Executing
Process ID = 2703
Parent ID = 1
The No of Words in String::1
*/

1 Comment

C Program for Fork to sort Numbers

C - Program for Fork to Sort Numbers in Ascending And Descending Order


#include<stdio.h>
#include<unistd.h>

int nos[10],n;
void ascending();
void descending();

int main(void)
{
  int pid;
  int i,j;
  printf("\nEnter the no of nos::");
  scanf("%d",&n);
  printf("\nEnter the Nos:");
  for(i=0;i<n;i++)
      scanf("%d",&nos[i]);
  pid=fork();
  if(pid==0)
  {
        printf("\nChild Process is Executing");
    printf("\nProcess ID = %d\nParent ID = %d",getpid(),getppid());
    ascending();
    printf("\n\n");
   }
   else
   {
    printf("\nParent Process is Executing");
    printf("\nProcess ID= %d\nParent ID= %d",getpid(),getppid());
    descending();
        printf("\n\n");
    }  


    return 0;
}


void ascending()
{
  int i,j,k,temp;
  for(i=0;i<n;i++)
  {
    for(j=i+1;j<n;j++)
    {
        if(nos[i]>nos[j])
        {
            temp=nos[i];
            nos[i]=nos[j];
            nos[j]=temp;  
        }
    }
   }

     printf("\n\nThe no in Ascending order are::\n");
         for(i=0;i<n;i++)
                printf("%d\t",nos[i]);

}

void descending()
{
  int i,j,k,temp;
  for(i=0;i<n;i++)
  {
        for(j=i+1;j<n;j++)
        {
                if(nos[i]<nos[j])
                {
                        temp=nos[i];
                        nos[i]=nos[j];
                        nos[j]=temp;
                }
        }
   }

    printf("\n\nThe no in Descending order are::\n");
        for(i=0;i<n;i++)
            printf("%d\t",nos[i]);
}
 
/*output-
[ketan@localhost ~]$ cc fork11.c
[ketan@localhost ~]$ ./a.out

Enter the no of nos::5

Enter the Nos:1 9 5 2 4

Child Process is Executing
Process ID = 2745
Parent ID = 2742

The no in Ascending order are::
1       2       4       5       9


Parent Process is Executing
Process ID= 2742
Parent ID= 2603

The no in Descending order are::
9       5       4       2       1
*/

Leave a comment

C Program for Producer Consumer Problem

C - Program to Implement Producer-Consumer Problem


#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<string.h>
#define SIZE 10

main()
{
    pid_t pid;
    ssize_t byte;
    char bin[SIZE], bout[SIZE];
    int fields[2],ch=0,count = 0,a;
    pipe(fields);
    pid = fork();
    if(pid==0)
    {
        xyz:
        printf("\n\tEnter your choice:\n\t1.Producer,\n\t2.Consumer,\n\t3.Exit.");
        printf("\n\tEnter Your choice: ");
        scanf("%d",&ch);
        if(ch==1)
        {
            close(fields[0]);
            while(count<SIZE)
            {
                printf("\n\tEnter the string: ");
                gets(bin);
                write(fields[1], bin, SIZE);
                count++;
            }
            close(fields[1]);
            printf("\n\tPipe is full.");
            goto xyz;
        }
        else
            wait(0);
        if(ch==3)
            exit(0);
    }
    else
    {
        close(fields[1]);
        wait();
        printf("\n\tThe string is: ");
        count=0;
        while(count++<SIZE)
        {
            byte = read(fields[0], bout, SIZE);
            if(byte!=0)
            {
                printf("\t");
                puts(bout);
            }
            else
            {
                printf("\n\tSTRING IS EMPTY");
                goto xyz;
            }
            sleep(1);
        }
        count=0;
        goto xyz;
    }
}

Leave a comment

C Program for Dinning Philosophers Problem

C - Program to Implement Dinning Philosophers Problem


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

pthread_mutex_t work_mutex[5];

struct chops
{
    int left;
    int right;
}p[5];

void *philosopher5()
{
    while(1)
    {
        if((p[5].left==1) || (p[5].right==1))
        {
            printf("\n\tPhilosopher5 is thinking...");
            sleep(2);
        }
        if((p[5].left==0) && (p[5].right==0))
        {
            pthread_mutex_lock(&work_mutex[4]);
            pthread_mutex_lock(&work_mutex[0]);
            p[5].left=1;
            p[1].right=1;
            p[5].right=1;
            p[4].left=1;
            printf("\n\tPhilosopher5 is eating....");
            sleep(6);
            printf("\n\tphilosopher5 is releasing chopstics.");
            p[5].left=0;
            p[1].right=0;
            p[5].right=0;
            p[4].left=0;
            pthread_mutex_unlock(&work_mutex[4]);
            pthread_mutex_unlock(&work_mutex[0]);
            sleep(5);
        }
    }
}

void *philosopher4()
{
    while(1)
    {
        if((p[4].left==1) || (p[4].right==1))
        {
            printf("\n\tphilosopher4 is thinking...");
            sleep(2);
        }
        if((p[4].left==0) && (p[4].right==0))
        {
            pthread_mutex_lock(&work_mutex[3]);
            pthread_mutex_lock(&work_mutex[4]);
            p[4].left=1;
            p[5].right=1;
            p[4].right=1;
            p[3].left=1;
            printf("\n\tPhilosopher4 is eating....");
            sleep(6);
            printf("\n\tphilosopher4 is releasing chopstics.");
            p[4].left=0;
            p[5].right=0;
            p[4].right=0;
            p[3].left=0;
            pthread_mutex_unlock(&work_mutex[3]);
            pthread_mutex_unlock(&work_mutex[4]);
            sleep(5);
        }
    }
}

void *philosopher3()
{
    while(1)
    {
        if((p[3].left==1) || (p[3].right==1))
        {
            printf("\n\tPhilosopher3 is thinking...");
       
    sleep(2);
        }
        if((p[3].left==0) && (p[3].right==0))
        {
            pthread_mutex_lock(&work_mutex[3]);
            pthread_mutex_lock(&work_mutex[2]);
            p[3].left=1;
            p[4].right=1;
            p[3].right=1;
            p[2].left=1;
            printf("\n\tPhilosopher3 is eating....");
            sleep(6);
            printf("\n\tphilosopher3 is releasing chopstics.");
            p[3].left=0;
            p[4].right=0;
            p[3].right=0;
            p[2].left=0;
            pthread_mutex_unlock(&work_mutex[3]);
            pthread_mutex_unlock(&work_mutex[2]);
            sleep(5);
        }
    }
}

void *philosopher2()
{
    while(1)
    {
        if((p[2].left==1) || (p[2].right==1))
        {
            printf("\n\tPhilosopher2 is thinking...");
            sleep(2);
        }
        if((p[2].left==0) && (p[2].right==0))
        {
            pthread_mutex_lock(&work_mutex[2]);
            pthread_mutex_lock(&work_mutex[1]);
            p[2].left=1;
            p[3].right=1;
            p[2].right=1;
            p[1].left=1;
            printf("\n\tPhilosopher2 is eating....");
            sleep(6);
            printf("\n\tphilosopher2 is releasing chopstics.");
            p[2].left=0;
            p[3].right=0;
            p[2].right=0;
            p[1].left=0;
            pthread_mutex_unlock(&work_mutex[2]);
            pthread_mutex_unlock(&work_mutex[1]);
            sleep(5);
        }
    }
}

void *philosopher1()
{
    while(1)
    {
        if((p[1].left==1) || (p[1].right==1))
        {
            printf("\n\tPhilosopher1 is thinking...");
            sleep(2);
        }
        if((p[1].left==0) && (p[1].right==0))
        {
            pthread_mutex_lock(&work_mutex[1]);
            pthread_mutex_lock(&work_mutex[0]);
            p[1].left=1;
            p[2].right=1;
            p[1].right=1;
            p[5].left=1;
            printf("\n\tPhilosopher1 is eating....");
            sleep(6);
            printf("\n\tphilosopher1 is releasing chopstics.");
            p[1].left=0;
            p[2].right=0;
            p[1].right=0;
            p[5].left=0;
            pthread_mutex_unlock(&work_mutex[1]);
            pthread_mutex_unlock(&work_mutex[0]);
            sleep(5);
        }
    }
}

main()
{
    int res,i;
    pthread_t ph1,ph2,ph3,ph4,ph5;
    for(i=0;i<5;i++)
    {
        res=pthread_mutex_init(&work_mutex[i],NULL);
        if(res!=0)
        {
            printf("\n\tError in creation of mutex.");
            //exit(EXIT_FAILURE);
        }
    }
    for(i=1;i<=5;i++)
    {
        p[i].left=0;
        p[i].right=0;
    }
    printf("\n\tProgram to demonstrate thread:");
    printf("\n\tCreating 5 new threads...");
    pthread_create(&ph1,NULL,philosopher1,NULL);
    pthread_create(&ph2,NULL,philosopher2,NULL);
    pthread_create(&ph3,NULL,philosopher3,NULL);
    pthread_create(&ph4,NULL,philosopher4,NULL);
    pthread_create(&ph5,NULL,philosopher5,NULL);
    printf("\n\tWaiting for thread to join....");
    res=pthread_join(ph1,NULL);
    exit(EXIT_SUCCESS);
}

Leave a comment

Simulation of Page replacement algorithms ( FIFO, LRU, Optimal)

C  Program for Simulation of Page replacement algorithms
(FIFO, LRU, Optimal)

#include<stdio.h>

void FIFO(char [],char [],int,int);
void lru(char [],char [],int,int);
void opt(char [],char [],int,int);

int main()
{
   int ch,YN=1,i,l,f;
   char F[10],s[25];
   clrscr();
   //system("clear");
   printf("\n\n\tEnter the no of empty frames: ");
   scanf("%d",&f);
   printf("\n\n\tEnter the length of the string: ");
   scanf("%d",&l);
   printf("\n\n\tEnter the string: ");
   scanf("%s",s);
   for(i=0;i<f;i++)
     F[i]=-1;
      do
    {
     // system("clear");
      printf("\n\n\t*********** MENU ***********");
      printf("\n\n\t1:FIFO\n\n\t2:LRU\n\n\t3:OPT\n\n\t4:EXIT");
      printf("\n\n\tEnter your choice: ");
      scanf("%d",&ch);
      //system("clear");
      switch(ch)
       {
      case 1:
          for(i=0;i<f;i++)
           {
             F[i]=-1;
           }

          FIFO(s,F,l,f);
          break;
      case 2:
          for(i=0;i<f;i++)
           {
             F[i]=-1;
           }
          lru(s,F,l,f);
          break;
      case 3:
          for(i=0;i<f;i++)
           {
             F[i]=-1;
           }

          opt(s,F,l,f);
          break;
      case 4:
          exit(0);
       }
      printf("\n\n\tDo u want to continue IF YES PRESS 1\n\n\tIF NO PRESS 0 : ");
      scanf("%d",&YN);
    }while(YN==1);return(0);
}

//FIFO
void FIFO(char s[],char F[],int l,int f)
{
   int i,j=0,k,flag=0,cnt=0;
   printf("\n\tPAGE\t    FRAMES\t  FAULTS");
   for(i=0;i<l;i++)
    {
       for(k=0;k<f;k++)
    {
      if(F[k]==s[i])
        flag=1;
    }

       if(flag==0)
    {
      printf("\n\t%c\t",s[i]);
      F[j]=s[i];
      j++;

      for(k=0;k<f;k++)
       {
        printf("   %c",F[k]);
       }
      printf("\tPage-fault%d",cnt);
      cnt++;
    }

       else
    {
      flag=0;
      printf("\n\t%c\t",s[i]);
      for(k=0;k<f;k++)
       {
        printf("   %c",F[k]);
       }

      printf("\tNo page-fault");
    }
       if(j==f)
    j=0;
    }

}


//LRU
void lru(char s[],char F[],int l,int f)
{
   int i,j=0,k,m,flag=0,cnt=0,top=0;
   printf("\n\tPAGE\t    FRAMES\t  FAULTS");
   for(i=0;i<l;i++)
    {
       for(k=0;k<f;k++)
    {
      if(F[k]==s[i])
       {
        flag=1;
         break;
       }
    }

       printf("\n\t%c\t",s[i]);
       if(j!=f && flag!=1)
    {
      F[top]=s[i];
      j++;

      if(j!=f)
       top++;
    }
       else
    {
       if(flag!=1)
        {
          for(k=0;k<top;k++)
           {
        F[k]=F[k+1];
           }

           F[top]=s[i];
        }
       if(flag==1)
        {
           for(m=k;m<top;m++)
           {
        F[m]=F[m+1];
           }

           F[top]=s[i];
        }
    }
       for(k=0;k<f;k++)
    {
     printf("   %c",F[k]);
    }

       if(flag==0)
    {
      printf("\tPage-fault%d",cnt);
      cnt++;
    }
       else
     printf("\tNo page fault");
       flag=0;
    }

}


//optimal
void opt(char s[],char F[],int l,int f)
{
   int i,j=0,k,m,flag=0,cnt=0,temp[10];

   printf("\n\tPAGE\t    FRAMES\t  FAULTS");
   for(i=0;i<10;i++)
     temp[i]=0;

   for(i=0;i<f;i++)
     F[i]=-1;

   for(i=0;i<l;i++)
    {
       for(k=0;k<f;k++)
    {
      if(F[k]==s[i])
        flag=1;
    }

       if(j!=f && flag==0)
    {
      F[j]=s[i];
      j++;
    }

       else if(flag==0)
    {
       for(m=0;m<f;m++)
        {
          for(k=i+1;k<l;k++)
           {
          if(F[m]!=s[k])
           {
             temp[m]=temp[m]+1;
           }
          else
           break;
           }
        }
       m=0;
       for(k=0;k<f;k++)
        {
           if(temp[k]>temp[m])
        {
          m=k;
        }
        }

       F[m]=s[i];
    }

       printf("\n\t%c\t",s[i]);
       for(k=0;k<f;k++)
    {
       printf("  %c",F[k]);
    }
       if(flag==0)
    {
      printf("\tPage-fault %d",cnt);
      cnt++;
    }
       else
     printf("\tNo Page-fault");
       flag=0;

       for(k=0;k<10;k++)
     temp[k]=0;
     }
}

Posted in , , , | 5 Comments

Simulation of Memory allocation algorithms ( First Fit, Best Fit , Next Fit )

C - Program for Simulation of Memory Allocation Algorithms

(First Fit, Best Fit, Next Fit)



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

void display(int ,int [10]);
void firstfit(int ,int [10],int [10],int);
void nextfit(int ,int [10],int [10],int);
void bestfit(int ,int [10],int [10],int);
void worstfit(int,int [10],int [10],int);

int main()
{
  int npr,nh=0,i,j,k,pr[10],hol[10],ch,temp[10];
  do{ 
      printf("\n\n----------MENU------------\n1.INPUT"
             "\n2.FIRST-FIT \n3.BEST FIT\n4.NEXT FIT"
             "\n5.WORST FIT\n6.EXIT\n\nENTER YOUR CHOICE:");
      scanf("%d",&ch);
    for(i=0;i<nh;i++)temp[i]=hol[i];
    switch(ch)
      {
         case 1:
                printf("\n Enter the number of processes:");
                scanf("%d",&npr);
                printf("\nNumber of holes:");
                scanf("%d",&nh);
                for(i=0;i<npr;i++)
                  {
                     printf("\nProcess %d:",i+1);  
                     scanf("%d",&pr[i]);  
                  }
                for(i=0;i<nh;i++)
                  {
                     printf("\nHole %d:",i+1);  
                     scanf("%d",&hol[i]);  
                      temp[i]=hol[i];
                  }
                break;
        case 2:
                firstfit(npr,temp,pr,nh);
                break;
        case 3: bestfit(npr,temp,pr,nh);
                break;
         case 4:nextfit(npr,temp,pr,nh);
                break;
         case 5:worstfit(npr,temp,pr,nh);
                 break;
         case 6:exit (0);//break;
        default:printf("\nWrong choice......!");
     }
   }while(ch!=6);
return 0;    
}

//First Fit
void firstfit(int npr,int hol[10],int pr[10],int nh)
{
   int i,j,k,flag=0;
   for(i=0;i<npr;i++)
   {
      flag=0;
      for(j=0;j<nh;j++)
      {
             if(pr[i]<hol[j])
              {
                hol[j]=hol[j]-pr[i];printf("\nMemory is Allocated to Process %d :(%d)",i+1,pr[i]);
                flag=1;break;             
              }
            else if(pr[i]==hol[j])
              {
                 flag=1;printf("\nMemory is Allocated to Process %d :(%d)",i+1,pr[i]);
                for(k=j;k<nh-1;k++)
                 {
                   hol[k]=hol[k+1];
                 }  nh--;
                 break;
              } 
        }
    if(flag==0)
    {printf("\n Hole is not Available.....");
    break;}
display(nh,hol);  
   }
}        

//Best fit
void bestfit(int npr,int hol[10],int pr[10],int nh){
int i,j,k,min,flag;
for(i=0;i<npr;i++)
   {
     flag=0;
       for(j=0;j<nh;j++)
        {
            if(pr[i]<=hol[j])
              {
                flag=1;  min=j;
                 for(k=j;k<nh;k++)
                 {
                   if((hol[min]>hol[k])&&(pr[i]<=hol[k]))min=k;
                        
                 }
               if(pr[i]<hol[min])
               {printf("\nMemory is Allocated to Process %d :(%d)",i+1,pr[i]);
                hol[min]=hol[min]-pr[i];
               break;             
               }
              else if(pr[i]==hol[min])
              {printf("\nMemory is Allocated to Process %d :(%d)",i+1,pr[i]);         
                for(k=min;k<nh-1;k++)
                   hol[k]=hol[k+1];
                nh--;
                 break;
              }         
               }     
          }       
    if(flag==0)
    {printf("\n Hole is not Available.....");
    break;}
display(nh,hol);  
      }
}

//Next Fit
void nextfit(int npr,int hol[10],int pr[10],int nh){
int i,j=0,k,flag=0;
for(i=0;i<npr;i++)
   {
     flag=0;
       for(;j<nh;)
        {
               if(pr[i]<hol[j])
               {
                hol[j]=hol[j]-pr[i];
               //j=(j+1)%nh;
flag=1;printf("\nMemory is Allocated to Process %d :(%d)",i+1,pr[i]);             
               break;             
               }
              else if(pr[i]==hol[j])
              {
            flag=1;printf("\nMemory is Allocated to Process %d :(%d)",i+1,pr[i]);
                for(k=j;k<nh-1;k++)
                   hol[k]=hol[k+1];
                nh--;
               //j=(j+1)%nh;
   break;
              }         
                j=(j+1)%nh;

          } 
    if(flag==0)
    {printf("\n Hole is not Available.....");
    break;}
    display(nh,hol);  
      }
//display(nh,hol);      }
 } 
  
//worst fit
void worstfit(int npr,int hol[10],int pr[10],int nh)
{
int i,j,k,max,flag;
for(i=0;i<npr;i++)
   {
     flag=0;
       for(j=0;j<nh;j++)
        {
            if(pr[i]<=hol[j])
     {
                printf("\nMemory is Allocated to Process %d :(%d)",i+1,pr[i]);
                flag=1;  max=j;
                 for(k=j;k<nh;k++)
                 {
                   if((hol[max]<hol[k])&&(pr[i]<=hol[k]))max=k;
                 }
               if(pr[i]<hol[max])
               {
              //printf("\nCPU is Allocated for process %d",i+1);
              hol[max]=hol[max]-pr[i];
               break;             
               }
              else if(pr[i]==hol[max])
              {
               //printf("\nCPU is Allocated for process %d",i+1);
               
                for(k=max;k<nh-1;k++)
                   hol[k]=hol[k+1];
                nh--;
                 break;
              }         
            }
          } 
    if(flag==0)
    {printf("\n Hole is not Available.....");
    break;}
    display(nh,hol);  
      }
//display(nh,hol);
}
void display(int nh,int hol[10])
{
 printf("\nHoles:");int i=0;
 for(i=0;i<nh;i++){printf("%d\t",hol[i]);}
}

1 Comment

CPU Scheduling Algoritms C Program

 

C - Program to Implement CPU Scheduling Algorithms

**********************************************************************************
Simulation of following CPU scheduling algorithms:
a. FCFS
b. SJF (preemptive and non-preemptive)
c. Priority Scheduling (preemptive and non-preemptive)
d. Round Robin Scheduling

**********************************************************************************

#include<stdio.h>
#include<stdlib.h>
#define MAX 20

typedef struct process
{
    int BT,AT,TAT,WT,PNO,PID;
    char name[10];
}process;

typedef struct RQ
{
    process pr[MAX];
    int f,r;
}RQ;

void get_PCB(process [],int *);
void FCFS(process [],int);
void sort_AT(process [],int);
void sort_BT(RQ []);
void disp_table(process [],int );
void SJF_NP(process [],int);
void SJF_P(process [],int);
void RR(process p[],int n,int);
float cal_avgwt(process [],int );
float cal_avgtat(process [],int );

void menu()
{
    printf("\n\t\t****MENU*****");
    printf("\n\t\t1. FCFS");
    printf("\n\t\t2. SJF NP");
    printf("\n\t\t3. RR");
    printf("\n\t\t4. SJF P");
    printf("\n\t\t5. EXIT");
    printf("\n\t\tEnter Choice: \t");
}
void main()
{
    int ch,TQ,n;
    process P[MAX];
    float avg_WT,avg_TAT;
    clrscr();
    printf("\nEnter Time Quantum");
    scanf("%d",&TQ);
    get_PCB(P,&n);
    do
    {
        clrscr();
        menu();
        scanf("%d",&ch);
        switch(ch)
        {
            case 1:
            {
                sort_AT(P,n);
                FCFS(P,n);
                disp_table(P,n);
                avg_WT=cal_avgwt(P,n);
                avg_TAT=cal_avgtat(P,n);
                printf("\nAVERAGE WT  : %f",avg_WT);
                printf("\nAVERAGE TAT : %f",avg_TAT);
                break;
            }
            case 2:
            {
                SJF_NP(P,n);
                disp_table(P,n);
                avg_WT=cal_avgwt(P,n);
                avg_TAT=cal_avgtat(P,n);
                printf("\nAVERAGE WT  : %f",avg_WT);
                printf("\nAVERAGE TAT : %f",avg_TAT);
                break;
            }
            case 3:
            {
                RR(P,n,TQ);
                disp_table(P,n);
                avg_WT=cal_avgwt(P,n);
                avg_TAT=cal_avgtat(P,n);
                printf("\nAVERAGE WT  : %f",avg_WT);
                printf("\nAVERAGE TAT : %f",avg_TAT);
                break;
            }
            case 4:
            {
                SJF_P(P,n);
                disp_table(P,n);
                avg_WT=cal_avgwt(P,n);
                avg_TAT=cal_avgtat(P,n);
                printf("\nAVERAGE WT  : %f",avg_WT);
                printf("\nAVERAGE TAT : %f",avg_TAT);
                break;
            }
            case 5:
                break;
        }
        getch();
    }while(ch!=5);
}


float cal_avgwt(process p[],int n)
{
    float avg=0;
    int i;
    for(i=0;i<n;i++)
    {
        avg+=p[i].WT;
    }
    avg=avg/n;
    return avg;
}
float cal_avgtat(process p[],int n)
{
    float avg=0;
    int i;
    for(i=0;i<n;i++)
    {
        avg+=p[i].TAT;
    }
    avg=avg/n;
    return avg;
}
int get_first_process(process p[],int n)
{
    int min,j,in;
    min=p[0].AT;
    for(j=0;j<n;j++)
    {
        if(p[j].AT<min)
        {
            in=j;
        }
       }
       return in;
}
void check_arrival(RQ *r,process p[],int time,int n)
{
    int i,j,flag=0;
    for(i=0;i<n;i++)
    {
        for(j=0;j<=r->r;j++)
        {
            if(strcmp(p[i].name,r->pr[j].name)==0)
                flag=1;
            else
                break;
        }
        if(p[i].AT == time && flag==0)
        {
            r->r=r->r + 1;
            r->pr[r->r]=p[i];
        }
        flag=0;
    }
}
void RR(process p[],int n,int tq)
{
    int count=0,i,start,time=0;
    RQ r;
    r.f=r.r=-1;
    start=get_first_process(p,n);
    r.pr[0]=p[start];
    r.f=r.r=0;
    check_arrival(&r,p,time,n);
    while(r.f!=-1)
    {
        for(count=0;count<tq;count++)
        {
            r.pr[r.f].BT--;
            time++;
            if(r.pr[r.f].BT==0)
                break;
            check_arrival(&r,p,time,n);
        }
        if(r.pr[r.f].BT!=0)
        {
            r.pr[r.r+1]=r.pr[r.f];
            r.r++;
        }
        else
        {
            p[r.pr[r.f].PID].TAT=time - r.pr[r.f].AT;
            p[r.pr[r.f].PID].WT=p[r.pr[r.f].PID].TAT - p[r.pr[r.f].PID].BT;
        }
        if(r.f==r.r)
            r.f=r.r=-1;
        else
            r.f++;
    }
}
void sort_BT(RQ *r)
{
    int i,j;
    process temp;
    for(i=r->f;i<=r->r;i++)
    {
        for(j=i+1;j<=r->r;j++)
        {
            if(r->pr[j].BT<r->pr[i].BT)
            {
                temp=r->pr[j];
                r->pr[j]=r->pr[i];
                r->pr[i]=temp;
            }
        }
    }
}

void SJF_NP(process p[],int n)
{
    int time=0,start;
    RQ r;
    r.f=r.r=-1;
    start=get_first_process(p,n);
    r.pr[0]=p[start];
    //p[start].WT=0;
    //p[start].TAT=p[start].BT;
    r.f=r.r=0;
    check_arrival(&r,p,time,n);
    while(r.f!=-1)
    {
        p[r.pr[r.f].PID].WT=time - r.pr[r.f].AT;
        p[r.pr[r.f].PID].TAT=p[r.pr[r.f].PID].WT + r.pr[r.f].BT;
        while(r.pr[r.f].BT != 0)
        {
            time++;
            check_arrival(&r,p,time,n);
            r.pr[r.f].BT--;
        }
        if(r.f==r.r)
            r.f=r.r=-1;
        else
            r.f++;
        sort_BT(&r);
    }
}
int get_total_time(process p[],int n)
{
    int i,sum=0;
    for(i=0;i<n;i++)
    {
        sum+=p[i].BT;
    }
    return sum;
}
void SJF_P(process p[],int n)
{
    int time=0,start,sum,i;
    RQ r;
    r.f=r.r=-1;
    start=get_first_process(p,n);
    r.pr[0]=p[start];
    //p[start].WT=0;
    //p[start].TAT=p[start].BT;
    r.f=r.r=0;
    check_arrival(&r,p,time,n);
    sum=get_total_time(p,n);
    for(i=0;i<sum;i++)
    {
        r.pr[r.f].BT--;
        time++;
        if(r.pr[r.f].BT==0)
        {
            p[r.pr[r.f].PID].TAT=time - r.pr[r.f].AT;
            p[r.pr[r.f].PID].WT=p[r.pr[r.f].PID].TAT - p[r.pr[r.f].PID].BT;
            r.f++;
        }
        check_arrival(&r,p,time,n);
        sort_BT(&r);
    }
}
void sort_AT(process p[],int n)
{
    int i,j;
    process temp;
    for(i=0;i<n;i++)
    {
        for(j=i+1;j<n;j++)
        {
            if(p[j].AT<p[i].AT)
            {
                temp=p[j];
                p[j]=p[i];
                p[i]=temp;
            }
        }
    }
}
void disp_table(process p[],int n)
{
    int i;
    printf("\n\n P_NAME \t AT \t BT \t WT \t TAT \t PNO");
    for(i=0;i<n;i++)
    {
        printf("\n %-10s \t %d \t %d \t %d \t %d \t %d",p[i].name,p[i].AT,p[i].BT,p[i].WT,p[i].TAT,p[i].PNO);
    }
}
void get_PCB(process p[],int *n)
{
    int i;
    printf("\n Enter total no of processes\n");
    scanf("%d",n);
    for(i=0;i<*n;i++)
    {
        printf("\n Enter Following details for Process %d",i+1);
        printf("\n Name :\t");
        scanf("%s",p[i].name);
        printf("\n Arrival Time :\t");
        scanf("%d",&p[i].AT);
        printf("\n Burst Time :\t");
        scanf("%d",&p[i].BT);
        printf("\n Priority :\t");
        scanf("%d",&p[i].PNO);
        p[i].PID=i;
    }
}
void FCFS(process p[],int n)
{
    int i,j,sum=0;
    p[0].TAT = p[0].BT;
    p[0].WT = 0;
    sum = p[0].BT;
    for(i=1;i<n;i++)
    {
        p[i].WT=sum - p[i].AT;
        p[i].TAT=p[i].WT + p[i].BT;
        sum+=p[i].BT;
    }
}



3 Comments