Showing posts with label array. Show all posts
Showing posts with label array. Show all posts

Tuesday, 28 February 2012

C program to search an element in an array using Binary search



#include<stdio.h>
main()
{
int a[20],i,j,d,t,x,l=0,low,mid,high;
printf("\nEnter the number of elements\n");
scanf("%d",&d);
printf("Enter the numbers\n");
for(i=0;i<d;i++)
scanf("%d",&a[i]);
for(i=0;i<d;i++)
{
for(j=i+1;j<d;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
printf("\nThe sorted list :");
for(i=0;i<d;i++)
printf("%d ",a[i]);
printf("\nEnter the number to be searched\n");
scanf("%d",&x);
low=0;
high=d-1;
while(low<=high)
{
mid=(low+high)/2;
if(x<a[mid])
high=mid-1;
else if(x>a[mid])
low=mid+1;
else
{
if(x==a[mid])
{
l++;
printf("The item %d is found at location %d\n",x,mid+1);
exit(0);
}
}
}
if(l==0)
printf("Item not found\n");
}




Saturday, 4 February 2012

C program to implement a queue using array



#include<stdio.h>
main()
{
int q[10]={0},i,front=-1,rear=-1,max=10,n,item;
printf("\n\tMENU\n1.ENQUEUE\n2.DEQUEUE\n3.DISPLAY\n4.EXIT\n");
do
{
printf("\nEnter your choice\n");
scanf("%d",&n);
switch(n)
{
case 1:
if(rear<max-1)
{
printf("Enter the element\n");
scanf("%d",&item);
if(rear==-1)
{
front=0;
rear=0;
q[rear]=item;
}
else
q[++rear]=item;
}
else
printf("Overflow\n");
break;

case 2:
if(front>=0)
{
printf("The deleted item =%d",q[front]);
if(front==rear)
{
front=-1;
rear=-1;
}
else
front++;
}
else
printf("Underflow\n");
break;

case 3:
if((front==-1)&&(rear==-1))
printf("The queue is empty\n");
else
{
printf("The elements of the queue are :");
for(i=front;i<=rear;i++)
printf("%d\t",q[i]);
}
break;

case 4:
break;

default:
printf("Invalid choice\n");
break;
}
}
while(n!=4);
}



C program to implement a stack using array



#include<stdio.h>
main()
{
int a[10]={0},i,top=-1,max=10,n,x;
printf("\n\tMENU\n1.PUSH\n2.POP\n3.DISPLAY\n4.EXIT\n");
do
{
printf("\nEnter your choice\n");
scanf("%d",&n);
switch(n)
{
case 1:
if(top==max-1)
printf("Overflow\n");
else
{
printf("Enter the element\n");
scanf("%d",&x);
a[++top]=x;
}
break;

case 2:
if(top<0)
printf("Underflow\n");
else
printf("The deleted item =%d",a[top--]);
break;

case 3:
if(top<0)
printf("The stack is empty\n");
else
{
printf("The elements of the stack are :");
for(i=0;i<=top;i++)
printf("%d\n",a[i]);
}
break;

case 4:
break;

default:
printf("Invalid choice\n");
break;
}
}
while(n!=4);
}