Tuesday, March 24, 2009

C Aptitude Questions and Answers

Predict the output or error(s) for the following:

1.
void main()
{
int const * p=5;
printf("%d",++(*p));
}
Answer:
Compiler error: Cannot modify a constant value.
Explanation:
p is a pointer to a "constant integer".

2.
main()
{
char s[ ]="man";
int i;
for(i=0;s[ i ];i++)
printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);
}
Answer:
mmmm
aaaa
nnnn
Explanation:
s[i], *(i+s), *(s+i), i[s] are all different ways of expressing the same idea.

3.
main()
{
float me = 1.1;
double you = 1.1;
if(me==you)
printf("I love U");
else
printf("I hate U");
}
Answer:
I hate U
Explanation:
For floating point numbers (float, double, long double) the values cannot be predicted exactly.

4.
main()
{
static int var = 5;
printf("%d ",var--);
if(var)
main();
}
Answer:
5 4 3 2 1
Explanation:
When static storage class is given, it is initialized once. The change in the value of a static variable is retained even between the function calls. Main is also treated like any other ordinary function, which can be called recursively.

5.

main()
{
int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} };
int *p,*q;
p=&a[2][2][2];
*q=***a;
printf("%d----%d",*p,*q);
}
Answer:
SomeGarbageValue---1
Explanation:
p=&a[2][2][2] you declare only two 2D arrays, but you are trying to access the third 2D(which you are not declared) it will print garbage values. *q=***a starting address of a is assigned integer pointer. Now q is pointing to starting address of a. If you print *q, it will print first element of 3D array.

6.

main()
{
struct xx
{
int x=3;
char name[]="hello";
};
struct xx *s;
printf("%d",s->x);
printf("%s",s->name);
}
Answer:
Compiler Error
Explanation:
You should not initialize structure variables in declaration.

7.

main()
{
struct xx
{
int x;
struct yy
{
char s;
struct xx *p;
};
struct yy *q;
};
}
Answer:
Compiler Error
Explanation:
The structure yy is nested within structure xx. Hence, the elements are of yy are to be accessed through the instance of structure xx, which needs an instance of yy to be known. If the instance is created after defining the structure the compiler will not know about the instance relative to xx. Hence for nested structure yy you have to declare member.

8.
main()
{
printf("\nab");
printf("\bsi");
printf("\rha");
}
Answer:
hai
Explanation:
\n - newline
\b - backspace
\r - linefeed

9.
main()
{
int i=5;
printf("%d%d%d%d%d%d",i++,i--,++i,--i,i);
}
Answer:
45545
Explanation:
The arguments in a function call are pushed into the stack from left to right. The evaluation is by popping out from the stack. and the evaluation is from right to left, hence the result.

10.
#define square(x) x*x
main()
{
int i;
i = 64/square(4);
printf("%d",i);
}
Answer:
64
Explanation:
the macro call square(4) will substituted by 4*4 so the expression becomes i = 64/4*4 . Since / and * has equal priority the expression will be evaluated as (64/4)*4 i.e. 16*4 = 64

11.
main()
{
char *p="hai friends",*p1;
p1=p;
while(*p!='\0') ++*p++;
printf("%s %s",p,p1);
}
Answer:
ibj!gsjfoet
Explanation:
During the execution of printf p points to last null character and all the content also got incremented.
p1 prints the incremented content.

12.

#define a 10
main()
{
#define a 50
printf("%d",a);
}
Answer:
50
Explanation:
The preprocessor directives can be redefined anywhere in the program. So the most recently assigned value will be taken.

13.

#define clrscr() 100
main()
{
clrscr();
printf("%d\n",clrscr());
}
Answer:
100
Explanation:
Preprocessor executes as a seperate pass before the execution of the compiler. So textual replacement of clrscr() to 100 occurs.The input program to compiler looks like this :
main()
{
100;
printf("%d\n",100);
}
Note:
100; is an executable statement but with no action. So it doesn't give any problem

14.
main()
{
printf("%p",main);
}
Answer:
Some address will be printed.
Explanation:
Function names are just addresses,main() is also a function. So the address of function main will be printed. %p in printf specifies that the argument is an address. They are printed as hexadecimal numbers.

15.

char *someFun1()
{
char temp[ ] = “string";
return temp;
}
main()
{
puts(someFun1());
}
Answer:
Garbage values.

16.

void main()
{
char far *farther,*farthest;
printf("%d..%d",sizeof(farther),sizeof(farthest));
}
Answer:
4..2
Explanation:
the second pointer is of char type and not a far pointer

17.

main()
{
int i=400,j=300;
printf("%d..%d");
}
Answer:
400..300
Explanation:
printf takes the values of the first two assignments of the program. Any number of printf's may be given. All of them take only the first two values. If more number of assignments given in the program,then printf will take garbage values.

18.

main()
{
char *p;
p="Hello";
printf("%c\n",*&*p);
}
Answer:
H

19.

main()
{
int i=1;
while (i<=5) { printf("%d",i); if (i>2)
goto here;
i++;
}
}
fun()
{
here:
printf("PP");
}
Answer:
Compiler error: Undefined label 'here' in function main
Explanation:
Labels have functions scope, in other words The scope of the labels is limited to functions. The label 'here' is available in function fun () Hence it is not visible in function main.

20.

main()
{
int i=1,j=2;
switch(i)
{
case 1: printf("GOOD");
break;
case j: printf("BAD");
break;
}
}
Answer:
Compiler Error: Constant expression required in function main.
Explanation:
The case statement can have only constant expressions .Enumerated types can be used in case statements.

21.

main()
{
int i;
printf("%d",scanf("%d",&i)); // value 10 is given as input here
}
Answer:
1
Explanation:
Scanf returns number of items successfully read and not 1/0. Here 10 is given as input which should have been scanned successfully. So number of items read is 1.

22.

#define f(g,g2) g##g2
main()
{
int var12=100;
printf("%d",f(var,12));
}
Answer:
100

23.

main()
{
char s[]={'a','b','c','\n','c','\0'};
char *p,*str,*str1;
p=&s[3];
str=p;
str1=s;
printf("%d",++*p + ++*str1-32);
}
Answer:
M
Explanation:
p is pointing to character '\n'.str1 is pointing to character 'a' ++*p meAnswer:"p is pointing to '\n' and that is incremented by one." the ASCII value of '\n' is 10. then it is incremented to 11. the value of ++*p is 11. ++*str1 meAnswer:"str1 is pointing to 'a' that is incremented by 1 and it becomes 'b'. ASCII value of 'b' is 98. both 11 and 98 is added and result is subtracted from 32.
i.e. (11+98-32)=77("M");

24.
main()
{
extern int i;
i=20;
printf("%d",sizeof(i));
}
Answer:
Linker error: undefined symbol '_i'.
Explanation:
extern declaration specifies that the variable i is defined somewhere else. The compiler passes the external variable to be resolved by the linker. So compiler doesn't find an error. During linking the linker searches for the definition of i. Since it is not found the linker shows an error.

25.

main()
{
printf("%d", out);
}
int out=100;
Answer:
Compiler error: undefined symbol out in function main.
Explanation:
The rule is that a variable is available for use from the point of declaration. Even though a is a global variable, it is not available for main. Hence an error.

26.

main()
{
extern out;
printf("%d", out);
}
int out=100;
Answer:
100
Explanation:
This is the correct way of writing the previous program.

27.

main()
{
show();
}
void show()
{
printf("I'm the greatest");
}
Answer:
Compier error: Type mismatch in redeclaration of show.
Explanation:
When the compiler sees the function show it doesn't know anything about it. So the default return type (ie, int) is assumed. But when compiler sees the actual definition of show mismatch occurs since it is declared as void. Hence the error.

28.
main()
{
int i=-1;
+i;
printf("i = %d, +i = %d \n",i,+i);
}
Answer:
i = -1, +i = -1
Explanation:
Unary + is the only dummy operator in C. Where-ever it comes you can just ignore it just because it has no effect in the expressions (hence the name dummy operator).

29.

What are the files which are automatically opened when a C file is executed?
Answer:
stdin, stdout, stderr (standard input,standard output,standard error).

30.

what will be the position of the file marker?
a: fseek(ptr,0,SEEK_SET);
b: fseek(ptr,0,SEEK_CUR);

Answer :
a: The SEEK_SET sets the file position marker to the starting of the file.
b: The SEEK_CUR sets the file position marker to the current position of the file.

31.

main()
{
char name[10],s[12];
scanf(" \"%[^\"]\"",s);
}
How scanf will execute?
Answer:
First it checks for the leading white space and discards it.Then it matches with a quotation mark and then it reads all character upto another quotation mark.

32.

What is the problem with the following code segment?
while ((fgets(receiving array,50,file_ptr)) != EOF);
Answer & Explanation:
fgets returns a pointer. So the correct end of file check is checking for != NULL.

33.
main()
{
char *cptr,c;
void *vptr,v;
c=10; v=0;
cptr=&c; vptr=&v;
printf("%c%v",c,v);
}
Answer:
Compiler error (at line number 4): size of v is Unknown.
Explanation:
You can create a variable of type void * but not of type void, since void is an empty type. In the second line you are creating variable vptr of type void * and v of type void hence an error.

34.

main()
{
char *str1="abcd";
char str2[]="abcd";
printf("%d %d %d",sizeof(str1),sizeof(str2),sizeof("abcd"));
}
Answer:
2 5 5

35.

main()
{
char not;
not=!2;
printf("%d",not);
}
Answer:
0

36.

#define FALSE -1
#define TRUE 1
#define NULL 0
main() {
if(NULL)
puts("NULL");
else if(FALSE)
puts("TRUE");
else
puts("FALSE");
}
Answer:
TRUE
Explanation:
Preprocessor doesn't replace the values given inside the double quotes. The check by if condition is boolean value false so it goes to else. In second if -1 is boolean value true hence "TRUE" is printed.

37.

main()
{
int k=1;
printf("%d==1 is ""%s",k,k==1?"TRUE":"FALSE");
}
Answer:
1==1 is TRUE
Explanation:
When two strings are placed together (or separated by white-space) they are concatenated (this is called as "stringization" operation). So the string is as if it is given as "%d==1 is %s". The conditional operator( ?: ) evaluates to "TRUE".

38.

main()
{
int *j;
{
int i=10;
j=&i;
}
printf("%d",*j);
}
Answer:
10
Explanation:
The variable i is a block level variable and the visibility is inside that block only. But the lifetime of i is lifetime of the function so it lives upto the exit of main function. Since the i is still allocated space, *j prints the value stored in i since j points i.

39.

main()
{
int i=-1;
-i;
printf("i = %d, -i = %d \n",i,-i);
}
Answer:
i = -1, -i = 1
Explanation:
-i is executed and this execution doesn't affect the value of i. In printf first you just print the value of i. After that the value of the expression -i = -(-1) is printed.

40.
main()
{
register i=5;
char j[]= "hello";
printf("%s %d",j,i);
}
Answer:
hello 5
Explanation:
if you declare i as register compiler will treat it as ordinary integer and it will take integer value. i value may be stored either in register or in memory.

41.

main()
{
int i=5,j=6,z;
printf("%d",i+++j);
}
Answer:
11
Explanation:
the expression i+++j is treated as (i++ + j)

42.

struct aaa{
struct aaa *prev;
int i;
struct aaa *next;
};
main()
{
struct aaa abc,def,ghi,jkl;
int x=100;
abc.i=0;abc.prev=&jkl;
abc.next=&def;
def.i=1;def.prev=&abc;def.next=&ghi;
ghi.i=2;ghi.prev=&def;
ghi.next=&jkl;
jkl.i=3;jkl.prev=&ghi;jkl.next=&abc;
x=abc.next->next->prev->next->i;
printf("%d",x);
}
Answer:
2
Explanation:
above all statements form a double circular linked list;
abc.next->next->prev->next->i
this one points to "ghi" node the value of at particular node is 2.

43.

struct point
{
int x;
int y;
};
struct point origin,*pp;
main()
{
pp=&origin;
printf("origin is(%d%d)\n",(*pp).x,(*pp).y);
printf("origin is (%d%d)\n",pp->x,pp->y);
}

Answer:
origin is(0,0)
origin is(0,0)
Explanation:
pp is a pointer to structure. we can access the elements of the structure either with arrow mark or with indirection operator.
Note:
Since structure pointer is globally declared x & y are initialized as zeroes

44.

main()
{
char *p;
int *q;
long *r;
p=q=r=0;
p++;
q++;
r++;
printf("%p...%p...%p",p,q,r);
}
Answer:
0001...0002...0004
Explanation:
++ operator when applied to pointers increments address according to their corresponding data-types.

45.

aaa()
{
printf("hi");
}
bbb(){
printf("hello");
}
ccc(){
printf("bye");
}
main()
{
int (*ptr[3])();
ptr[0]=aaa;
ptr[1]=bbb;
ptr[2]=ccc;
ptr[2]();
}
Answer:
bye
Explanation:
ptr is array of pointers to functions of return type int.ptr[0] is assigned to address of the function aaa. Similarly ptr[1] and ptr[2] for bbb and ccc respectively. ptr[2]() is in effect of writing ccc(), since ptr[2] points to ccc.

46.

main()
{
int i =0;j=0;
if(i && j++)
printf("%d..%d",i++,j);
printf("%d..%d,i,j);
}
Answer:
0..0
Explanation:
The value of i is 0. Since this information is enough to determine the truth value of the boolean expression. So the statement following the if statement is not executed. The values of i and j remain unchanged and get printed.

47.

main()
{
int i;
i = abc();
printf("%d",i);
}
abc()
{
_AX = 1000;
}
Answer:
1000
Explanation:
Normally the return value from the function is through the information from the accumulator. Here _AH is the pseudo global variable denoting the accumulator. Hence, the value of the accumulator is set 1000 so the function returns value 1000.

48.

int i;
main()
{
int t;
for ( t=4;scanf("%d",&i)-t;printf("%d\n",i))
printf("%d--",t--);
}
// If the inputs are 0,1,2,3 find the o/p
Answer:
4--0
3--1
2--2
Explanation:
Let us assume some x= scanf("%d",&i)-t the values during execution
will be,
t i x
4 0 -4
3 1 -2
2 2 0

49.

main()
{
int a= 0;int b = 20;char x =1;char y =10;
if(a,b,x,y)
printf("hello");
}
Answer:
hello
Explanation:
The comma operator has associativity from left to right. Only the rightmost value is returned and the other values are evaluated and ignored. Thus the value of last variable y is returned to check in if. Since it is a non zero value if becomes true so, "hello" will be printed.

50.

main()
{
unsigned int i;
for(i=1;i>-2;i--)
printf("c aptitude");
}
Explanation:
i is an unsigned integer. It is compared with a signed value. Since the both types doesn't match, signed is promoted to unsigned value. The unsigned equivalent of -2 is a huge value so condition becomes false and control comes out of the loop.

51.

What are the following notations of defining functions known as?
i. int abc(int a,float b)
{
/* some code */
}

ii. int abc(a,b)
int a; float b;
{
/* some code*/
}
Answer:
i. ANSI C notation
ii. Kernighan & Ritche notation

52.

main()
{
char *p;
p="%d\n";
p++;
p++;
printf(p-2,300);
}
Answer:
300
Explanation:
The pointer points to % since it is incremented twice and again decremented by 2, it points to '%d\n' and 300 is printed.

53.

void main()
{
int k=ret(sizeof(float));
printf("\n here value is %d",++k);
}
int ret(int ret)
{
ret += 2.5;
return(ret);
}
Answer:
Here value is 7

54.

void main()
{
unsigned giveit=-1;
int gotit;
printf("%u ",++giveit);
printf("%u \n",gotit=--giveit);
}
Answer:
0 65535

55.

void main()
{
int i;
char a[]="\0";
if(printf("%s\n",a))
printf("Ok here \n");
else
printf("Forget it\n");
}
Answer:
Ok here
Explanation:
Printf will return how many characters does it print. Hence printing a null character returns 1 which makes the if statement true, thus "Ok here" is printed.

56.

void main()
{
void *v;
int integer=2;
int *i=&integer;
v=i;
printf("%d",(int*)*v);
}
Answer:
Compiler Error. We cannot apply indirection on type void*.
Explanation:
Void pointer is a generic pointer type. No pointer arithmetic can be done on it. Void pointers are normally used for,
1. Passing generic pointers to functions and returning such pointers.
2. As a intermediate pointer type.
3. Used when the exact pointer type will be known at a later point of time.

57.

void main()
{
int i=i++,j=j++,k=k++;
printf(“%d%d%d”,i,j,k);
}
Answer:
Garbage values.
Explanation:
An identifier is available to use in program code from the point of its declaration.
So expressions such as i = i++ are valid statements. The i, j and k are automatic variables and so they contain some garbage value. Garbage in is garbage out (GIGO).

58.

void main()
{
static int i=i++, j=j++, k=k++;
printf(“i = %d j = %d k = %d”, i, j, k);
}
Answer:
i = 1 j = 1 k = 1
Explanation:
Since static variables are initialized to zero by default.

59.

main()
{
while(1)
{
if(printf("%d",printf("%d")))
break;
else
continue;
}
}
Answer:
Garbage values
Explanation:
The inner printf executes first to print some garbage value. The printf returns no of characters printed and this value also cannot be predicted. Still the outer printf prints something and so returns a non-zero value. So it encounters the break statement and comes out of the while statement.

60.

main()
{
unsigned int i=10;
while(i-->=0)
printf("%u ",i);

}
Answer:
10 9 8 7 6 5 4 3 2 1 0 65535 65534…..
Explanation:
Since i is an unsigned integer it can never become negative. So the expression i-- >=0 will always be true, leading to an infinite loop.

61.

main()
{
int x,y=2,z,a;
if(x=y%2) z=2;
a=2;
printf("%d %d ",z,x);
}
Answer:
Garbage-value 0
Explanation:
The value of y%2 is 0. This value is assigned to x. The condition reduces to if (x) or in other words if(0) and so z goes uninitialized.

62.

main()
{
int a[10];
printf("%d",*a+1-*a+3);
}
Answer:
4
Explanation:
*a and -*a cancels out. The result is as simple as 1 + 3 = 4 !

63.
main()
{
unsigned int i=65000;
while(i++!=0);
printf("%d",i);
}
Answer:
1
Explanation:
Note the semicolon after the while statement. When the value of i becomes 0 it comes out of while loop. Due to post-increment on i the value of i while printing is 1.

64.

main()
{
int i=0;
while(+(+i--)!=0)
i-=i++;
printf("%d",i);
}
Answer:
-1
Explanation:
Unary + is the only dummy operator in C. So it has no effect on the expression and now the while loop is, while(i--!=0) which is false and so breaks out of while loop. The value –1 is printed due to the post-decrement operator.

65.

Is the following statement a declaration/definition. Find what does it mean?
int (*x)[10];
Answer
Definition.
x is a pointer to array of(size 10) integers.

66.

#ifdef something
int some=0;
#endif

main()
{
int thing = 0;
printf("%d %d\n", some ,thing);
}

Answer:
Compiler error : undefined symbol some
Explanation:
This is a very simple example for conditional compilation. The name something is not already known to the compiler making the declaration int some = 0; effectively removed from the source code.

67.

#if something == 0
int some=0;
#endif

main()
{
int thing = 0;
printf("%d %d\n", some ,thing);
}

Answer
0 0
Explanation
This code is to show that preprocessor expressions are not the same as the ordinary expressions. If a name is not known the preprocessor treats it to be equal to zero.

68.
int swap(int *a,int *b)
{
*a=*a+*b;*b=*a-*b;*a=*a-*b;
}
main()
{
int x=10,y=20;
swap(&x,&y);
printf("x= %d y = %d\n",x,y);
}
Answer
x = 20 y = 10
Explanation
This is one way of swapping two values. Simple checking will help understand this.

69.
main()
{
int i=5;
printf("%d",++i++);
}
Answer:
Compiler error: Lvalue required in function main
Explanation:
++i yields an rvalue. For postfix ++ to operate an lvalue is required.

70.

main()
{
char *p = “ayqm”;
char c;
c = ++*p++;
printf(“%c”,c);
}
Answer:
b
Explanation:
There is no difference between the expression ++*(p++) and ++*p++. Parenthesis just works as a visual clue for the reader to see which expression is first evaluated.

71.

main()
{
int i=5;
printf(“%d”,i=++i ==6);
}

Answer:
1
Explanation:
The expression can be treated as i = (++i==6), because == is of higher precedence than = operator. In the inner expression, ++i is equal to 6 yielding true(1). Hence the result.

72.
void ( * abc( int, void ( *def) () ) ) ();

Answer::
abc is a ptr to a function which takes 2 parameters .(a). an integer variable.(b). a ptr to a funtion which returns void. the return type of the function is void.

73.

main()
{
while (strcmp(“some”,”some\0”))
printf(“Strings are not equal\n”);
}
Answer:
No output
Explanation:
Ending the string constant with \0 explicitly makes no difference. So “some” and “some\0” are equivalent. So, strcmp returns 0 (false) hence breaking out of the while loop.

74.

main()
{
char str1[] = {‘s’,’o’,’m’,’e’};
char str2[] = {‘s’,’o’,’m’,’e’,’\0’};
while (strcmp(str1,str2))
printf(“Strings are not equal\n”);
}
Answer:
“Strings are not equal”
“Strings are not equal”
….
Explanation:
If a string constant is initialized explicitly with characters, ‘\0’ is not appended automatically to the string. Since str1 doesn’t have null termination.

75.

main()
{
int i = 3;
for (;i++=0;) printf(“%d”,i);
}

Answer:
Compiler Error: Lvalue required.

76.

void main()
{
int *mptr, *cptr;
mptr = (int*)malloc(sizeof(int));
printf(“%d”,*mptr);
int *cptr = (int*)calloc(sizeof(int),1);
printf(“%d”,*cptr);
}
Answer:
garbage-value 0
Explanation:
The memory space allocated by malloc is uninitialized, whereas calloc returns the allocated memory space initialized to zeros.

77.

void main()
{
static int i;
while(i<=10) (i>2)?i++:i--;
printf(“%d”, i);
}
Answer:
32767
Explanation:
Since i is static it is initialized to 0. Inside the while loop the conditional operator evaluates to false, executing i--. This continues till the integer value rotates to positive value (32767). The while condition becomes false and hence, comes out of the while loop, printing the i value.


No comments:

Post a Comment