contoh-contoh program bahasa C
contoh 1
//Queue
using static memory allocation
#include
<iostream.h>
#include
<conio.h>
int
top=-1;
const
int bottom=0;
int
q_arr[10];
void
insert(void)
{
if(top==-1)
cout<<"\n\nList is
Empty\n\n";
if(top==10)
{
cout<<"\nList overflow\n";
goto out;
}
cout<<"\nEnter info to be
inserted:-";
cin>>q_arr[top+1];
top=top+1;
out:
}
void
del(void)
{
int
c=0;
if(top==-1)
{
cout<<"\n\nList
Underflow\n";
goto out;
}
cout<<"\n\nInfo which is deleted
by you is "<<q_arr[bottom];
while(c<top)
{
q_arr[c]=q_arr[c+1];
c++;
}
top=top-1;
out:
}
void
main()
{
clrscr();
int choice;
while(1)
{
cout<<"\n\n\nChoose your
choice\n";
cout<<"1) Insert element\n";
cout<<"2) Delete element\n";
cout<<"3) Exit\n";
cout<<"Enter your choice:-";
cin>>choice;
switch(choice)
{
case 1 : insert();
break;
case 2 :
del();
break;
case 3 :
goto out;
default: cout<<"\n\nEntered
Info is Invalid\nTry again\n\n";
}
}
out:
}
contoh 2
//Queue
using dynamic memory allocation (FIFO)
#include
<iostream.h>
#include
<conio.h>
struct
queue
{
int data;
struct queue *next;
};
static
int top=-1;
queue
*head=NULL;
void
insert(void)
{
if(top==-1)
cout<<"\n\nList is
Empty\n";
if(top>=9)
{
cout<<"\n\nList
Overflow\n";
goto out;
}
else
{
queue *newl;
newl=new queue;
cout<<"\n\nEnter your Data :-
";
cin>>newl->data;
if(head==NULL) //If head is Null inserting at first position
{
newl->next=head;
head=newl;
}
else //Inserting at Last Position
{
queue *count=head;
while(count->next!=NULL)
count=count->next;
count->next=newl;
newl->next=NULL;
}
top=top+1;
}
out:
}
void
del(void)
{
if(top<0)
{
cout<<"\n\nList
Underflow\n";
goto out;
}
else
{
queue *temp;
cout<<"\n\nData Which was Deleted
was "<<head->data;
temp=head;
head=head->next;
delete(temp);
top=top-1;
}
out:
}
void
main()
{
clrscr();
int choice;
while(1)
{
cout<<"\n\n\nChoose your
choice\n";
cout<<"1) Insert\n";
cout<<"2) Delete\n";
cout<<"3) Exit\n";
cout<<"Enter your choice :- ";
cin>>choice;
switch(choice)
{
case 1 : insert();
break;
case 2 : del();
break;
case 3 : goto out;
default: cout<<"\n\nEnter
choice is Invalid\nTry Again\n\n";
}
}
out:
}
0 komentar:
Post a Comment