Documente Academic
Documente Profesional
Documente Cultură
Interview Questions
This page lists some common interview questions for software engineers.
Questions
Click on the question to see its answer.
Useful tips
1. Introduction
9. Conclusion
Logic questions
10. Given a rectangular (cuboidal for the puritans) cake with a rectangular
piece removed (any size or orientation), how would you cut the
remainder of the cake into two equal halves with one straight cut of a
knife ?
11.You're given an array containing both positive and negative integers and
required to find the subarray with the largest sum (O(N) a la KBL).
Write a routine in C for the above.
14. How many points are there on the globe where by walking one mile
south, one mile east and one mile north you reach the place where you
started.
15. In a X's and 0's game (i.e. TIC TAC TOE) if you write a program for this
give a fast way to generate the moves by the computer. I mean this
should be the fastest way possible.
16.A version of the "There are three persons X Y Z, one of which always
lies"..
17. There are 3 ants at 3 corners of a triangle, they randomly start moving
towards another corner.. what is the probability that they don't collide.
18.If you are on a boat and you throw out a suitcase, Will the level of water
increase.
19. There are 4 men who want to cross a bridge. They all begin on the same
side. You have 17 minutes to get all of them across to the other side. It is
night. There is one flashlight. A maximum of two people can cross at
one time. Any party who crosses, either 1 or 2 people, must have the
flashlight with them. The flashlight must be walked back and forth, it
cannot be thrown, etc. Each man walks at a different speed. A pair must
walk together at the rate of the slower mans pace.
20. Man 1:1 minute to cross
21. Man 2: 2 minutes to cross
22. Man 3: 5 minutes to cross
23. Man 4: 10 minutes to cross
24. You have 5 jars of pills. Each pill weighs 10 gram, except for
contaminated pills contained in one jar, where each pill weighs 9 gm.
Given a scale, how could you tell which jar had the contaminated pills in
just one measurement?
25. One train leaves Los Angeles at 15 MPH heading for New York.
Another train leaves from New York at 20mph heading for Los Angeles
on the same track. If a bird, flying at 25mph, leaves from Los Angeles at
the same time as the train and flies back and forth between the two trains
until they collide, how far will the bird have traveled?
26. Imagine that you have 26 constants, labelled A through Z. Each constant
is assigned a value in the following way: A = 1; the rest of the values
equal their position in the alphabet (B corresponds to the second position
so it equals 2, C = 3, etc.) raised to the power of the preceeding constant
value. So, B = 2 ^ (A's value), or B = 2^1 = 2. C = 3^2 = 9. D = 4^9, etc.,
etc. Find the exact numerical value to the following equation:
(X - A) * (X - B) * (X - C) * ... * (X - Y) * (X - Z)
27. You have 12 balls. All of them are identical except one, which is either
heavier or lighter than the rest - it is either hollow while the rest are
solid, or solid while the rest are hollow. You have a simple two-armed
scale, and are permitted three weighings. Can you identify the odd ball,
and determine whether it is hollow or solid.
29. Given only putchar (no sprintf, itoa, etc.) write a routine putlong that
prints out an unsigned long in decimal.
32. What are the different ways to say, the value of x can be either a 0 or a 1.
33. I was given two lines of assembly code which found the absolute value
of a number stored in two's complement form. I had to recognize what
the code was doing.
42. Write a function that computes the nth number in the Fibonacci
sequence.
50. Write, efficient code for extracting unique elements from a sorted list of
array. e.g. (1, 1, 3, 3, 3, 5, 5, 5, 9, 9, 9, 9) -> (1, 3, 5, 9).
Microsoft question
78.Write a function and the node data structure to visit all of the nodes in a
binary tree.
79.You know what a queue is .... Implement a queue class with Java. What
is the cost of enqueue and dequeue? Can you improve this? What if the
queue is full (I was using an looping array)? What kind of mechanism
would you use to increase its size?
80.Give an algorithm that calculates the distance between two text strings
(only operations you can have are: delete, add, and change, one by one).
81.Given the definition of a sequence (5 4 7 6 is, but 1 2 4 5 is not), write an
algorithm to check if an arbitrary array is a sequence or not. Once I
figured out a solution, I was asked to do a space and time complexity
analysis.
82.Describe a situation where concurrent access would lead to
inconsistency in your application. How would you solve this problem?
83. You are given a list of n numbers from 1 to n-1, with one of the numbers
repeated. Devise a method to determine which number is repeated.
From CSRI
142. Given ships travel between points A and B, one every hour
leaving from both ends (simultaneously), how many ships are required
(minimum), if the journey takes 1hr 40 mts. How many ships does each
ship encounter in its journey, and at what times?
143. Write a SetPixel(x, y) function, given a pointer to the bitmap.
Each pixel is represented by 1 bit. There are 640 pixels per row. In each
byte, while the bits are numbered right to left, pixels are numbered left to
right. Avoid multiplications and divisions to improve performance.
144. How do you represent an n-ary tree? Write a program to print the
nodes of such a tree in breadth first order.
145. Write the 'tr' program of UNIX. Invoked as
tr -str1 -str2.
146. What does the term cast refer to? Why is it used?
147. In arithmetic expressions, to what data type will the C compiler
promote a character?
153. Specify the skeletons of two C loops with the test at the top.
156. What does a break statement do? Which control structures use it?
157. In a loop, what is the difference between a break and continue
statement?
164. State the syntax for the printf() and scanf() functions. State their
one crucial difference with respect to their parameters.
171. Assuming the variable address above, how would one refer to the
city portion of the record within a C expression?
178. What are the following and how do they differ: int, long, float and
double?
182. What is the difference between the & and && operators and the |
and || operators?
185. From the standpoint of logic, what is the difference between the
fragment:
186. if (next < max)
187. next++;
188. else
189. next = 0;
and the fragment:
next += (next < max)? (1):(-next);
195. Declare a pointer called fnc which points to a function that returns
an unsigned long.
199. Given the decimal number 27, how would one express it as a
hexadecimal number in C?
207. Write an efficient C code for 'tr' program. 'tr' has two command
line arguments. They both are strings of same length. tr reads an input
file, replaces each character in the first string with the corresponding
character in the second string. eg. 'tr abc xyz' replaces all 'a's by 'x's, 'b's
by 'y's and so on.
208. Write C code to implement strtok() 'c' library function.
209. Implement strstr(), strcpy(), strtok() etc
210. Reverse a string.
211. Given a linked list which is sorted, how will you insert in sorted
way.
212. Write a function that allocates memory for a two-dimensional
array of given size (parameter x & y)
213. Write source code for printHex(int i) in C/C++
214. Write a function that finds the last instance of a character in a
string.
233. What are the differences between a C++ struct and C++ class?
234. How many ways are there to initialize an int with a constant?
235. How does throwing and catching exceptions differ from using
setjmp and longjmp?
250. What is the difference between C and C++ ? Would you prefer to
use one over the other ?
251. What are the access privileges in C++ ? What is the default access
level ?
259. What is the difference between a shallow copy and a deep copy ?
260. What are the differences between new and malloc?
261. What is the difference between delete and delete[]?
262. What are the differences between a struct in C and in C++?
263. What are the advantages/disadvantages of using #define?
264. What are the advantages/disadvantages of using inline and const?
265. What is the difference between a pointer and a reference?
266. When would you use a pointer? A reference?
267. What does it mean to take the address of a reference?
268. What does it mean to declare a function or variable as static?
269. What is the order of initalization for data?
270. What is name mangling/name decoration?
271. What kind of problems does name mangling cause?
272. How do you work around them?
273. What is a class?
274. What are the differences between a struct and a class in C++?
275. What is the difference between public, private, and protected
access?
276. For class CFoo { }; what default methods will the compiler
generate for you>?
277. How can you force the compiler to not generate them?
278. What is the purpose of a constructor? Destructor?
279. What is a constructor initializer list?
280. When must you use a constructor initializer list?
281. What is a: Constructor? Destructor? Default constructor? Copy
constructor? Conversion constructor?
282. What does it mean to declare a... member function as virtual?
member function as static? member varible as static? destructor as static?
283. Can you explain the term "resource acqusition is initialization?"
284. What is a "pure virtual" member function?
285. What is the difference between public, private, and protected
inheritance?
286. What is virtual inheritance?
287. What is placement new?
288. What is the difference between operator new and the new
operator?
289. What is exception handling?
290. Explain what happens when an exception is thrown in C++.
291. What happens if an exception is not caught?
292. What happens if an exception is throws from an object's
constructor?
293. What happens if an exception is throws from an object's
destructor?
294. What are the costs and benefits of using exceptions?
295. When would you choose to return an error code rather than throw
an exception?
296. What is a template?
297. What is partial specialization or template specialization?
298. How can you force instantiation of a template?
299. What is an iterator?
300. What is an algorithm (in terms of the STL/C++ standard library)?
301. What is std::auto_ptr?
302. What is wrong with this statement? std::auto_ptr ptr(new
char[10]);
304. What output does the following code generate? Why? What
output does it generate if you make A::Foo() a pure virtual function?
305. What output does this program generate as shown? Why?
306. C++ ( what is virtual function ? what happens if an error occurs in
constructor or destructor. Discussion on error handling, templates,
unique features of C++. What is different in C++, ( compare with unix).
307. I was given a c++ code and was asked to find out the bug in that.
The bug was that he declared an object locally in a function and tried to
return the pointer to that object. Since the object is local to the function,
it no more exists after returning from the function. The pointer,
therefore, is invalid outside.
Design
314. Draw a class diagram (UML) for a system. (They described the
system in plain english).
315. Which do you prefer, inheritance or delegation? Why?
316. What is the difference between RMI and IIOP?
Java questions
317. http://www.javaprepare.com/quests/question.html
General questions
1. Introduction
The technical interview is perhaps the most intimidating and mysterious
event that job hunters experience in the quest for that "killer offer." The
rigor and format of the technical interview varies from one company to
the next, but there are some fundamental similarities. An interviewer
presents you with a problem to be solved. The interviewer may leave the
room and give you some time to work the solution out before returning.
Or the interviewer may wait patiently while you study the problem and
figure it out. The interviewer may even start quizzing you right away
about aspects of the problem and approaches to solving it. Some of these
problems can appear quite challenging, especially if you've never been
through a technical interview before. To make matters worse, simply
getting the answer to the problem may not be enough to land the job. On
the other hand, getting the correct answer may not even be necessary.
What is an interviewer looking for in candidates during the technical
interview? Interviewers recognize that this setting is, by its very nature,
stressful. Otherwise competent candidates may be completely stumped
by an interview problem only to discover an elegant, simple solution
later that night. Interviewers may be interested in seeing how you work
under stressful situations or how well you adapt. It is worth noting that
interviewers are more interested in seeing how you work than seeing
whether you can come up with the correct answer. In this article, I will
deal with both how you can better showcase your skills and experience,
and what kinds of problems you can expect to be asked.
These basic rules are often taught to programmers and are (or at any rate,
should be) drilled into your head in computer-science classes. For some
reason, however, they are easily forgotten during the technical interview.
Being one of the few candidates careful and experienced enough to
remember these important steps can make the difference between getting
an offer and getting the cold shoulder. Don't be afraid to ask for
clarifications of the problem or the requirements for the solution.
You should never assume that you have been given all the data necessary
to solve the problem to the satisfaction of the interviewer. This is
especially likely to be the case when interviewing with IT consulting
companies. In this environment, the client may need some prodding in
order to provide a complete specification. So, the reasoning goes, ideal
candidates will be willing to talk to the client to figure out the expected
inputs, the desired outputs, the data ranges and data types, and the
special cases. The ideal candidate will ask these questions rather than
spend all the allotted time coming up with a solution that doesn't meet
the client's needs. The first thing to do, then, is to make sure that you and
the interviewer agree on what the problem is and what an acceptable
solution would be. Make all of your assumptions explicit and up-front,
so the interviewer can correct you if you are mistaken.
Initialize all variables, give variables descriptive names, and always use
comments.
In addition to these basic rules for the technical interview, there are some
other things worth pointing out. Interviewers don't always have the
chance to examine your résumé in advance. This means that the
interviewer may not be aware of your past work experience. Don't
hesitate to point out experiences working in teams (whether as a part of a
past job, a class programming project, or a hobby), working on large
projects (paying attention to time spent on design, implementation, and
testing), dealing with customers to define requirements, and managing
people and projects. Interviewers are interested in hearing about
successes as well as failures. When these past experiences weren't
successful, you should point out the lessons learned or wisdom gained as
a result of these failures. Interviewers want to see that candidates who
have had negative experiences are not going to repeat their mistakes.
9. Conclusion
Logic questions
The cut (plane) should pass through the center of the two rectangles: the
outer cake and the inner hollow area. Since any plane passing through
the center of the cuboid will divide the volume in two halves, both the
cake and hollow area are divided into two equal halves.
14.How many points are there on the globe where by walking one mile
south, one mile east and one mile north you reach the place where
you started.
The answer is "many points". The set of such points is given as {North
pole, special circle}.
From north pole, walking one mile south followed by one mile east still
keeps you one mile south of North pole.
The special circle consists of a set of points defined as follows. Let's say
you were to locate a spot near the South Pole where the circular distance
"around" the Earth's North-South axis is 1 mile. The path of such a
journey would create a circle with a radius of approximately 840.8 feet
(because C=2.r.pi). Call this point X. Now consider another point Y one
mile north of X. The special circle is the circular path around North-
South axis going through Y. If you begin you journey from any point
(say Y1) on this special circle, and travel one mile south, you get to a
point (say X1) on the circle of point X. Now one mile east will bring you
back to X1, because circumference of circle of X is 1 mile. Then one
mile North brings you back to Y1. (Answer supplied by Kristie Boman)
15.In a X's and 0's game (i.e. TIC TAC TOE) if you write a program
for this give a fast way to generate the moves by the computer. I
mean this should be the fastest way possible.
The answer is that you need to store all possible configurations of the
board and the move that is associated with that. Then it boils down to
just accessing the right element and getting the corresponding move for
it. Do some analysis and do some more optimization in storage since
otherwise it becomes infeasible to get the required storage in a DOS
machine.
18.If you are on a boat and you throw out a suitcase, Will the level of
water increase.
19.There are 4 men who want to cross a bridge. They all begin on the
same side. You have 17 minutes to get all of them across to the other
side. It is night. There is one flashlight. A maximum of two people
can cross at one time. Any party who crosses, either 1 or 2 people,
must have the flashlight with them. The flashlight must be walked
back and forth, it cannot be thrown, etc. Each man walks at a
different speed. A pair must walk together at the rate of the slower
mans pace.
20. Man 1:1 minute to cross
21. Man 2: 2 minutes to cross
22. Man 3: 5 minutes to cross
23. Man 4: 10 minutes to cross
1 and 2 cross together. 1 comes back. then 3 and 4 cross. 2 comes back.
then 1 and 2 cross. Total time is 2+1+10+2+2 = 17.
24.You have 5 jars of pills. Each pill weighs 10 gram, except for
contaminated pills contained in one jar, where each pill weighs 9 gm.
Given a scale, how could you tell which jar had the contaminated
pills in just one measurement?
Take one pill from first, two from second, three from third and so on.
Total pills are n(n+1)/2 and should weigh 10n(n+1)/2. If it weighs x gm
less than that then the x'th jar is contaminated, since we took x pills from
that jar which weighed 1 gm less.
25.One train leaves Los Angeles at 15 MPH heading for New York.
Another train leaves from New York at 20mph heading for Los
Angeles on the same track. If a bird, flying at 25mph, leaves from
Los Angeles at the same time as the train and flies back and forth
between the two trains until they collide, how far will the bird have
traveled?
27.You have 12 balls. All of them are identical except one, which is
either heavier or lighter than the rest - it is either hollow while the
rest are solid, or solid while the rest are hollow. You have a simple
two-armed scale, and are permitted three weighings. Can you
identify the odd ball, and determine whether it is hollow or solid.
Let the balls be numbered 1 to 12. Firstly, put 1-4 on one side and 5-8 on
other side. If both are equal then one of 9-12 is odd. Then second try,
weigh 9-10 vs 1-2, if equal, one of 11-12 is bad, else 9-10 is bad. Testing
which one is bad can be done by (third try) weighing 11 or 9,
respectively, with good ball 1. It also gives whether the odd ball is heavy
or light.
The basic idea is to draw one quadrant and replicate it to other four
quadrants. Assuming the center is given as (x,y) and radius as r units,
then start X from (x+r) down to (x) and start Y from y up to (y+r). In the
iteration, keep comparing is the equation is satisfied or not within an
error of one unit for x and y. If not then re-adjust X and Y.
29.Given only putchar (no sprintf, itoa, etc.) write a routine putlong
that prints out an unsigned long in decimal.
30. void putlong(unsigned long x)
31. {
32. // we know that 32 bits can have 10 digits. 2^32 = 4294967296
33. for (unsigned long y = 1000000000; y > 0; y /= 10) {
34. putchar( (x / y) + '0');
35. x = x % y;
36. }
37. }
40.What are the different ways to say, the value of x can be either a 0 or
a 1.
Apparently the if then else solution has a jump when written out in
assembly.
if (x == 0)
y=0
else
y =x
41.I was given two lines of assembly code which found the absolute
value of a number stored in two's complement form. I had to
recognize what the code was doing.
Pretty simple if you know some assembly and some fundaes on number
representation.
44.A real life problem - A square picture is cut into 16 sqaures and they
are shuffled. Write a program to rearrange the 16 squares to get the
original big square.
52.Switch the integer values stored in two registers without using any
additional memory.
To swap the values, you can carry out the following instructions:
Reg_1 = Reg_1 + Reg_2;
Reg_2 = Reg_1 - Reg_2;
Reg_1 = Reg_1 - Reg_2;
53.Given two strings S1 and S2. Delete from S2 all those characters
which occur in S1 also and finally create a clean S2 with the relevant
characters deleted.
Microsoft question
74.Given only putchar (no sprintf, itoa, etc.) write a routine putlong
that prints out an unsigned long in decimal. [ I gave the obvious
solution of taking % 10 and / 10, which gives us the decimal value in
reverse order. This requires an array since we need to print it out in
the correct order. The interviewer wasn't too pleased and asked me
to give a solution which didn't need the array ].
77.How many points are there on the globe where by walking one mile
south, one mile east and one mile north you reach the place where
you started.
78.Give a very good method to count the number of ones in a 32 bit
number. (caution: looping through testing each bit is not a solution).
79.What are the different ways to say, the value of x can be either a 0 or
a 1. Apparently the if then else solution has a jump when written out
in assembly. if (x == 0) y=0 else y =x
a is a power of 2.
81.How can you print singly linked list in reverse order? (it's a huge list
and you cant use recursion)
82.How can you find out if there is a loop in a very long list?
83.A character set has 1 and 2 byte characters. One byte characters
have 0 as the first bit. You just keep accumulating the characters in
a buffer. Suppose at some point the user types a backspace, how can
you remove the character efficiently. ( Note: You cant store the last
character typed because the user can type in arbitrarily many
backspaces)
84.How would you reverse the bits of a number with log N arithmetic
operations, where N is the number of bits in the integer (eg 32,64..)
85.Whats the simples way to check if the sum of two unsigned integers
has resulted in an overflow.
89.Find the largest 10**n less than given number, then div etc.
90.Infinite.
92.reverse the pointers till you reach the end and print-and-reverse as
you return.
93.Have two 'threads' one at twice the speed of the other traversing the
list and see if at anytime they meet.
94.Scan the bytes backward till you reach one with the first bit set to 0.
Now this is either a one byte character or the second byte of a two
byte one. Either way it marks a Character boundary. Start from
there an scan forward to find what the last character is.
95.Flip adjacent bits, then flip adjacent 2 bit sets, then 4-bits and so on.
Each of this swap can be done in constant time using appropriate
masks and shifts.
97.Write a function and the node data structure to visit all of the nodes
in a binary tree.
98.You know what a queue is .... Implement a queue class with Java.
What is the cost of enqueue and dequeue? Can you improve this?
What if the queue is full (I was using an looping array)? What kind
of mechanism would you use to increase its size?
102. You are given a list of n numbers from 1 to n-1, with one of
the numbers repeated. Devise a method to determine which number
is repeated.
The sum of the numbers 1 to n-1 is (n)(n-1)/2. Add the numbers on the
list, and subtract (n)(n-1)/2. The result is the number that has been
repeated.
You are presented with a linked list, which may have a "loop" in it. That
is, an element of the linked list may incorrectly point to a previously
encountered element, which can cause an infinite loop when traversing
the list. Devise an algorithm to detect whether a loop exists in a linked
list. How does your answer change if you cannot change the structure of
the list elements?
One possible answer is to add a flag to each element of the list. You
could then traverse the list, starting at the head and tagging each element
as you encounter it. If you ever encountered an element that was already
tagged, you would know that you had already visited it and that there
existed a loop in the linked list. What if you are not allowed to alter the
structure of the elements of the linked list? The following algorithm will
find the loop:
The important realization for this problem is that the hour hand is always
moving. In other words, at 1:30, the hour hand is halfway between 1 and
2. Once you remember that, this problem is fairly straightforward.
Assuming you don't care whether the function returns the shorter or
larger angle, Example 4 shows a solution to this problem.
For the sake of this problem, assume that the string has been stripped of
punctuation (including spaces), and has been converted to a single case.
The most efficient way to detect whether a string is a palindrome is to
create two pointers. Set one at the beginning of the string, and one at the
end. Compare the values at those locations. If the values don't match, the
string isn't a palindrome. Otherwise, move each pointer inward and
repeat the comparison. Stop when the pointers are pointing to the same
position in the string (if its length is an odd-number) or when the
pointers have "crossed" (if the string's length is an even-number).
Example 5 shows the correct solution.
Assume that the file format is one byte for every pixel in the file, and
that the approximation will produce one ASCII character of output for
each pixel. This problem is easier to solve than it sounds. This is one of
the tricks used in technical interview questions. Problems may be
obscured or made to sound difficult. Don't be fooled! Take the time to
think about the core of the problem. In this case, all you want is an
algorithm for reading the values in a file and outputting characters based
upon those values.
You then have to assign an ASCII character to each of those four ranges
of numbers. For example, you could use "_", "~", "+", and "#". Then, the
algorithm is as follows:
1. Open the file.
2. For every byte in the file:
a. Read in one byte.
b. If the value is in the range 0..63, we'll print '_'.
c. If the value is in the range 64..127, we'll print '~'.
d. If the value is in the range 128..191, we'll print '+'.
e. If the value is in the range 192..255, we'll print '#'.
3. Close the file.
112. Assuming that locks are the only reason due to which
deadlocks can occur in a system. What would be a foolproof method
of avoiding deadlocks in the system.
119. Give a good data structure for having n queues ( n not fixed)
in a finite memory segment. You can have some data-structure
separate for each queue. Try to use at least 90% of the memory
space.
121. Given a list of numbers ( fixed list) Now given any other list,
how can you efficiently find out if there is any element in the second
list that is an element of the first list (fixed list).
given a linked list with the following property node2 is left child of
node1, if node2 < node1 else, it is the right child.
O P
|
|
O A
|
|
O B
|
|
O C
How do you convert the above linked list to the form without disturbing
the property. Write C code for that.
OP||OB///O?O?
125. A square picture is cut into 16 squares and they are shuffled.
Write a program to rearrange the 16 squares to get the original big
square.
127. How would you implement a hash table ? How do you deal
with collisions?
141. Write a routine that prints out a 2-D array in spiral order.
145. How would you print out the data in a binary tree, level by
level, starting at the top?
146. Given an array of characters which form a sentence of words,
give an efficient algorithm to reverse the order of the words in it.
148. Given a list of numbers ( fixed list) Now given any other list,
how can you efficiently find out if there is any element in the second
list that is an element of the first list (fixed list).
From CSRI
161. Given ships travel between points A and B, one every hour
leaving from both ends (simultaneously), how many ships are
required (minimum), if the journey takes 1hr 40 mts. How many
ships does each ship encounter in its journey, and at what times?
165. What does the term cast refer to? Why is it used?
If the test is at the bottom, the body of the loop will always be executed
at least once. When the test is at the top, the body of the loop may never
be executed.
177. Specify the skeletons of two C loops with the test at the top.
178. next = 0; /* setup */
179.
180. while ( next < max) { /* test */
181. printf("Hello "); /* body */
182. next++; /* update */
183. }
184.
185. and
186.
187. for ( next = 0; next < max; next++) /* setup,test */
188. /* and update */
189. printf("Hello"); /* body */
The break terminates the loop. The continue branches immediately to the
test portion of the loop.
A definition tells the compiler to set aside storage for the variable. A
declaration makes the variable known to parts of the program that may
wish to use it. A variable might be defined and declared in the same
statement.
extern - Tells the compiler that the variable is defined in another module.
volatile - Tells the compiler that other programs will be modifying this
variable in addition to the program being compiled. For example, an I/O
device might need write directly into a program or data space.
Meanwhile, the program itself may never directly access the memory
area in question. In such a case, we would not want the compiler to
optimize-out this data area that never seems to be used by the program,
yet must exist for the program to function correctly in a larger context.
206. State the syntax for the printf() and scanf() functions. State
their one crucial difference with respect to their parameters.
Where fmtStr tells printf() how to format the variable list that follows.
var1 through varN may be variables of any base type.
scanf( fmtStr, &var1, &var2, &varN);
This routine is the input compliment to printf().
addrPtr address;
220. Assuming the variable address above, how would one refer to
the city portion of the record within a C expression?
address->city
They both specify a file for inclusion into the current source file. The
difference is where the file stdio.h is expected to be. In the case of the
brackets, the compiler will look in all the default locations. In the case of
the quotes, the compiler will only look in the current directory.
227. What are the following and how do they differ: int, long, float
and double?
(The parenthesis around "x * x" are extremely important because the
macro may be expanded into a place where any embedded spaces could
cause the compiler to misinterpret the expression. The consequences
could range from a pesky syntax error to wrong answers when the
program is run.). Moral: The preprocessor does not know C.
231. What is the difference between the & and && operators and
the | and || operators?
& and | are bitwise AND and OR operators respectively. They are
usually used to manipulate the contents of a variable on the bit level. &&
and || are logical AND and OR operators respectively. They are usually
used in conditionals.
Do the following until either the end of standard input or the variable c
takes on the value of a tab, space, or backspace character: Store the
character that succeeds the character stored in c into the current location
pointed by buff. Then increment buff to point to the next location in
memory. Meanwhile, d is assigned the same value as c and it is the value
of d that is used in the comparison to EOF.
Yes.
The void data type is used when no other data type is appropriate. A void
pointer is a pointer that may point to any kind of object at all. It is used
when a pointer must be specified but its type is unknown.
248. Given the decimal number 27, how would one express it as a
hexadecimal number in C?
0x1B
void *ptr;
assign the pointer to a long number and the number with 11...1100 add 4
to the number
256. Write an efficient C code for 'tr' program. 'tr' has two
command line arguments. They both are strings of same length. tr
reads an input file, replaces each character in the first string with
the corresponding character in the second string. eg. 'tr abc xyz'
replaces all 'a's by 'x's, 'b's by 'y's and so on.
257. have an array of length 26.
258. put 'x' in array element corr to 'a'
259. put 'y' in array element corr to 'b'
260. put 'z' in array element corr to 'c'
261. put 'd' in array element corr to 'd'
262. put 'e' in array element corr to 'e'
263. and so on.
the code
while (!eof)
{
c = getc();
putc(array[c - 'a']);
}
267. Given a linked list which is sorted, how will you insert in
sorted way.
Inheritance is property such that a parent (or super) class passes the
characteristics of itself to children (or sub) classes that are derived from
it. The sub-class has the option of modifying these characteristics in
order to make a different but fundamentally related class from the super-
class.
It is the process of, and ability to redefine the way an object responds to
a C++ operator symbol. This would be done in the object's class
definition.
You should know about mangled function names and type-safe linkages.
Then you should explain how the extern "C" linkage specification
statement turns that feature off during compilation so that the linker
properly links function calls to C functions. Another acceptable answer
is "I don't know. We never had to do that." Merely describing what a
linker does would indicate to me that you do not understand the issue
that underlies the question.
7. What are the differences between a C++ struct and C++ class?
The default member and base class access specifiers are different.
It's okay to discuss the notational differences between the two idioms.
Explain the syntax of try blocks, catch exception handlers, and throw
expressions. Then specifically address what happens in a throw that does
not happen in a longjmp. Your answer should reflect an understanding of
the behavior described in the answer just given.
One valid reason for not knowing about exception handling is that your
experience is exclusively with older C++ compilers that do not
implement exception handling. I would prefer that you have at least
heard of exception handling, though.
It is not unusual for C and C++ programmers to be unfamiliar with
setjmp/ longjmp. Those constructs are not particularly intuitive. A C
programmer who has written recursive descent parsing algorithms will
certainly be familiar with setjmp/ longjmp. Others might not, and that's
acceptable. In that case, you won't be able to discuss how
setjmp/longjmp differs from C++ exception handling, but let the
interview turn into a discussion of C++ exception handling in general.
That conversation will reveal to the interviewer a lot about your overall
understanding of C++.
A reader pointed out that a class can ensure that its objects are
instantiated on the heap by making its destructor private. This idiom
necessitates a kludgy DeleteMe kind of function because the instantiator
cannot call the delete operator for objects of the class. The DeleteMe
function would then use "delete this."
I got a lot of mail about this issue. Many programmers believe that delete
this is a valid construct. In my experience, classes that use delete this
when objects are instantiated by users usually spawn bugs related to the
idiom, most often when a program dereferences a pointer to an object
that has already deleted itself.
11. What is a default constructor?
A constructor that has no arguments or one where all the arguments have
default argument values.
If you don't code a default constructor, the compiler provides one if there
are no other constructors. If you are going to instantiate an array of
objects of the class, the class must have a default constructor.
The compiler uses this idiom as one way to infer conversion rules for a
class. A constructor with more than one argument and with default
argument values can be interpreted by the compiler as a conversion
constructor when the compiler is looking for an object of the type and
sees an object of the type of the constructor's first argument.
First, you must know that a copy constructor is one that has only one
argument, which is a reference to the same type as the constructor. The
compiler invokes a copy constructor wherever it needs to make a copy of
the object, for example to pass an argument by value. If you do not
provide a copy constructor, the compiler creates a member-by-member
copy constructor for you.
This discussion is a good place to get into why classes need copy
constructors and overloaded assignment operators. By discussing the
requirements with respect to data member pointers that point to
dynamically allocated resources, you demonstrate a good grasp of the
problem.
There are three acceptable answers: "Never," "Rarely," and "When the
problem domain cannot be accurately modeled any other way."
There are some famous C++ pundits and luminaries who disagree with
that third answer, so be careful.
Let's digress to consider this issue lest your interview turn into a
religious debate. Consider an Asset class, Building class, Vehicle class,
and CompanyCar class. All company cars are vehicles. Some company
cars are assets because the organizations own them. Others might be
leased. Not all assets are vehicles. Money accounts are assets. Real-
estate holdings are assets. Some real-estate holdings are buildings. Not
all buildings are assets. Ad infinitum. When you diagram these
relationships, it becomes apparent that multiple inheritance is an intuitive
way to model this common problem domain. You should understand,
however, that multiple inheritance, like a chainsaw, is a useful tool that
has its perils, needs respect, and is best avoided except when nothing
else will do. Stress this understanding because your interviewer might
share the common bias against multiple inheritance that many object-
oriented designers hold.
The simple answer is that a virtual destructor is one that is declared with
the virtual attribute.
16. Explain the ISA and HASA class relationships. How would
you implement each in a class design?
A specialized class "is a" specialization of another class and, therefore,
has the ISA relationship with the other class. An Employee ISA Person.
This relationship is best implemented with inheritance. Employee is
derived from Person. A class may have an instance of another class. For
example, an Employee "has a" Salary, therefore the Employee class has
the HASA relationship with the Salary class. This relationship is best
implemented by embedding an object of the Salary class in the
Employee class.
There are other relationships. The USESA relationship is when one class
uses the services of another. The Employee class uses an object (cout) of
the ostream class to display the employee's name onscreen, for example.
But if you get ISA and HASA right, you usually don't need to go any
further.
Prior to templates, you had to use inheritance; your design might include
a generic List container class and an application-specific Employee
class. To put employees in a list, a ListedEmployee class is multiply
derived (contrived) from the Employee and List classes. These solutions
were unwieldy and error-prone. Templates solved that problem.
25. What are the access privileges in C++ ? What is the default
access level ?
The access privileges in C++ are private, public and protected. The
default access level assigned to members of a class is private. Private
members of a class are accessible only within the class and by friends of
the class. Protected members are accessible by the class itself and it's
sub-classes. Public members of a class can be accessed by anyone.
Polymorphism refers to the ability to have more than one method with
the same signature in an inheritance hierarchy. The correct method is
invoked at run-time based on the context (object) on which the method is
invoked. Polymorphism allows for a generic use of method names while
providing specialized implementations for them.
48. What are the differences between a struct and a class in C++?
50. For class CFoo { }; what default methods will the compiler
generate for you>?
51. How can you force the compiler to not generate them?
52. What is the purpose of a constructor? Destructor?
62. What is the difference between operator new and the new
operator?
69. When would you choose to return an error code rather than
throw an exception?
70. What is a template?
Note: I've only asked this question once; and yes, he understood that I
was asking him how cfront was put together.
78. What output does the following code generate? Why? What
output does it generate if you make A::Foo() a pure virtual
function?
79. #include
80. class A {
81. public:
82. A() {
83. this->Foo();
84. }
85. virtual void Foo() {
86. cout << "A::Foo()" << endl;
87. }
88. };
89. class B : public A {
90. public:
91. B() {
92. this->Foo();
93. }
94. virtual void Foo() {
95. cout << "A::Foo()" << endl;
96. }
97. };
98. int main(int, char**)
99. {
100. B objectB;
101. }
102.
103. p {return 0;
104. }
143. I was given a c++ code and was asked to find out the bug in
that. The bug was that he declared an object locally in a function
and tried to return the pointer to that object. Since the object is local
to the function, it no more exists after returning from the function.
The pointer, therefore, is invalid outside.
One that can be modified by the class even when the object of the class
or the member function doing the modification is const.
The ability to determine at run time the type of an object by using the
typeid operator or the dynamic_cast operator.
This solution assumes that two library vendors don't use the same
namespace, of course.
Yes. The ANSI committee added the bool intrinsic type and its true and
false value keywords and the wchar_t data type to support character sets
wider than eight bits.
Other apparent new types (string, complex, and so forth) are
implemented as classes in the Standard C++ Library rather than as
intrinsic types.
Design
Java questions
153. http://www.javaprepare.com/quests/question.html
In UNIX, are the files allocated contiguous blocks of data a) no, they
might be fragmented how is the fragmented data kept track of a) describe
the direct blocks and indirect blocks in UNIX file system
185. draw the graph with performace on one axis and 'n' on
another, where 'n' in the 'n' in n-way disk interleaving. (a tricky
question, should be answered carefully)
187. What sort of technique you would use to update a set of files
over a network, where a server contains the master copy.
General questions
190. What was the last book you read (does not have to be job
related!)
191. If you could recommend one resource (book, web site, etc.) to
a new software developer just out of school, what would it be?
192. What was the most interesting project that you worked on?
193. What was the most challenging project that you worked on?
194. If you could have any job in the world, what would it be?
199. A chemist calls you up and says his Netscape isn't working.
What's wrong and how do you find out?
212. What was the hardest program error for you to find and
correct?
213. What did you find hardest when working with others in a
project?
214. What is a tool or system that you learned on your own? i.e.
not in a class room?
218. What to test for given that there isn't enough time to test
everything you want to.
219. Why do u think u are smart.
221. Do you want to know any thing about the company.( Try to
ask some relevant and interesting question).
Interview Questions
If you would like to contribute to the list or send feedback, please email Kundan Singh.