Tricky c questions and answers




Tricky c programs question for interview and answers with explanation. These questions are for experienced persons.


C advanced interview questions and answers


(1) What will be output if you will compile and execute the following c code?

struct marks{
  int p:3;
  int c:3;
  int m:2;
};
void main(){
  struct marks s={2,-6,5};
  printf("%d %d %d",s.p,s.c,s.m);
}

(a) 2 -6 5
(b) 2 -6 1
(c) 2 2 1
(d) Compiler error
(e) None of these

Answer: (c)
Explanation:

Binary Representation:

  • Binary value of 2: 00000010 (Choose the last two bits)
  • Binary value of 6: 00000110
  • Binary value of -6: 11111001 + 1 = 11111010 (Select the last three bits)
  • Binary value of 5: 00000101 (Choose the last two bits)

Complete memory representation:


(2) What will be output if you will compile and execute the following c code?

void main(){
   int huge*p=(int huge*)0XC0563331;
   int huge*q=(int huge*)0xC2551341;
   *p=200;
   printf("%d",*q);
}

(a)0
(b)Garbage value
(c)null
(d) 200
(e)Compiler error

Answer: (d)
Explanation:

Calculating the Physical Address:

  • Physical address of huge pointer 'p':

    • Huge address: 0xC0563331
    • Offset address: 0x3331
    • Segment address: 0xC056
    • Physical address = Segment address * 0x10 + Offset address = 0xC056 * 0x10 + 0x3331 = 0xC0560 + 0x3331 = 0xC3891
  • Physical address of huge pointer 'q':

    • Huge address: 0xC2551341
    • Offset address: 0x1341
    • Segment address: 0xC255
    • Physical address = Segment address * 0x10 + Offset address = 0xC255 * 0x10 + 0x1341 = 0xC2550 + 0x1341 = 0xC3891

Since both huge pointers 'p' and 'q' are pointing to the same physical address, the content of 'q' will also be the same as the content of 'p.


(3) Write c program which display mouse pointer and position of pointer.(In x coordinate, y coordinate)?

Answer:
#include”dos.h”
#include”stdio.h”
void main()
{
union REGS i,o;
int x,y,k;
//show mouse pointer
i.x.ax=1;
int86(0x33,&i,&o);
while(!kbhit()) //its value will false when we hit key in the key board
{
i.x.ax=3; //get mouse position
x=o.x.cx;
y=o.x.dx;
clrscr();
printf("(%d , %d)",x,y);
delay(250);
int86(0x33,&i,&o);
}
getch();
}

(4) Write a c program to create dos command: dir.

Answer:

Step 1: Write following code.

#include “stdio.h”
#include “dos.h”
void main(int count,char *argv[]){
   struct find_t q ;
   int a;
   if(count==1)
      argv[1]="*.*";
      a = _dos_findfirst(argv[1],1,&q);
      if(a==0){
         while (!a){
            printf(" %s\n", q.name);
            a = _dos_findnext(&q);
         }
      }
      else{
         printf("File not found");
      }
}

Step 2: Save the file as list.c (you can choose any name).

Step 3: Compile and execute the file.

Step 4: Right-click on "My Computer" in the Windows XP operating system and select "Properties."

Step 5: Navigate to Advanced -> Environment Variables.

Step 6: In the window that appears, click on the "New" button (located inside the red box).



Step 7:

  • Variable name: path
  • Variable value: c:\tc\bin\list.c (Specify the path where you have saved the file)


Step 8:

  • Open the command prompt.
  • Write list and press Enter.
  • Explore command line argument tutorials.

(6) What will be output if you will compile and execute the following c code?

void main(){
   int i=10;
   static int x=i;
   if(x==i)
      printf("Equal");
   else if(x>i)
      printf("Greater than");
   else
      printf("Less than");
}

(a) Equal
(b) Greater than
(c) Less than
(d) Compiler error
(e) None of above

Answer: (d)
Explanation:

Static variables are considered load-time entities, whereas auto variables are run-time entities. It is not permissible to initialize any load-time variable with a run-time variable. In the context of this example, 'i' is a run-time variable, while 'x' is a load-time variable.


(7) What will be output if you will compile and execute the following c code?

void main(){
   int i;
   float a=5.2;
   char *ptr;
   ptr=(char *)&a;
   for(i=0;i<=3;i++)
      printf("%d ",*ptr++);
}

(a)0 0 0 0
(b)Garbage Garbage Garbage Garbage
(c)102 56 -80 32
(d)102 102 -90 64
(e)Compiler error

Answer: (d)
Explanation:

In C, the float data type is a four-byte data type, while a char pointer, such as 'ptr,' can point to one byte of memory at a time. Considering the memory representation of the float variable 'a' initialized to 5.2:



The ptr pointer will sequentially point to the fourth, third, second, and first bytes of memory. The content of each byte is as follows:

  • Content of the fourth byte:

    • Binary value: 01100110
    • Decimal value: 64 + 32 + 4 + 2 = 102
  • Content of the third byte:

    • Binary value: 01100110
    • Decimal value: 64 + 32 + 4 + 2 = 102
  • Content of the second byte:

    • Binary value: 10100110
    • Decimal value: -128 + 32 + 4 + 2 = -90
  • Content of the first byte:

    • Binary value: 01000000
    • Decimal value: 64

Note: The character pointer treats the Most Significant Bit (MSB) of each byte, i.e., the leftmost bit of the given figure, as the sign bit.


(8) What will be output if you will compile and execute the following c code?

void main(){
   int i;
   double a=5.2;
   char *ptr;
   ptr=(char *)&a;
   for(i=0;i<=7;i++)
      printf("%d ",*ptr++);
}

(a) -51 -52 -52 -52 -52 -52 20 64
(b) 51 52 52 52 52 52 20 64
(c) Eight garbage values.
(d) Compiler error
(e) None of these

Answer: (a)
Explanation:

In C, the double data type is an eight-byte data type, while a char pointer, such as 'ptr,' can point to one byte of memory at a time. Considering the memory representation of the double variable 'a' initialized to 5.2:



The ptr pointer will sequentially point to the eighth, seventh, sixth, fifth, fourth, third, second, and first bytes of memory, as shown in the figure above. The content of each byte is as follows:

  • Content of the eighth byte:

    • Binary value: 11001101
    • Decimal value: -128 + 64 + 8 + 4 + 1 = -51
  • Content of the seventh byte:

    • Binary value: 11001100
    • Decimal value: -128 + 64 + 8 + 4 = -52
  • Content of the sixth byte:

    • Binary value: 11001100
    • Decimal value: -128 + 64 + 8 + 4 = -52
  • Content of the fifth byte:

    • Binary value: 11001100
    • Decimal value: -128 + 64 + 8 + 4 = -52
  • Content of the fourth byte:

    • Binary value: 11001100
    • Decimal value: -128 + 64 + 8 + 4 = -52
  • Content of the third byte:

    • Binary value: 11001100
    • Decimal value: -128 + 64 + 8 + 4 = -52
  • Content of the second byte:

    • Binary value: 000010100
    • Decimal value: 16 + 4 = 20
  • Content of the first byte:

    • Binary value: 01000000
    • Decimal value: 64

Note: The character pointer treats the Most Significant Bit (MSB) of each byte, i.e., the leftmost bit of the above figure, as the sign bit.


(9) What will be output if you will compile and execute the following c code?

void main(){
   printf("%s","c" "question" "bank");
}

(a) c question bank
(b) c
(c) bank
(d) cquestionbank
(e) Compiler error

Answer: (d)
Explanation:

In C, the string constant 'xy' is equivalent to the concatenation of two string constants 'x' and 'y', denoted as 'x' 'y'.


(10) What will be output if you will compile and execute the following c code?

void main(){
   printf("%s",__DATE__);
}

(a) Current system date
(b) Current system date with time
(c) null
(d) Compiler error
(e) None of these

Answer: (a)
Explanation:

__DATE__ is a global identifier in C that returns the current system date.

(11) What will be output if you will compile and execute the following c code?

void main(){
   char *str="c-pointer";
   printf("%*.*s",10,7,str);
}

(a) c-pointer
(b) c-pointer
(c) c-point
(d) cpointer null null
(e) c-point

Answer: (e)
Explanation:

The format specifier %*.*s in the printf function serves the following purposes:

  • The first * denotes the width, indicating the number of spaces allocated to print the string.
  • The second * denotes precision, specifying the number of characters to be printed from any given string.

The output of the code using this format specifier is illustrated in the following figure:




(12) What will be output if you will compile and execute the following c code?

void start();
void end();
#pragma startup start
#pragma exit end
int static i;
void main(){
   printf("\nmain function: %d",++i);
}
void start(){
   clrscr();
   printf("\nstart function: %d",++i);
}
void end(){
   printf("\nend function: %d",++i);
   getch();
}

(a)
main function: 2
start function: 1
end function:3
(b)
start function: 1
main function: 2
end function:3
(c)
main function: 2
end function:3
start function: 1
(d) Compiler error
(e) None of these

Answer: (b)
Explanation:

Every C program typically begins execution with the main function and concludes with a null statement. However, the #pragma startup directive allows for the invocation of a function just before the main function, and similarly, #pragma exit provides a mechanism to call a function at program termination.

(13) What will be output if you will compile and execute the following c code?

void main(){
   int a=-12;
   a=a>>3;
   printf("%d",a);
}

(a) -4
(b) -3
(c) -2
(d) -96
(e) Compiler error

Answer :( c)
Explanation:

The binary representation of 12 is: 00000000 00001100. To obtain the binary value of -12, one needs to take the 2’s complement of 12, which is:



The binary value of -12, obtained through the 2’s complement of 12, is: 11111111 11110100.


Right Shifting Rule:

  • Rule 1: If the number is positive, fill vacant spaces on the left side with 0s.
  • Rule 2: If the number is negative, fill vacant spaces on the left side with 1s.

In this particular case, where the number is negative, perform a right shift of all binary digits by three spaces and fill the vacant spaces on the left side with 1s, as illustrated in the following figure:



Given that it is a negative number, the output will also be negative, represented in 2’s complement form.



Hence final out put will be:


As a result of the right shift and considering its 2’s complement representation, the binary value corresponds to the decimal value of -2. Therefore, the output is indeed -2.

(14) What will be output if you will compile and execute the following c code?

#include "string.h"
void main(){
   clrscr();
 printf("%d%d",sizeof("string"),strlen("string"));
getch();
}
(a) 6 6
(b) 7 7
(c) 6 7
(d) 7 6
(e) None of these

Answer: (d)
Explanation:

The sizeof operator in C returns the size of the entire array, including the null character ('\0'), for a string declared as an array of characters. On the other hand, the strlen function from the <string.h> library returns the length of the string, excluding the null character.


(15) What will be output if you will compile and execute the following c code?

void main(){
   static main;
   int x;
   x=call(main);
   clrscr();
   printf("%d ",x);
   getch();
}
int call(int address){
   address++;
   return address;
}
(a) 0
(b) 1
(c) Garbage value
(d) Compiler error
(e) None of these

Answer: (b)
Explanation:

While 'main' is not a reserved keyword in C, it holds a special significance as the entry point for program execution. The term 'main' can also be used as a variable name within the 'main' function and other functions.

(16) What will be output if you will compile and execute the following c code?

void main(){
   int a,b;
   a=1,3,15;
   b=(2,4,6);
   clrscr();
   printf("%d ",a+b);
   getch();
}
(a) 3
(b) 21
(c) 17
(d) 7
(e) Compiler error

Answer: (d)
Explanation:
In C, the comma serves a dual purpose as both a separator and an operator. In the expressions:
a=1, 3, 15;
b= (2, 4, 6);
The comma acts as an operator. The comma operator enjoys the lowest precedence among operators, and its associativity is from left to right. Assigning the priority of each operator in the first statement:


Hence, in the first statement, the value 1 will be assigned to 'a'.

Now, assigning the priority of each operator in the second statement:




(17) What will be output if you will compile and execute the following c code?

int extern x;
void main()
   printf("%d",x);
   x=2;
   getch();
}
int x=23;

(a) 0
(b) 2
(c) 23
(d) Compiler error
(e) None of these

Answer: (c)
Explanation:

Extern variables in C enable the program to locate the declaration of a variable anywhere in the program. This provides flexibility in accessing variables declared outside the current scope or file.

(18) What will be output if you will compile and execute the following c code?

void main(){
   int i=0;
   if(i==0){
      i=((5,(i=3)),i=1);
      printf("%d",i);
   }
   else
      printf("equal");
}

(a) 5
(b) 3
(c) 1
(d) equal
(e) None of above

Answer: (c)
Explanation:

(19) What will be output if you will compile and execute the following c code?

void main(){
   int a=25;
   clrscr();
   printf("%o %x",a,a);
   getch();
}

(a) 25 25
(b) 025 0x25
(c) 12 42
(d) 31 19
(e) None of these

Answer: (d)
Explanation:

The format specifier %o is used in C to print numbers in octal format, while %x is used to print numbers in hexadecimal format. It's important to note that in C, octal numbers are denoted by a leading 0, and hexadecimal numbers start with '0x'.

(20) What will be output if you will compile and execute the following c code?

#define message "union is\
power of c"
void main(){
   clrscr();
   printf("%s",message);
   getch();
}

(a) union is power of c
(b) union ispower of c
(c) union is
Power of c
(d) Compiler error
(e) None of these

Answer: (b)
Explanation:


If you wish to write a macro constant across multiple lines, it can be concluded with the character ".This indicates a continuation of the macro definition onto the next line.

(21) What will be output if you will compile and execute the following c code?

#define call(x) #x
void main(){
   printf("%s",call(c/c++));
}

(a)c
(b)c++
(c)#c/c++
(d)c/c++
(e)Compiler error

Answer: (d)
Explanation:

The '#' symbol in C is known as the stringizing operator. It converts the macro function call argument into a string. For example, consider the following lines in the intermediate file:

test.c 1:
test.c 2: void main(){
test.c 3: printf("%s","c/c++");
test.c 4: }
test.c 5:
It's evident that the macro call is replaced by its argument in string format during preprocessing.



(22) What will be output if you will compile and execute the following c code?

void main(){
   if(printf("cquestionbank"))
      printf("I know c");
   else
      printf("I know c++");
}

(a) I know c
(b) I know c++
(c) cquestionbankI know c
(d) cquestionbankI know c++
(e) Compiler error

Answer: (c)
Explanation:

The return type of the printf function in C is an integer, representing the number of characters it prints, including blank spaces. In the context of an if condition, the printf function will return 13. In C, any non-zero value is considered true, so the else part will not be executed.

If you have any doubts regarding the explanations provided for the above tricky questions, feel free to ask in the comment section.

61 comments:

Anonymous said...

nice questions and answers

ganesh said...

good qustions

Anonymous said...

good question as well ans
but i didnt got explanation of qustion 16
so please elborate explanation if possibe

Unknown said...

this is really a vry good stuff..

Anonymous said...

good questions :) thanks

Anonymous said...

thanks :) good questions

Piyush Shrivastava said...

Nice collection here. I am an engineering student and these questions will sure help in building up my programming aptitude. Thanks

amit said...

can someone please elaborate about question no.16

sandeep yadav said...

very very good questions...

adarsh said...

ON question 16:
when i=2,3,4;//i.e without brackets
priority in given to first one.

when i=(2,3,4)//i.e with brackets
priority is given to last one

amit said...

I'm very much greatful to you adarsh for your clarification.......

amit said...

I'm very greatful to you for your clarification.

Anonymous said...

(6) What will be output if you will compile and execute the following c code?

void main(){
int i=10;
static int x=i;
if(x==i)
printf("Equal");
else if(x>i)
printf("Greater than");
else
printf("Less than");
}



This code perefctly compiles in C++ giving answer "EQUAL"

Anonymous said...

Thanks for Qs :) really a good set of Qs for experienced people.
Can anyone share some more interesting Qs like this.

Anonymous said...

explaination for 16th ques?

Unknown said...

first we use clrscr()functionafter main function......in 16...the value of a and b in ram....then we useing clrscr....which used clear the memory.....printf not found any value and give it compile time error...........

Unknown said...

brackets means starting of stack.....means last in first out(LIFO)

Yadhunandana Kumaraiah said...

challenging questions that floating storage question is awesome.........

Unknown said...

nice questions..............
this will help me a lot.

Unknown said...

Will you please explain the 3rd program mouse pointer

madhu said...

1,2,3,4,5,1,2,3,1,2,3,4,5......
separate the series like
1,,2,3,4,5 and a,2,3
and 1,2,3,4,5
ten find the sum of this series .. guys please help me ......

madhu said...

write a program to find the power of 12 without using pow function ?

the output should be in the form of

2 power 12

3 power 12...so on ...

Anonymous said...

int powi(int number, int exponent)
{
int i, product = 1;
for (i = 0; i < exponent; i++)
product *= number;

return product;
}

void main()
{
int rez=0,i=0;
for(i=0;i<5;i++)
{
rez=powi(12,i);
printf("\n%d power of 12 is %d",i,rez);
}

}

Dr.Sexpert said...

Not in getting laid. {()}---<--8

Grammar Nazi said...

*explanation

Unknown said...

why array index starts with zero

Unknown said...

why this code gives output :
-2 -1
instead of
2 1

#include
struct marks {
int a:1;
int b:2;
};

int main(){
struct marks obj={1,6};
printf("%d %d\n",obj.b,obj.a);

}

Unknown said...

#include
long int power(int ,int );

int main(){
int i,n;
printf("enter a number(not greater than 5 other wise overflow will occer.) to generate power series :\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
printf("%d power 12 is : %ld\n",i,power(i,12));
}

long int power(int a,int b){
int c;
long int ans=1;
for(c=1;c<=b;c++)
ans=ans*a;
return ans;
}

Anonymous said...

In "C" it will give compilation error, whereas in C++ it will give "EQUAl"

P@m said...

thanks itz really helpfull :)

Anonymous said...

void start();
void end();
#pragma startup start
#pragma exit end
int static i;
void main(){
printf("\nmain function: %d",++i);
}
void start(){
clrscr();
printf("\nstart function: %d",++i);
}
void end(){
printf("\nend function: %d",++i);
getch();
}


On Fedora16 it will print output as:

main function:1

Sathish said...

Very good stuff... Thanks :-0

neerajkumarghildiyal said...

really very intresting sirrrrrrrrrrrrrr.........

Anonymous said...

@pankaj verma
for b there are only 2 bits allocated so 110 ->10 first bit(most sig) 1 so -ve =>-2
and for a there is only 1 bit alloc so 1->1 first bit(most sig) 1 so -ve hence it => -1

Unknown said...

1 in your program can be represented in binary by 00000001..And 6 is as 00000110..Now using a:1 means taking the single lsb i.e 1 which also represents negative sign..alternativly if you use a:2,your obj.a will be +1..Again,for 6,b:2 i,e taking the 2 lsb's from 6 which is 10 i.e representation of -2,alternatively using b:4 would mean taking 4 lsb's as 0110,so obj.b woild be 6..

Unknown said...

very good stuff

Unknown said...

The following C program segfaults of IA-64, but works fine on IA-32.

int main()
{
int* p;
p = (int*)malloc(sizeof(int));
*p = 10;
return 0;
}

Why does it happen so?

Unknown said...

What is the differnce between the following function calls to
scanf?(Please notice the space carefully in the second call. Try
removing it and observe the behaviour of the program)
#include
int main()
{
char c;
scanf("%c",&c);
printf("%c\n",c);

scanf(" %c",&c);
printf("%c\n",c);

return 0;
}

Unknown said...

What is the use of the following macro?
#define DPRINTF(x) printf("%s:%d\n",#x,x)

ece said...

could i get answer for the following question.

Problem;
Given an English text print out the list of words and their anagrams in their order of occurrence. Word A is an anagram of word B if it can be derived from word B by merely shuffling the letters in word B.

Important Points:

Text can contain words in upper case as well as lower case and punctuation marks

Anagrams are not to be case sensitive

The word and its anagrams are to be printed in the order of their occurrence in the text, separated by a blank.

If a word has no anagram in the text, then do not print it

If a word or its anagram occurs more than once do not print it again

Numbers are to be considered as valid words

Input:

A text containing K English words (where K <= 5000), with spaces and punctuation marks

Output:

The output should contain the word (in its order of occurrence in the text) and its set of anagrams in the text (again in their order of occurrence), separated by blanks

Each new list of words and anagrams should begin on a new line

All words in the output should be printed in lower case characters

Sample Input

Sample Output

Parts of the world have sunlight for close to 24 hours during summer. Dan went to the north pole to lead an expedition during summer. He had a strap on his head to identify himself as the leader. Dan had to deal with the sun never going down for 42 consecutive days and his leadership strap soon became a blindfold. He wondered what kind of traps lay ahead of him.

parts strap traps

24 42

dan and

lead deal

Unknown said...

Very good questions.........hope to see more in future!!!!

Anonymous said...

int
rpow(int num, int power)
{
return power == 0 ? 1 : num * rpow(num, power-1);
}



main()
{
int num, power;
printf("Enter number : ");
scanf("%d", &num);
printf("to +ve power : ");
scanf("%d", &power);
if (power < 0) {
printf("power must be +ve");
exit(-1);
}
printf("number %d raised to power %d is %d\n", num, power, rpow(num, power));
}

neerajkumarghildiyal said...

sir plz.. add tutorials for file handling in c also.

Anonymous said...

good work

Unknown said...

explain the output of following question??
#include
int main()
{
int a=-10;
char *p=(char *)&a;
printf("%d",*p);
return 0;
}

Unknown said...

Doubt in
void main(){
int i;
double a=5.2;
char *ptr;
ptr=(char *)&a;
for(i=0;i<=7;i++)
printf("%d ",*ptr++);
}

Anonymous said...

yeasuuuuuuu

vijay kumar said...

thanks for logical information

Anonymous said...

Really Helpful questions...good coverage of all topics...Thanks a lot!

Anonymous said...

kusuuuuuuuuuuuuuuuuuuuuuuu

Himanshu said...

use fflush(); just before the 2nd scanf function...

Unknown said...

int main()
{
int a=15;
a=(++a)+015+0x15;
printf("%d",a);
return 1;
}

i don't know how to work octal and hex hear so plz tell me what is o/p with explanation of that prog.

shravan kashyap said...

Hello!, could you plz explain me the precedence order in 16th question , especially II case i..e a=(1,2,3),
in a much more clear way.
Thank you

thulasi said...

This site will gives more time pass for lovers of C, and can love C, in deep.

Unknown said...

ITS GOOD FOR US

Rahul Barahpuria said...

binary form of int value 10 is 00000000 00001010 (2Bytes)
binary form of -10 is its 2's compliment i.e., 11111111 11110110

Now, size of char data type is 1 byte only,
so, *p will have value 11110110 only. (11111111 is excluded)
Negative form of 11110110 is its 2's compliment i,e. 00001010 whose decimal value is -10 which will be shown as the output.

Archana said...

i = a, b, c;// stores a into i, discarding the unused b and c rvalues
i = (a, b, c);// stores c into i, discarding the unused a and b rvalues

Comma works as an operator in first case. Precedence of comma operator is least in operator precedence table. So the assignment operator takes precedence over comma and the expression “i = a, b, c″ becomes equivalent to “(i = a), b, c″.

In the second case,brackets are used.So comma operator is executed first.(a, b, c) is a sequence of expressions, separated by commas, which evaluates to the last expression c.

Hope this helps!

Archana said...

i = a, b, c;// stores a into i, discarding the unused b and c rvalues
i = (a, b, c);// stores c into i, discarding the unused a and b rvalues

Comma works as an operator in first case. Precedence of comma operator is least in operator precedence table. So the assignment operator takes precedence over comma and the expression “i = a, b, c″ becomes equivalent to “(i = a), b, c″.

In the second case,brackets are used.So comma operator is executed first.(a, b, c) is a sequence of expressions, separated by commas, which evaluates to the last expression c.

Hope this helps!

Archana said...

50
The statement mixes decimal,octal(o)and hexadecimal(ox).
Before addition,everything will be converted to binary format.

Unknown said...

very helpful site i love this

Surya Kalvas said...

Suggest me a book for these type of tricky problems of c