Sunday, December 12, 2010

Binary search on array

#include
#include

#define SIZE 20

class array
{
int a[SIZE];
int n;

public:
array();
void read();
void binary_search();
void display();
};

array::array()
{
n=0;
}

void array::read()
{
int i;
cout<<"\nEnter the size of the array:";
cin>>n;
cout<<"\nEnter the "< for(i=0;i {
cin>>a[i];
}
}

void array::binary_search()
{
int i,j,mid,lb,ub,flag;
int temp,item;

for(i=0;i {
for(j=i+1;j {
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
cout<<"\nThe sorted array is:\n";
for(i=0;i cout<<"\t" < cout<<"\nEnter the item to be searched:";
cin>>item;



for(lb=0,ub=n-1;lb {
mid=(lb+ub)/2;
if(a[mid]==item)
{
flag=1;
break;
}
else if(item>a[mid])
{
lb=mid+1;
}
else if(item {
ub=mid-1;
}
else
{
flag=0;
}
}
if(flag==1)
{
cout<<"\n\nThe element "< }
else
{
cout<<"\nThe element is not found in array!!!!";
}
}

void array::display()
{
int i;

cout<<"\nThe array is \n";
for(i=0;i {
cout< }
}

void main()
{
array a1;

clrscr();

a1.read();
a1.display();
a1.binary_search();

getch();
}

Saturday, May 8, 2010

MULTIPLY TWO MATRICES AND PRINT THE RESULT

//Program to multiply two matrices and print the result.
#include
#include
void main()
{
int a[10][10],b[10][10],m[10][10];
int r1,c1,r2,c2,i,j,k;
char ch;
do
{
clrscr();
printf("Enter the order of first matrix:");
scanf("%d\n%d",&r1,&c1);
printf("Enter the order of second matrix:");
scanf("%d\n%d",&r2,&c2);
printf("Enter the %d elements of the matrix 1:",r1*c1);
for(i=0;i {
for(j=0;j {
scanf("%d",&a[i][j]);
}
}
printf("Enter the %d elements of the matrix 2:",r2*c2);
for(i=0;i {
for(j=0;j {
scanf("%d",&b[i][j]);
}
}
printf("The first Matrix is:\n");
for(i=0;i {
for(j=0;j {
printf("%d ",a[i][j]);
}
printf("\n");
}
printf("The second matrix is:\n");
for(i=0;i {
for(j=0;j {
printf("%d ",b[i][j]);
}
printf("\n");
}
if(c1==r2)
{
for(i=0;i {
for(j=0;j {
m[i][j]=0;
for(k=0;k {
m[i][j]+=a[i][k]*b[k][j];
}
}
}
printf("The result after multiplication is:\n");
for(i=0;i {
for(j=0;j {
printf("%d ",m[i][j]);
}
printf("\n");
}
}
else
{
printf("Multiplication is not possible!!");
}
printf("\nDo You Want to Continue(Y/N):");
}
while((ch=getch())=='y'||ch=='Y');
}



Output
--------------------------------------
Enter the order of first matrix:2 2
Enter the order of second matrix:2 2
Enter the 4 elements of the matrix 1:1 1 1 1
Enter the 4 elements of the matrix 2:1 1 1 1
The first Matrix is:
1 1
1 1
The second matrix is:
1 1
1 1
The result after multiplication is:
2 2
2 2

Do You Want to Continue(Y/N):N