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

Saturday, May 21, 2011

C program to implement Binary Search

#include
#include
int main()
{
int a[50],item,n,beg,last,mid,i;
printf("\n\n\t\t enter desired array size ");
scanf(" %d",&n);
printf("\n\n\t\t enter array elements \n");
for(i=0;i< n ;i++)
{
scanf("%d",&a[i]);
}
printf("\n\n\t\t enter elements to be searched for");
scanf("%d",&item);
beg=0;
last=n-1;
while(beg<=last)
{
mid=(beg+last)/2;
if(item==a[mid])
{
printf("\n\n\t\t element found at position %d",mid+1);
}
else if(item>a[mid])
beg=mid+1;
else
last=mid-1;
printf("\n\n\t\t element not found");
}
getch();
}

C program to implement Linear Search

//program for linear search
#include
#include
int main()
{
int a[10],item,n,i;
printf("\n\n\t how many elements do you want to enter in the array:");
scanf("%d",&n);
printf("\n\n\t enter the elements of the array:");
for(int i=0;iscanf("%d",&a[i]);
printf("\n\n\t enter the element to be searched:");
scanf("%d",&item);
for(i=0;i{
if(a[i]==item)
printf("\n\n\t element is found at position %d",i+1);
else
printf("\n\n\t the elememt is not present in the array:");
}
getch();
}

C program to remove duplicates from an array

/*Read elements into an array. Write a Program to find duplicate
elements in the array and display the resultant array by removing
the duplicates.*/


int main()
{
int a[100],i,j,k,b,t=0;


printf("\nEnter the size of 1 dimensional array");
scanf("%d",&b);
printf("\nEnter the array");
for(i=0;i scanf("%d",&a[i]);
for(i=0;i {
for(j=i+1;j {
if(a[i]==a[j])
{
t++;
for(k=j;k a[k]=a[k+1];

}
}
}
for(i=0;i<=b-t;i++)
printf("\n%d",a[i]);
system("pause");
return 0;
}

C program To reverse the contents of an Array

int main()
{
int a[100],i,j,k,b,t;


printf("\nEnter the size of 1 dimensional array");
scanf("%d",&b);
printf("\nEnter the array");
for(i=0;i scanf("%d",&a[i]);
for(j=0;j<=b/2;j++)
{
t=a[j];
a[j]=a[b-j-1];
a[b-j-1]=t;
}

for(k=0;kprintf("\n%d",a[k]);
system("pause");
return 0;
}

C program to understand Single dimension array

Read values into an one dimensional array and compute the sum of
their squares


int main()
{
int a[100],i,j,b,sum=0;


printf("\nEnter the size of 1 dimensional array");
scanf("%d",&b);
printf("\nEnter the array");
for(i=0;i scanf("%d",&a[i]);
printf("\nThe sum of there squares is");
for(j=0;j {
sum=sum+pow(a[j],2);
}
printf("%d",sum);
system("pause");
return 0;
}