Wednesday, April 9, 2008

C++ Questions and answers - 3

Cplusplus technical interview questions for application developers jobs

1.Suppose a one dimensional array AR containing integers is arranged in ascending order. Write a user defined function in C++ to search for one integer from AR with the help of binary search method, returning an integer 0 to show absence ofthe number and integer 1 to show presence of the number in the array. The function should have three parameters: (1) an array AR (2) the number to be searched and (3) the number of elements N in the array.
Ans.
#include
#include
void main()
{
clrscr();
int search(int ar[],int x,int n);
int f,i,N,X,AR[100];
cout<<"Enter the number of elements in the array:"; cin>>N;
cout<<"Enter the elements in ascending order:"; for(i=1;i<=N;i++) cin>>AR[i];
cout<<"Enter the element to be found:"; cin>>X;
f=search(AR,X,N);
if(f==1)
cout<<"x is present."; else cout<<"x is absent."; getch(); } int search(int ar[],int x,int n) { int u=n,l=1,found=0,mid; while(l<=u) { mid=(l+u)/2; if(ar[mid]==x) return(found=1); if(ar[mid]>x)
u=mid-1;
else
l=mid+1;
}
return(found);
}

2. An array A[10][20] is stored in the memory with each element requiring 2 bytes of storage. If the base address of array in the memory is 400, determine the location of A[8][13] when the array is stored as (1) Row major (2) Column major.
Ans. 3
No. of rows r=10
No. of columns c=20
Element size w=2
A[I][J]=A[8][13] i.e., I=8, J=13
Lower bound of rows lr=0 (According to C++)
Lower bound of columns lc=0 (According to C++)
Row Major
A[I][J]=B+w(c(I-lr)+(J-lc))
=400+2(20(8-0)+(13-0))
=400+346
=746
Column Major
A[I][J]=B+w((I-lr)+r(J-lc))
=400+2((8-0)+10(13-0))
=400+276
=676

3.Write a user defined function in C++ to display the multiplication of row element of two dimensional array A[4][6] containing integer.
Ans.
#include
#include
void main()
{
void product_rows(int a[5][6]);
int i,j,a[4][6];
clrscr();
for(i=0;i<=3;i++) for(j=0;j<=5;j++) cin>>a[i][j];
product_rows(a);
getch();
}
void product_rows(int a[4][6])
{
int prod,i,j;
for(i=0;i<=3;i++) { prod=1; for(j=0;j<=5;j++) prod*=a[i][j]; cout<<"The product of "<info;
ptr=front;
front=rear=NULL;
}
else
{
f=front->info;
ptr=front;
front=front->link;
}

No comments: