#include<iostream.h>
#include<conio.h>
int main()
{
int n;
cout<<"Enter no. of philosophers:\n";
cin>>n;
int phil[n],x,choice,y,z;
for(x=0;x<n;x++)
phil[x]=0;
do
{
cout<<"\nEnter choice:\n1-Philosopher Wants To Eat\n";
cout<<"2-Philosopher Wants To Think\n3-Status\n4-End\n";
cin>>choice;
switch(choice)
{
case 1:
cout<<"Enter the place of philosopher:\n";
cin>>x;
if(phil[x]==0)
{
y=(x+1)%n;
z=x-1;
if(z==-1)
z=n-1;
if(phil[y]==0&&phil[z]==0)
{
phil[x]=1;
cout<<"Philosopher is now eating.\n";
}
else
cout<<"Neighbours are using chopstick.\n";
}
else
cout<<"Philosopher is already eating.\n";
break;
case 2:
cout<<"Enter the place of philosopher:\n";
cin>>x;
if(phil[x]==1)
{
phil[x]=0;
cout<<"Philosopher is now thinking.\n";
}
else
cout<<"Philosopher was already thinking.\n";
break;
case 3:
cout<<"Current state is:\n";
for(x=0;x<n;x++)
if(phil[x]==0)
cout<<"Think\t";
else
cout<<"Eat\t";
cout<<"\n";
break;
}
}while(choice!=4);
getch();
return 0;
}
OUTPUT:
#include<conio.h>
int main()
{
int n;
cout<<"Enter no. of philosophers:\n";
cin>>n;
int phil[n],x,choice,y,z;
for(x=0;x<n;x++)
phil[x]=0;
do
{
cout<<"\nEnter choice:\n1-Philosopher Wants To Eat\n";
cout<<"2-Philosopher Wants To Think\n3-Status\n4-End\n";
cin>>choice;
switch(choice)
{
case 1:
cout<<"Enter the place of philosopher:\n";
cin>>x;
{
y=(x+1)%n;
z=x-1;
if(z==-1)
z=n-1;
if(phil[y]==0&&phil[z]==0)
{
phil[x]=1;
cout<<"Philosopher is now eating.\n";
}
else
cout<<"Neighbours are using chopstick.\n";
}
else
cout<<"Philosopher is already eating.\n";
break;
case 2:
cout<<"Enter the place of philosopher:\n";
cin>>x;
if(phil[x]==1)
{
phil[x]=0;
cout<<"Philosopher is now thinking.\n";
}
else
cout<<"Philosopher was already thinking.\n";
break;
case 3:
cout<<"Current state is:\n";
for(x=0;x<n;x++)
if(phil[x]==0)
cout<<"Think\t";
else
cout<<"Eat\t";
cout<<"\n";
break;
}
}while(choice!=4);
getch();
return 0;
}
OUTPUT:
No comments:
Post a Comment