Monday, December 28, 2009

programming interviews part4

today we shall discuss some problems which require some c features

1.how to find the machine is little endian or big endian

#include < iostream >
using namespace std;
int main()
{
int n=1;
if(*(char*)&n==1)
cout<<"small";
else
cout<<"big";
cin.sync();
cin.get();
return 0;
}

2.
wap for finding the sizeof a particular datatype without using sizeof()

#include < iostream >
//#define size(T)(*((char*)&T+1-*(char*)&T));
#define SIZEOF(var) (size_t)(&var+1) - (size_t)(&var)

using namespace std;
int main()
{
int a;
cout << SIZEOF(a);
cin.sync();
cin.get();
return 0;
}

3.wap for finding if stack grows upward or downwards


#include < iostream >
using namespace std;
int main()
{
auto int a; auto int b;
if((&b-&a)>0)
cout<<"down";
else
cout<<"up";
cin.sync();
cin.get();
return 0;
}

4.wap for converting from one endian to other

int myreversefunc(int num)
{
int byte0, byte1, byte2, byte3;

byte0 = (num & x000000FF) >> 0 ;
byte1 = (num & x0000FF00) >> 8 ;
byte2 = (num & x00FF0000) >> 16 ;
byte3 = (num & xFF000000) >> 24 ;

return((byte0 << 24) | (byte1 << 16) | (byte2 << 8) | (byte3 << 0));
}

5.
wap a c program for swapping nibbles in byte
nibble=4bits
byte=8bits
#include < stdio.h >

unsigned char swap_nibbles(unsigned char c)
{
unsigned char temp1, temp2;
temp1 = c & 0x0F;
temp2 = c & 0xF0;
temp1=temp1 << 4;
temp2=temp2 >> 4;

return(temp2|temp1); //adding the bits
}

int main()
{
char ch=0x34;
printf("\nThe exchanged value is %x",swap_nibbles(ch));
return 0;
}

6.wap for adding 2 numbers without +

some guys like(rancho in 3 idiots mite come up with answers like a-(-b)
which is somewhat acceptable if interviewer isn't like imperial college principal)

for others

#include < iostream >
using namespace std;
int main()
{
int a=5,b=4;
int c=0,d=0;
while(b!=0)
{
c=a^b;
d=a&b;
a=c;
d << = 1;
b=d;
}
cout << a;
cin.sync();
cin.get();
return 0;
}


7.wap for swapping two numbers without
temp variable

#include < iostream >
using namespace std;
int main()
{
int a=7,b=8;
a-=b;
b+=a;
a-=b;
a*=-1;
cout << a << endl << b;
cin.sync();
cin.get();
return 0;
}

No comments:

Post a Comment