Thursday 24 November 2011

Sample technical Questions


 C- Questions

1. What does static variable mean?
2. What is a pointer?
3. What is a structure?
4. What are the differences between structures and arrays?
5. In header files whether functions are declared or defined?
6. What are the differences between malloc() and calloc()?
7. What are macros? what are its advantages and disadvantages?
8. Difference between pass by reference and pass by value?
9. What is static identifier?
10. Where are the auto variables stored?
11. Where does global, static, local, register variables, free memory and C Program instructions get stored?
12. Difference between arrays and linked list?
13. What are enumerations?
14. Describe about storage allocation and scope of global, extern, static, local and register variables?
15. What are register variables? What are the advantage of using register variables?
16. What is the use of typedef?
17. Can we specify variable field width in a scanf() format string? If possible how?
18. Out of fgets() and gets() which function is safe to use and why?
19. Difference between strdup and strcpy?
20. What is recursion?
21. Differentiate between a for loop and a while loop? What are it uses?
22. What are the different storage classes in C?
23. Write down the equivalent pointer _expression for referring the same element a[i][j][k][l]?
24. What is difference between Structure and Unions?
25. What the advantages of using Unions?
26. What are the advantages of using pointers in a program?
27. What is the difference between Strings and Arrays?
28. In a header file whether functions are declared or defined?
29. What is a far pointer? where we use it?
30. How will you declare an array of three function pointers where each function receives two ints and returns a float?
31. what is a NULL Pointer? Whether it is same as an uninitialized pointer?
32. What is a NULL Macro? What is the difference between a NULL Pointer and a NULL Macro?
33. What does the error 'Null Pointer Assignment' mean and what causes this error?
34. What is near, far and huge pointers? How many bytes are occupied by them?
35. How would you obtain segment and offset addresses from a far address of a memory location?
36. Are the expressions arr and &arr same for an array of integers?
37. Does mentioning the array name gives the base address in all the contexts?
38. Explain one method to process an entire string as one unit?
39. What is the similarity between a Structure, Union and enumeration?
40. Can a Structure contain a Pointer to itself?
41. How can we check whether the contents of two structure variables are same or not?
42. How are Structure passing and returning implemented by the complier?
43. How can we read/write Structures from/to data files?
44. What is the difference between an enumeration and a set of pre-processor # defines?
45. what do the 'c' and 'v' in argc and argv stand for?
46. Are the variables argc and argv are local to main?
47. What is the maximum combined length of command line arguments including the space between adjacent arguments?
48. If we want that any wildcard characters in the command line arguments should be appropriately expanded, are we required to make any special provision? If yes, which?
49. Does there exist any way to make the command line arguments available to other functions without passing them as arguments to the function?
50. What are bit fields? What is the use of bit fields in a Structure declaration?
51. To which numbering system can the binary number 1101100100111100 be easily converted to?
52. Which bit wise operator is suitable for checking whether a particular bit is on or off?
53. Which bit wise operator is suitable for turning off a particular bit in a number?
54. Which bit wise operator is suitable for putting on a particular bit in a number?
55. Which bit wise operator is suitable for checking whether a particular bit is on or off?
56. which one is equivalent to multiplying by 2:Left shifting a number by 1 or Left shifting an unsigned int or char by 1?
57. Write a program to compare two strings without using the strcmp() function.
58. Write a program to concatenate two strings.
59. Write a program to interchange 2 variables without using the third one.
60. Write programs for String Reversal & Palindrome check
61. Write a program to find the Factorial of a number
62. Write a program to generate the Fibinocci Series
63. Write a program which employs Recursion
64. Write a program which uses Command Line Arguments
65. Write a program which uses functions like strcmp(), strcpy()? etc
66. What are the advantages of using typedef in a program?
67. How would you dynamically allocate a one-dimensional and two-dimensional array of integers?
68. How can you increase the size of a dynamically allocated array?
69. How can you increase the size of a statically allocated array?
70. When reallocating memory if any other pointers point into the same piece of memory do you have to readjust these other pointers or do they get readjusted automatically?
71. Which function should be used to free the memory allocated by calloc()?
72. How much maximum can you allocate in a single call to malloc()?
73. Can you dynamically allocate arrays in expanded memory?
74. What is object file? How can you access object file?
75. Which header file should you include if you are to develop a function which can accept variable number of arguments?
76. Can you write a function similar to printf()?
77. How can a called function determine the number of arguments that have been passed to it?
78. Can there be at least some solution to determine the number of arguments passed to a variable argument list function?
79. How do you declare the following:
* An array of three pointers to chars
* An array of three char pointers
* A pointer to array of three chars
* A pointer to function which receives an int pointer and returns a float pointer
* A pointer to a function which receives nothing and returns nothing
80. What do the functions atoi(), itoa() and gcvt() do?
81. Does there exist any other function which can be used to convert an integer or a float to a string?
82. How would you use qsort() function to sort an array of structures?
83. How would you use qsort() function to sort the name stored in an array of pointers to string?
84. How would you use bsearch() function to search a name stored in array of pointers to string?
85. How would you use the functions sin(), pow(), sqrt()?
86. How would you use the functions memcpy(), memset(), memmove()?
87. How would you use the functions fseek(), freed(), fwrite() and ftell()?
88. How would you obtain the current time and difference between two times?
89. How would you use the functions randomize() and random()?
90. How would you implement a substr() function that extracts a sub string from a given string?
91. What is the difference between the functions rand(), random(), srand() and randomize()?
92. What is the difference between the functions memmove() and memcpy()?
93. How do you print a string on the printer?
94. Can you use the function fprintf() to display the output on the screen?

C++ Questions
 
1. What is a class?
2. What is an object?
3. What is the difference between an object and a class?
4. What is the difference between class and structure?
5. What is public, protected, private?
6. What are virtual functions?
7. What is friend function?
8. What is a scope resolution operator?
9. What do you mean by inheritance?
10. What is abstraction?
11. What is polymorphism? Explain with an example.
12. What is encapsulation?
13. What do you mean by binding of data and functions?
14. What is function overloading and operator overloading?
15. What is virtual class and friend class?
16. What do you mean by inline function?
17. What do you mean by public, private, protected and friendly?
18. When is an object created and what is its lifetime?
19. What do you mean by multiple inheritance and multilevel inheritance? Differentiate between them.
20. Difference between realloc() and free?
21. What is a template?
22. What are the main differences between procedure oriented languages and object oriented languages?
23. What is R T T I ?
24. What are generic functions and generic classes?
25. What is namespace?
26. What is the difference between pass by reference and pass by value?
27. Why do we use virtual functions?
28. What do you mean by pure virtual functions?
29. What are virtual classes?
30. Does c++ support multilevel and multiple inheritance?
31. What are the advantages of inheritance?
32. When is a memory allocated to a class?
33. What is the difference between declaration and definition?
34. What is virtual constructors/destructors?
35. In c++ there is only virtual destructors, no constructors. Why?
36. What is late bound function call and early bound function call? Differentiate.
37. How is exception handling carried out in c++?
38. When will a constructor executed?
39. What is Dynamic Polymorphism?
40. Write a macro for swapping integers.

DATA STRUCTURE QUESTIONS


1. What is a data structure?
2. What does abstract data type means?
3. Evaluate the following prefix _expression " ++ 26 + - 1324" (Similar types can be asked)
4. Convert the following infix _expression to post fix notation ((a+2)*(b+4)) -1 (Similar types can be asked)
5. How is it possible to insert different type of elements in stack?
6. Stack can be described as a pointer. Explain.
7. Write a Binary Search program
8. Write programs for Bubble Sort, Quick sort
9. Explain about the types of linked lists
10. How would you sort a linked list?
11. Write the programs for Linked List (Insertion and Deletion) operations
12. What data structure would you mostly likely see in a non recursive implementation of a recursive algorithm?
13. What do you mean by Base case, Recursive case, Binding Time, Run-Time Stack and Tail Recursion?
14. Explain quick sort and merge sort algorithms and derive the time-constraint relation for these.
15. Explain binary searching, Fibinocci search.
16. What is the maximum total number of nodes in a tree that has N levels? Note that the root is level (zero)
17. How many different binary trees and binary search trees can be made from three nodes that contain the key values 1, 2 & 3?
18. A list is ordered from smaller to largest when a sort is called. Which sort would take the longest time to execute?
19. A list is ordered from smaller to largest when a sort is called. Which sort would take the shortest time to execute?
20. When will you sort an array of pointers to list elements, rather than sorting the elements themselves?
21. The element being searched for is not found in an array of 100 elements. What is the average number of comparisons needed in a sequential search to determine that the element is not there, if the elements are completely unordered?
22. What is the average number of comparisons needed in a sequential search to determine the position of an element in an array of 100 elements, if the elements are ordered from largest to smallest?
23. Which sort show the best average behavior?
24. What is the average number of comparisons in a sequential search?
25. Which data structure is needed to convert infix notations to post fix notations?
26. What do you mean by:
* Syntax Error
* Logical Error
* Runtime Error
How can you correct these errors?
27. In which data structure, elements can be added or removed at either end, but not in the middle?
28. How will inorder, preorder and postorder traversals print the elements of a tree?
29. Parenthesis are never needed in prefix or postfix expressions. Why?
30. Which one is faster? A binary search of an orderd set of elements in an array or a sequential search of the elements.


JAVA QUESTIONS

1. What is the difference between an Abstract class and Interface?
2. What is user defined exception?
3. What do you know about the garbage collector?
4. What is the difference between java and c++?
5. In an htm form I have a button which makes us to open another page in 15 seconds. How will you do that?
6. What is the difference between process and threads?
7. What is update method called?
8. Have you ever used HashTable and Directory?
9. What are statements in Java?
10. What is a JAR file?
11. What is JNI?
12. What is the base class for all swing components?
13. What is JFC?
14. What is the difference between AWT and Swing?
15. Considering notepad/IE or any other thing as process, What will happen if you start notepad or IE 3 times ? Where three processes are started or three threads are started?
16. How does thread synchronization occur in a monitor?
17. Is there any tag in htm to upload and download files?
18. Why do you canvas?
19. How can you know about drivers and database information ?
20. What is serialization?
21. Can you load the server object dynamically? If so what are the 3 major steps involved in it?
22. What is the layout for toolbar?
23. What is the difference between Grid and Gridbaglayout?
24. How will you add panel to a frame?
25. Where are the card layouts used?
26. What is the corresponding layout for card in swing?
27. What is light weight component?
28. Can you run the product development on all operating systems?
29. What are the benefits if Swing over AWT?
30. How can two threads be made to communicate with each other?
31. What are the files generated after using IDL to java compiler?
32. What is the protocol used by server and client?
33. What is the functionability stubs and skeletons?
34. What is the mapping mechanism used by java to identify IDL language?
35. What is serializable interface?
36. What is the use of interface?
37. Why is java not fully objective oriented?
38. Why does java not support multiple inheritance?
39. What is the root class for all java classes?
40. What is polymorphism?
41. Suppose if we have a variable 'I' in run method, if I can create one or more thread each thread will occupy a separate copy or same variable will be shared?
42. What are virtual functions?
43. Write down how will you create a Binary tree?
44. What are the traverses in binary tree?
45. Write a program for recursive traverse?
46. What are session variable in servlets?
47. What is client server computing?
48. What is constructor and virtual function? Can we call a virtual function in a constructor?
49. Why do we use oops concepts? What is its advantage?
50. What is middleware? What is the functionality of web server?
51. Why is java not 100% pure oops?
52. When will you use an interface and abstract class?
53. What is the exact difference in between Unicast and Multicast object? Where will it be used?
54. What is the main functionality of the remote reference layer?
55. How do you download stubs from Remote place?
56. I want to store more than 10 objects in a remote server? Which methodology will follow?
57. What is the main functionality of Prepared Statement?
58. What is meant by Static query and Dynamic query?
59. What are Normalization Rules? Define Normalization?
60. What is meant by Servelet? What are the parameters of service method?
61. What is meant by Session? Explain something about HTTP Session Class?
62. In a container there are 5 components. I want to display all the component names, how will you do that?
63. Why there are some null interface in JAVA? What does it mean? Give some null interface in JAVA?
64. Tell some latest versions in JAVA related areas?
65. What is meant by class loader? How many types are there? When will we use them?
66. What is meant by flickering?
67. What is meant by distributed application? Why are we using that in our application?
68. What is the functionality of the stub?
69. Explain about version control?
70. Explain 2-tier and 3-tier architecture?
71. What is the role of Web Server?
72. How can we do validation of the fields in a project?
73. What is meant by cookies? Explain the main features?
74. Why java is considered as platform independent?
75. What are the advantages of java over C++?
76. How java can be connected to a database?
77. What is thread?
78. What is difference between Process and Thread?
79. Does java support multiple inheritance? if not, what is the solution?
80. What are abstract classes?
81. What is an interface?
82. What is the difference abstract class and interface?
83. What are adapter classes?
84. what is meant wrapper classes?
85. What are JVM.JRE, J2EE, JNI?
86. What are swing components?
87. What do you mean by light weight and heavy weight components?
88. What is meant by function overloading and function overriding?
89. Does java support function overloading, pointers, structures, unions or linked lists?
90. What do you mean by multithreading?
91. What are byte codes?
92. What are streams?
93. What is user defined exception?
94. In an htm page form I have one button which makes us to open a new page in 15 seconds. How will you do that? 


Advanced JAVA questions
1. What is RMI?
2. Explain about RMI Architecture?
3. What are Servelets?
4. What is the use of servlets?
5. Explain RMI Architecture?
6. How will you pass values from htm page to the servlet?
7. How do you load an image in a Servelet?
8. What is purpose of applet programming?
9. How will you communicate between two applets?
10. What IS the difference between Servelets and Applets?
11. How do you communicate in between Applets and Servlets?
12. What is the difference between applet and application?
13. What is the difference between CGI and Servlet?
14. In the servlets, we are having a web page that is invoking servlets ,username and password? which is checks in database? Suppose the second page also if we want to verify the same information whether it will connect to the database or it will be used previous information?
15. What are the difference between RMI and Servelets?
16. How will you call an Applet using Java Script Function?
17. How can you push data from an Applet to a Servlet?
18. What are 4 drivers available in JDBC? At what situation are four of the drivers used?
19. If you are truncated using JDBC , how can you that how much data is truncated?
20. How will you perform truncation using JDBC?
21. What is the latest version of JDBC? What are the new features added in that?
22. What is the difference between RMI registry and OS Agent?
23. To a server method, the client wants to send a value 20, with this value exceeds to 20 a message should be sent to the client . What will you do for achieving this?
24. How do you invoke a Servelet? What is the difference between doPost method and doGet method?
25. What is difference between the HTTP Servelet and Generic Servelet? Explain about their methods and parameters?
26. Can we use threads in Servelets?
27. Write a program on RMI and JDBC using Stored Procedure?
28. How do you swing an applet?
29. How will you pass parameters in RMI? Why do you serialize?
30. In RMI ,server object is first loaded into memory and then the stub reference is sent to the client. true or false?
31. Suppose server object not loaded into the memory and the client request for it. What will happen?
32. What is the web server used for running the servelets?
33. What is Servlet API used for connecting database?
34. What is bean? Where can it be used?
35. What is the difference between java class and bean?
36. Can we sent objects using Sockets?
37. What is the RMI and Socket?
38. What is CORBA?
39. Can you modify an object in corba?
40. What is RMI and what are the services in RMI?
41. What are the difference between RMI and CORBA?
42. How will you initialize an Applet?
43. What is the order of method invocation in an Applet?
44. What is ODBC and JDBC? How do you connect the Database?
45. What do you mean by Socket Programming?
46. What is difference between Generic Servlet and HTTP Servelet?
47. What you mean by COM and DCOM?
48. what is e-commerce?


Operating System Questions

1. What are the basic functions of an operating system?
2. Explain briefly about, processor, assembler, compiler, loader, linker and the functions executed by them.
3. What are the difference phases of software development? Explain briefly?
4. Differentiate between RAM and ROM?
5. What is DRAM? In which form does it store data?
6. What is cache memory?
7. What is hard disk and what is its purpose?
8. Differentiate between Complier and Interpreter?
9. What are the different tasks of Lexical analysis?
10. What are the different functions of Syntax phase, Sheduler?
11. What are the main difference between Micro-Controller and Micro- Processor?
12. Describe different job scheduling in operating systems.
13. What is a Real-Time System ?
14. What is the difference between Hard and Soft real-time systems ?
15. What is a mission critical system ?
16. What is the important aspect of a real-time system ?
17. If two processes which shares same system memory and system clock in a distributed system, What is it called?
18. What is the state of the processor, when a process is waiting for some event to occur?
19. What do you mean by deadlock?
20. Explain the difference between microkernel and macro kernel.
21. Give an example of microkernel.
22. When would you choose bottom up methodology?
23. When would you choose top down methodology?
24. Write a small dc shell script to find number of FF in the design.
25. Why paging is used ?
26. Which is the best page replacement algorithm and Why? How much time is spent usually in each phases and why?
27. Difference between Primary storage and secondary storage?
28. What is multi tasking, multi programming, multi threading?
29. Difference between multi threading and multi tasking?
30. What is software life cycle?
31. Demand paging, page faults, replacement algorithms, thrashing, etc.
32. Explain about paged segmentation and segment paging
33. While running DOS on a PC, which command would be used to duplicate the entire diskette?


MICROPROCESSOR QUESTIONS

1. Which type of architecture 8085 has?
2. How many memory locations can be addressed by a microprocessor with 14 address lines?
3. 8085 is how many bit microprocessor?
4. Why is data bus bi-directional?
5. What is the function of accumulator?
6. What is flag, bus?
7. What are tri-state devices and why they are essential in a bus oriented system?
8. Why are program counter and stack pointer 16-bit registers?
9. What does it mean by embedded system?
10. What are the different addressing modes in 8085?
11. What is the difference between MOV and MVI?
12. What are the functions of RIM, SIM, IN?
13. What is the immediate addressing mode?
14. What are the different flags in 8085?
15. What happens during DMA transfer?
16. What do you mean by wait state? What is its need?
17. What is PSW?
18. What is ALE? Explain the functions of ALE in 8085.
19. What is a program counter? What is its use?
20. What is an interrupt?
21. Which line will be activated when an output device require attention from CPU?

ELECTRONICS QUESTIONS

1. What is meant by D-FF?
2. What is the basic difference between Latches and Flip flops?
3. What is a multiplexer?
4. How can you convert an SR Flip-flop to a JK Flip-flop?
5. How can you convert an JK Flip-flop to a D Flip-flop?
6. What is Race-around problem? How can you rectify it?
7. Which semiconductor device is used as a voltage regulator and why?
8. What do you mean by an ideal voltage source?
9. What do you mean by zener breakdown and avalanche breakdown?
10. What are the different types of filters?
11. What is the need of filtering ideal response of filters and actual response of filters?
12. What is sampling theorem?
13. What is impulse response?
14. Explain the advantages and disadvantages of FIR filters compared to IIR counterparts.
15. What is CMRR? Explain briefly.
16. What do you mean by half-duplex and full-duplex communication? Explain briefly.
17. Which range of signals are used for terrestrial transmission?
18. What is the need for modulation?
19. Which type of modulation is used in TV transmission?
20. Why we use vestigial side band (VSB-C3F) transmission for picture?
21. When transmitting digital signals is it necessary to transmit some harmonics in addition to fundamental frequency?
22. For asynchronous transmission, is it necessary to supply some synchronizing pulses additionally or to supply or to supply start and stop bit?
23. BPFSK is more efficient than BFSK in presence of noise. Why?
24. What is meant by pre-emphasis and de-emphasis?
25. What do you mean by 3 dB cutoff frequency? Why is it 3 dB, not 1 dB?
26. What do you mean by ASCII, EBCDIC?

Aptitude Questions - Set 1

Aptitude Questions - Set 1
var pubId=17196; var siteId=17197; var kadId=14342; var kadwidth=300; var kadheight=250; var kadtype=1; 
 *An artical sold at amount of 50% the net sale price is rs 425 .what is the list price of the artical?

a) 500
b) 488
c) 480
d) 510

Ans 500

*A man leaves office daily at 7pm  A driver with car comes from his home to pick him from office and bring back home 
     One day he gets free at 5:30 and instead of waiting for driver he starts walking towards home.
     In the way he meets the car and returns home on car  He reaches home 20 minutes earlier than usual.
     In how much time does the man reach home usually??

Ans. 1hr 20min

*A works thrice as much as B. If A takes 60 days less than B to do a work then find the number of days it would take to       complete the work if both work together?

Ans. 22½days

*How many 1's are there in the binary form of  8*1024 + 3*64 + 3

Ans. 4

*In a digital circuit which was to implement (A B) + (A)XOR(B), the designer implements (A B) (A)XOR(B) 
    What is the probability of error in it ?

A boy has Rs 2. He wins or loses Re 1 at a time  If he wins he gets Re 1 and if he loses the game he loses Re 1.
     He can loose only 5 times. He is out of the game if he earns Rs 5.
     Find the number of ways in which this is possible?

Ans. 16

*If there are 1024*1280 pixels on a screen and each pixel can have around 16 million colors
     Find the memory required for this?

Ans. 4MB

*On a particular day A and B decide that they would either speak the truth or will lie.
     C asks A whether he is speaking truth or lying?
     He answers and B listens to what he said. C then asks B what A has said  B says "A says that he is a liar"
     What is B speaking ?

(a) Truth
(b) Lie
(c) Truth when A lies
(d) Cannot be determined

Ans. (b)

*What is the angle between the two hands of a clock when time is 8:30

Ans. 75(approx)

 *A student is ranked 13th from right and 8th from left. How many students are there in totality ?

* A man walks east and turns right and then from there to his left and then 45degrees to
  his right.In which direction did he go

Ans. North west

 *A student gets 70% in one subject, 80% in the other. To get an overall of   75% how much should get in third subject.

A man shows his friend a woman sitting in a park and says that she the daughter of my  grandmother's only son.
    What is the relation between the two

Ans. Daughter

 

 *How many squares with sides 1/2 inch long are needed to cover a rectangle that is 4 ft long and 6 ft wide

(a) 24
(b) 96
(c) 3456
(d) 13824
(e) 14266

 If a=2/3b , b=2/3c, and c=2/3d what part of d is b/

(a) 8/27
(b) 4/9
(c) 2/3
(d) 75%
(e) 4/3

Ans. (b)

*2598Successive discounts of 20% and 15% are equal to a single discount of

(a) 30%
(b) 32%
(c) 34%
(d) 35%
(e) 36

Ans. (b)

*The petrol tank of an automobile can hold g liters.If a liters was removed when the tank was full, what part of the full tank was removed?

(a)g-a
(b)g/a
(c) a/g
(d) (g-a)/a
(e) (g-a)/g

Ans. (c)

*If x/y=4 and y is not '0' what % of x is 2x-y

(a)150%
(b)175%
(c)200%
(d)250%

Ans. (b)

Infosys Aps Ques and answers


Infosys

Aptitude Questions with answers
1.There is a escalator and 2 persons move down it.A takes 50 steps and B takes 75 steps while the escalator is moving down. Given that the time taken
by A to take 1 step is equal to time taken by B to take 3 steps. Find the no. of steps in the escalator while it is staionary.
Solution (not sure):
If A takes 1 step in one second, then B takes 3 steps in one second. If A takes t1 seconds to take 50 steps, then B takes 150 steps in t1 seconds.
For B, to take 150 steps he requires t1 seconds,
then to take 75 steps he requires t1/2 seconds.
So now, s1=50, t1 = t1 & s2=75, t2=t1/2
ans= (s1*t2 ~ s2*t1) / (t1 ~ t2) which gives 100.
so 100 steps is the answer
2. If 5/2 artists make 5/2 paintings using 5/2 canvases in 5/2 days then how many artists r required to make 25 paintings using 25 canvases in 25 days?
3. If the digits of my present age are reversed then i get the age of my son.If 1 year ago my age was twice as that of my son.Find my present age.
ans. father-73, son-37
4. There are 6561 balls out of them 1 is heavy.Find the min. no. of times the balls have to be weighed for finding out the haevy ball.
ans. 8
5. If i walk with 30 miles/hr i reach 1 hour before and if i walk with 20 miles/hr i reach 1 hour late.Find the distance between 2 points and the
 exact time of reaching destination is 11 am then find the speed with which it walks.
ans. 120miles and 24 miles/hr
6. There r four face cards (J,Q,K,A) all of different types(diamond,club,spade,heart) and some conditions r given.find the order of cards
ans. king -> jack -> queen -> ace
heart diamond spade club
7. If A,B,C,D,E r 5 members of a family.4 of them give true statements :
1. E is my mother in law
2. C is my son in law's brother
3. B is my father's brother
4. A is my brother's wife
Who made the stmt. and what r the realtions among them
ans. E
|
A<-->B--C
|
D
<--> denotes husband-wife
-- denotes brothers
8. The product of 5 different temperatures is 12.If all of then r integers then find all the temperatures
ans. -2,-1,1,2,3
9.There r 9 cities numbered 1 to 9.From how many cities the flight can start so as to reach the city 8 either directly or indirectly such the path formed
 is divisible by 3.
eg. 1368-Flights goes through 1-3-6-8.
10. If i do this puzzle i find it to be hard than the last puzzle that i did before that after that..............very complex stmt.
Is that puzzle difficult,easy,can't say or depends on the no. of puzzles
11. Replace each letter by a digit. Each letter must be represented by the same digit and no beginning letter of a word can be 0.
O N E
O N E
O N E
O N E
-------
T E N
-------
Ans: 0 =1, N = 8 ,E = 2, T = 7.
12. Ann, Boobie, Cathy and Dave are at their monthly business meeting. Their occupations are author, biologist, chemist and doctor, but not necessarily
in that order. Dave just told the biologist that Cathy was on her way with doughnuts. Ann is sitting across from the doctor and next to the chemist.
 The doctor was thinking that Boobie was a goofy name for parent's to choose,but didn't say anything. What is each person's occupation?
Ans: Since Dave spoke to the biologist and Ann sat next to the chemist and across the doctor, Cathy must be the author and Ann the biologist.
The doctor didn't speak, but David did, so Bobbie is the doctor and Dave the chemist.
13. Sometime after 10:00 PM a murder took place. A witness claimed that the clock must have stopped at the time of the shooting. It was later found
that the postion of both the hands were the same but their positions had interchanged. Tell the time of the shooting (both actual and claimed).
Ans: Time of shooting = 11:54 PM Claimed Time = 10:59 PM.
14. Next number in the series is 1 , 2 , 4 , 13 , 31 , 112 , ?
Ans: 224.
No number has digits more than 4. All of them are 1 , 2, 4, 8 , 16 , 32 , 64 converted to numbers in base 5.
15. Shahrukh speaks truth only in the morning and lies in the afternoon, whereas Salman speaks truth only in the afternoon. A says that B is Shahrukh.
 Is it morning or afternoon and who is A - Shahrukh or Salman?
Ans: Afternoon.A is Salman.
16. Two trains starting at same time, one from Bangalore to Mysore and other in opposite direction arrive at their destination 1 hr and 4 hours respectively after passing each other. How nuch faster is one train from other?
Ans: Twice.
17. There are 6 volumes of books on a rack kept in order ( ie vol.1, vol. 2 and so on ). Give the position after the following changes were noticed.
All books have been changed Vol.5 was directly to the right of Vol.2 Vol.4 has Vol.6 to its left and both weren't at Vol.3's place.Vol.1 has Vol.3 on right
 and Vol.5 on left. An even numbered volume is at Vol.5's place Find the order in which the books are kept now.
Ans: 2, 5,1,3,6,4.
18. I bought a car with a peculiar 5 digit numbered licence plate which on reversing could still be read. On reversing value is increased by 78633.
Whats the original number if all digits were different?
Ans: Only 0 1 6 8 and 9 can be read upside down. So on rearranging these digits, we get the answer as 10968.
19. The shape in the sketch below is that of a square attached to half of a similar square. Divide it into four equal pieces.
Ans: Hint : The figure can be divided into 12 equal triangles.

20) There are two balls touching each other circumferencically. The radius of the big ball is 4 times the diameter of the small all.
The outer small ball rotates in anticlockwise direction circumferencically over the bigger one at the rate of 16 rev/sec. The bigger wheel also rotates
 anticlockwise at N rev/sec. What is 'N' for the horizontal line from the centre of small wheel always is horizontal.
21)
1 2 3 4
+ 3 4 5 5
----------
4 6 8 9
- 2 3 4 5
----------
2 3 4 4
+ 1 2 5 4
------------
3 6 9 8
------------
Q) Strike off any digit from each number in seven rows (need not be at same place) and combine the same operations with 3 digit numbers to get the same addition. After this strike off another digit from all and add all the No.s to get the same 2 digit No. perform the same process again with 1 digit No.s. Give the ' no.s in 7 rows at each stage.
22) There is a safe with a 5 digit No. The 4th digit is 4 greater thansecond digit, while 3rd digit is 3 less than 2nd digit. The 1st digit is thrice the last digit. There are 3 pairs whose sum is 11. Find the number.
Ans: 65292.
23) there are 2 guards Bal and Pal walking on the side of a wall of a wearhouse(12m X 11m) in opposite directions. They meet at a point and Bal says to Pal "See you again in the other side". After a few moments of walking Bal decides to go back for a smoke but he changes his direction again to his previous one after 10 minutes of walking in the other(opposite) direction remembering that Pal will be waiting for to meet. If Bal and Pal walk 8 and 11 feet respectively, how much distance they would have travelled before meeting again.
24. 13 kigs and 6 libs can produce 510 tors in 10 hrs, 8 kigs and 14 libs can produce 484 tors in 12 hrs.
Find the rate of production of tors for kigs and libs. Express the answer in tors/hr.
25)
xxx)xxxxx(xxx
3xx
-------
xxx
x3x
-------
xxx
3xx
-------
Q) Find the 5 digit No.
Hint: 5 is used atleast once in the calculation.
26) A fly is there 1 feet below the ceiling right across a wall length is 30m at equal distance from both the ends. There is a spider 1 feet above floor right across the long wall eqidistant from both the ends. If the width of the room is 12m and 12m, what distance is to be travelled by the spider to catch the fly, if it takes the shortest path.
27) Ramesh sit around a round table with some other men. He has one rupee more than his right person and this person in turn has 1 rupee more than the person to his right and so on, Ramesh decided to give 1 rupee to his right & he in turn 2 rupees to his right and 3 rupees to his right & so on. This process went on till a person has 'no money' to give to his right. At this time he has 4 times the money to his right person. How many men are there along with Ramesh and what is the money with poorest fellow.
28)Question related to probabilities of removing the red ball from a basket, given that two balls are removed from the basket and the other ball is red. The basket contains blue,red,yellow balls.
29)Venkat has 1boy&2daughters.The product of these children age is 72.The sum of their ages give the door numberof Venkat.Boy is elder of three.Can you tell the ages of all the three.
30)L:says all of my other 4 friends have money
M:says that P said that exact one has money
N:says that L said that precisely two have money
O:says that M said that 3 of others have money.
P:Land N said that they have money.
All are liers.
Who has money & who doesn't have?
31)Post man has a data of name surname door number, pet name of 4 families. But only one is correct for each family. There are a set of statements & questions.
33) 4 couples have a party. Depending on the set of statements, find who insulted whom and who is the host of the party.
34) 5 women given some of their heights (tall,medium,short) Hair( long, plainted), stards(Black or Brown), sari,2 medium,2-short.Tall->no sari.Plainted->medium. Answer the combinations.
35) A person has to go both Northwards & Southwards in search of a job. He decides to go by the first train he encounters.There are trains for every 15 min both southwards and northwards. First train towards south is at 6:00 A.M. and that towards North is at 6:10. If the person arrives at any random time, what is the probability that he gets into a train towards North.
36) A person has his own coach&. Whenever he goes to railway station he takes his coach. One day he was supposed to reach the railway station at 5 O'clock. But he finished his work early and reached at 3 O'clock. Then he rung up his residence and asked to send the coach immediately. He came to know that the coach has left just now to the railway station. He thought that the coach has left just now to the railway station. He thought that he should not waste his time and started moving towards his residence at the speed of 3 miles/hr. On the way, he gets the coach and reaches home at 6 o'clock. How far is his residence from railway station.
37) Radha,Geeta & Revathi went for a picnic. After a few days they forgot the date, day and month on which they went to picnic. Radha said that it was on Thursday, May 8 and Geeta said that it was Thursday May 10. Revathi said Friday Jun 8. Now one of them told all things wrongly, others one thing wrong and the last two things wrongly. If April 1st is tuesday, what is the right day, date and month?

38. There is 66x33m rectangular area. Ram is 11/8 times faster than Krishna. Both of them started walking at opposite ends and they met at some point then, Ram said "See you in the other end" Then they continued walking. After some time Ram thought he will have tea so he turned back walked back 15 meters then he changed his mind again andcontinued walking. How much Krishna has traveled by the time they meet?
39. There are 5 burglars and once went to a bakery to rob it obviously The first guy ate 1/2 of the total bread and 1/2 of the bread. The second guy ate 1/2 of the remaining and 1/2 of the bread. The third guy ,fourth guy and fifth guy did the same. After fifth guy there is no bread left out. How many bread are there?
40. All members belonging to D are members of A.
All members belonging to E are members of D.
All members belonging to C are members of both A & D.
Some members of A does not belong to D. All members belonging to D are members of E. 5 questions are there.
41. Write each statements true or false:-
1. The sum of the 1st three statements and the 2nd false statement gives the true statement.
2.The no. of true statements false statement.
3. The sum of 2nd true statement and 1st false statement gives the first true statement.
4. There are at most 3 false statements.
5.There is no two consecutive true statements.
42. There are twelve consecutive flags at an equal interval of distance. A man passes the 8th flag in 8 seconds. How many more seconds will he take to pass the remaining 4 flags?
43. A person has to cover the fixed distance through his horses. There are five horses in the cart. They ran at the full potential for the 24 hours continuously at constant speed and then two of the horses ran away to some other direction. So he reached the destination 48 hours behind the schedule. If the five horses would have run 50 miles more, then the person would have been only 24 hours late. Find the distance of the destination.
44. A boat M leaves shore A and at the same time boat B leaves shore B. They move across the river. They met at 500 yards away from A and after that they met 300 yards away from shore B without halting at shores. Find the distance between the shore A & B.
45. A person was going through train from Bombay to Pune. After every five minutes he finds a train coming from opposite direction. Velocity of trains are equal of either direction. If the person reached Pune in one hour then how many trains he saw in the journey?
46. Food grains are to be sent to city from godown. Owner wants to reach the food grains at 11 O' Clock in the city. If a truck travels at a speed of 30km/hr then he will reach the city one hour earlier. If the truck travels at a speed of 20km/h then he will reach the city one hour late. Find the distance between the godown to city. Also with which speed the truck should travel in order to reach at exactly 11 'O clock.
47. There are five persons A,B,C,D,E whose birthdays occur at the consecutive days. Birthday of A is some days or day before C & birthday of B is exactly the same days or day after E. D is two days older than E. If birth day of C is on Wednesday then find out the birthdays of other.
48. Persons say these statements.
A says either Democratic or liberal wins the elections.
B says Democratic wins.
C says neither democratic nor liberal wins the election.
Of these only one is wrong. Who wins the election?
49. Six persons A,B,C,D,E &F went to soldier cinema. There are six consecutive seats. A sits in the first seat followed by B, followed by C and so on. If A taken on of the six seats, then B should sit adjacent to A. C should sit adjacent to A or B. D should sit adjacent to A, B or C and so on. How many possibilities are there ?
50. Suppose there are four grades A, B, C, D. (A is the best and D is the worst) 4 persons Jack, Jean, Poul and Lucy wrote the final exam and made the statements like this:-
1. Jack: If I will get A then Lucy will get D.
2. Lucy: If I will get C then Jack will get D.
Jack grade is better than Poul grade.
3. Jean: If Jean doesn't get A then Jack will not get A.
4. Poul: If Jack get A, then Jean will not get B, Lucy will get C, I won't either A or B.
If all the above statements are true, then which person will get which grade?

Test Your C and C ++ Skills - Set 7


Test Your C and C ++ Skills - Set 7
151) #include <stdio.h>
main()
{
char * str = "hello";
char * ptr = str;
char least = 127;
while (*ptr++)
least = (*ptr<least ) ?*ptr :least;
printf("%d",least);
}
Answer:
0
Explanation:
After ‘ptr’ reaches the end of the string the value pointed by ‘str’ is ‘\0’. So the value of ‘str’ is less than that of ‘least’. So the value of ‘least’ finally is 0.

152) Declare an array of N pointers to functions returning pointers to functions returning pointers to characters?
Answer:
(char*(*)( )) (*ptr[N])( );

153) main()
{
struct student
{
char name[30];
struct date dob;
}stud;
struct date
{
int day,month,year;
};
scanf("%s%d%d%d", stud.rollno, &student.dob.day, &student.dob.month, &student.dob.year);
}
Answer:
Compiler Error: Undefined structure date
Explanation:
Inside the struct definition of ‘student’ the member of type struct date is given. The compiler doesn’t have the definition of date structure (forward reference is not allowed in C in this case) so it issues an error.

154) main()
{
struct date;
struct student
{
char name[30];
struct date dob;
}stud;
struct date
{
int day,month,year;
};
scanf("%s%d%d%d", stud.rollno, &student.dob.day, &student.dob.month, &student.dob.year);
}
Answer:
Compiler Error: Undefined structure date
Explanation:
Only declaration of struct date is available inside the structure definition of ‘student’ but to have a variable of type struct date the definition of the structure is required.


155) There were 10 records stored in “somefile.dat” but the following program printed 11 names. What went wrong?
void main()
{
struct student
{
char name[30], rollno[6];
}stud;
FILE *fp = fopen(“somefile.dat”,”r”);
while(!feof(fp))
{
fread(&stud, sizeof(stud), 1 , fp);
puts(stud.name);
}
}
Explanation:
fread reads 10 records and prints the names successfully. It will return EOF only when fread tries to read another record and fails reading EOF (and returning EOF). So it prints the last record again. After this only the condition feof(fp) becomes false, hence comes out of the while loop.

156) Is there any difference between the two declarations,
1. int foo(int *arr[]) and
2. int foo(int *arr[2])
Answer:
No
Explanation:
Functions can only pass pointers and not arrays. The numbers that are allowed inside the [] is just for more readability. So there is no difference between the two declarations.

157) What is the subtle error in the following code segment?
void fun(int n, int arr[])
{
int *p=0;
int i=0;
while(i++<n)
p = &arr[i];
*p = 0;
}
Answer & Explanation:
If the body of the loop never executes p is assigned no address. So p remains NULL where *p =0 may result in problem (may rise to runtime error “NULL pointer assignment” and terminate the program).

158) What is wrong with the following code?
int *foo()
{
int *s = malloc(sizeof(int)100);
assert(s != NULL);
return s;
}
Answer & Explanation:
assert macro should be used for debugging and finding out bugs. The check s != NULL is for error/exception handling and for that assert shouldn’t be used. A plain if and the corresponding remedy statement has to be given.

159) What is the hidden bug with the following statement?
assert(val++ != 0);
Answer & Explanation:
Assert macro is used for debugging and removed in release version. In assert, the experssion involves side-effects. So the behavior of the code becomes different in case of debug version and the release version thus leading to a subtle bug.
Rule to Remember:
Don’t use expressions that have side-effects in assert statements.

160) void main()
{
int *i = 0x400; // i points to the address 400
*i = 0; // set the value of memory location pointed by i;
}
Answer:
Undefined behavior
Explanation:
The second statement results in undefined behavior because it points to some location whose value may not be available for modification. This type of pointer in which the non-availability of the implementation of the referenced location is known as 'incomplete type'.

161) #define assert(cond) if(!(cond)) \
(fprintf(stderr, "assertion failed: %s, file %s, line %d \n",#cond,\
__FILE__,__LINE__), abort())
void main()
{
int i = 10;
if(i==0)
assert(i < 100);
else
printf("This statement becomes else for if in assert macro");
}
Answer:
No output
Explanation:
The else part in which the printf is there becomes the else for if in the assert macro. Hence nothing is printed.
The solution is to use conditional operator instead of if statement,
#define assert(cond) ((cond)?(0): (fprintf (stderr, "assertion failed: \ %s, file %s, line %d \n",#cond, __FILE__,__LINE__), abort()))
Note:
However this problem of “matching with nearest else” cannot be solved by the usual method of placing the if statement inside a block like this,
#define assert(cond) { \
if(!(cond)) \
(fprintf(stderr, "assertion failed: %s, file %s, line %d \n",#cond,\
__FILE__,__LINE__), abort()) \
}

162) Is the following code legal?
struct a
{
int x;
struct a b;
}
Answer:
No
Explanation:
Is it not legal for a structure to contain a member that is of the same
type as in this case. Because this will cause the structure declaration to be recursive without end.

163) Is the following code legal?
struct a
{
int x;
struct a *b;
}
Answer:
Yes.
Explanation:
*b is a pointer to type struct a and so is legal. The compiler knows, the size of the pointer to a structure even before the size of the structure
is determined(as you know the pointer to any type is of same size). This type of structures is known as ‘self-referencing’ structure.

164) Is the following code legal?
typedef struct a
{
int x;
aType *b;
}aType
Answer:
No
Explanation:
The typename aType is not known at the point of declaring the structure (forward references are not made for typedefs).

165) Is the following code legal?
typedef struct a aType;
struct a
{
int x;
aType *b;
};
Answer:
Yes
Explanation:
The typename aType is known at the point of declaring the structure, because it is already typedefined.

166) Is the following code legal?
void main()
{
typedef struct a aType;
aType someVariable;
struct a
{
int x;
aType *b;
};
}
Answer:
No
Explanation:
When the declaration,
typedef struct a aType;
is encountered body of struct a is not known. This is known as ‘incomplete types’.

167) void main()
{
printf(“sizeof (void *) = %d \n“, sizeof( void *));
printf(“sizeof (int *) = %d \n”, sizeof(int *));
printf(“sizeof (double *) = %d \n”, sizeof(double *));
printf(“sizeof(struct unknown *) = %d \n”, sizeof(struct unknown *));
}
Answer :
sizeof (void *) = 2
sizeof (int *) = 2
sizeof (double *) = 2
sizeof(struct unknown *) = 2
Explanation:
The pointer to any type is of same size.

168) char inputString[100] = {0};
To get string input from the keyboard which one of the following is better?
1) gets(inputString)
2) fgets(inputString, sizeof(inputString), fp)
Answer & Explanation:
The second one is better because gets(inputString) doesn't know the size of the string passed and so, if a very big input (here, more than 100 chars) the charactes will be written past the input string. When fgets is used with stdin performs the same operation as gets but is safe.

169) Which version do you prefer of the following two,
1) printf(“%s”,str); // or the more curt one
2) printf(str);
Answer & Explanation:
Prefer the first one. If the str contains any format characters like %d then it will result in a subtle bug.


170) void main()
{
int i=10, j=2;
int *ip= &i, *jp = &j;
int k = *ip/*jp;
printf(“%d”,k);
}
Answer:
Compiler Error: “Unexpected end of file in comment started in line 5”.
Explanation:
The programmer intended to divide two integers, but by the “maximum munch” rule, the compiler treats the operator sequence / and * as /* which happens to be the starting of comment. To force what is intended by the programmer,
int k = *ip/ *jp;
// give space explicity separating / and *
//or
int k = *ip/(*jp);
// put braces to force the intention
will solve the problem.

171) void main()
{
char ch;
for(ch=0;ch<=127;ch++)
printf(“%c %d \n“, ch, ch);
}
Answer:
Implementaion dependent
Explanation:
The char type may be signed or unsigned by default. If it is signed then ch++ is executed after ch reaches 127 and rotates back to -128. Thus ch is always smaller than 127.

172) Is this code legal?
int *ptr;
ptr = (int *) 0x400;
Answer:
Yes
Explanation:
The pointer ptr will point at the integer in the memory location 0x400.


173) main()
{
char a[4]="HELLO";
printf("%s",a);
}
Answer:
Compiler error: Too many initializers
Explanation:
The array a is of size 4 but the string constant requires 6 bytes to get stored.

174) main()
{
char a[4]="HELL";
printf("%s",a);
}
Answer:
HELL%@!~@!@???@~~!
Explanation:
The character array has the memory just enough to hold the string “HELL” and doesnt have enough space to store the terminating null character. So it prints the HELL correctly and continues to print garbage values till it accidentally comes across a NULL character.

175) main()
{
int a=10,*j;
void *k;
j=k=&a;
j++;
k++;
printf("\n %u %u ",j,k);
}
Answer:
Compiler error: Cannot increment a void pointer
Explanation:
Void pointers are generic pointers and they can be used only when the type is not known and as an intermediate address storage type. No pointer arithmetic can be done on it and you cannot apply indirection operator (*) on void pointers.

176) main()
{
extern int i;
{ int i=20;
{
const volatile unsigned i=30; printf("%d",i);
}
printf("%d",i);
}
printf("%d",i);
}
int i;

177) Printf can be implemented by using __________ list.
Answer:
Variable length argument lists

178) char *someFun()
{
char *temp = “string constant";
return temp;
}
int main()
{
puts(someFun());
}
Answer:
string constant
Explanation:
The program suffers no problem and gives the output correctly because the character constants are stored in code/data area and not allocated in stack, so this doesn’t lead to dangling pointers.

179) char *someFun1()
{
char temp[ ] = “string";
return temp;
}
char *someFun2()
{
char temp[ ] = {‘s’, ‘t’,’r’,’i’,’n’,’g’};
return temp;
}
int main()
{
puts(someFun1());
puts(someFun2());
}
Answer:
Garbage values.
Explanation:
Both the functions suffer from the problem of dangling pointers. In someFun1() temp is a character array and so the space for it is allocated in heap and is initialized with character string “string”. This is created dynamically as the function is called, so is also deleted dynamically on exiting the function so the string data is not available in the calling function main() leading to print some garbage values. The function someFun2() also suffers from the same problem but the problem can be easily identified in this case.

Test Your C and C ++ Skills - Set 6


Test Your C and C ++ Skills - Set 6
126)
int aaa() {printf(“Hi”);}
int bbb(){printf(“hello”);}
iny ccc(){printf(“bye”);}
main()
{
int ( * ptr[3]) ();
ptr[0] = aaa;
ptr[1] = bbb;
ptr[2] =ccc;
ptr[2]();
}
Answer:
bye
Explanation:
int (* ptr[3])() says that ptr is an array of pointers to functions that takes no arguments and returns the type int. By the assignment ptr[0] = aaa; it means that the first function pointer in the array is initialized with the address of the function aaa. Similarly, the other two array elements also get initialized with the addresses of the functions bbb and ccc. Since ptr[2] contains the address of the function ccc, the call to the function ptr[2]() is same as calling ccc(). So it results in printing "bye".
127)
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.
128) main()
{
char p[ ]="%d\n";
p[1] = 'c';
printf(p,65);
}
Answer:
A
Explanation:
Due to the assignment p[1] = ‘c’ the string becomes, “%c\n”. Since this string becomes the format string for printf and ASCII value of 65 is ‘A’, the same gets printed.


129) void ( * abc( int, void ( *def) () ) ) ();
Answer::
abc is a ptr to a function which takes 2 parameters .(a). an integer variable.(b). a ptrto a funtion which returns void. the return type of the function is void.
Explanation:
Apply the clock-wise rule to find the result.
130) 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.
131) 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, it treats whatever the values that are in the following positions as part of the string until it randomly reaches a ‘\0’. So str1 and str2 are not the same, hence the result.


132) main()
{
int i = 3;
for (;i++=0;) printf(“%d”,i);
}
Answer:
Compiler Error: Lvalue required.
Explanation:
As we know that increment operators return rvalues and hence it cannot appear on the left hand side of an assignment operation.


133) 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.
134) 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.
135) main()
{
int i=10,j=20;
j = i, j?(i,j)?i:j:j;
printf("%d %d",i,j);
}
Answer:
10 10
Explanation:
The Ternary operator ( ? : ) is equivalent for if-then-else statement. So the question can be written as:
if(i,j)
{
if(i,j)
j = i;
else
j = j;
}
else
j = j;
136) 1. const char *a;
2. char* const a;
3. char const *a;
-Differentiate the above declarations.
Answer:
1. 'const' applies to char * rather than 'a' ( pointer to a constant char )
*a='F' : illegal
a="Hi" : legal
2. 'const' applies to 'a' rather than to the value of a (constant pointer to char )
*a='F' : legal
a="Hi" : illegal
3. Same as 1.
137) main()
{
int i=5,j=10;
i=i&=j&&10;
printf("%d %d",i,j);
}
Answer:
1 10
Explanation:
The expression can be written as i=(i&=(j&&10)); The inner expression (j&&10) evaluates to 1 because j==10. i is 5. i = 5&1 is 1. Hence the result.
138) main()
{
int i=4,j=7;
j = j || i++ && printf("YOU CAN");
printf("%d %d", i, j);
}
Answer:
4 1
Explanation:
The boolean expression needs to be evaluated only till the truth value of the expression is not known. j is not equal to zero itself means that the expression’s truth value is 1. Because it is followed by || and true || (anything) => true where (anything) will not be evaluated. So the remaining expression is not evaluated and so the value of i remains the same.
Similarly when && operator is involved in an expression, when any of the operands become false, the whole expression’s truth value becomes false and hence the remaining expression will not be evaluated.
false && (anything) => false where (anything) will not be evaluated.
139) main()
{
register int a=2;
printf("Address of a = %d",&a);
printf("Value of a = %d",a);
}
Answer:
Compier Error: '&' on register variable
Rule to Remember:
& (address of ) operator cannot be applied on register variables.
140) main()
{
float i=1.5;
switch(i)
{
case 1: printf("1");
case 2: printf("2");
default : printf("0");
}
}
Answer:
Compiler Error: switch expression not integral
Explanation:
Switch statements can be applied only to integral types.
141) main()
{
extern i;
printf("%d\n",i);
{
int i=20;
printf("%d\n",i);
}
}
Answer:
Linker Error : Unresolved external symbol i
Explanation:
The identifier i is available in the inner block and so using extern has no use in resolving it.
142) main()
{
int a=2,*f1,*f2;
f1=f2=&a;
*f2+=*f2+=a+=2.5;
printf("\n%d %d %d",a,*f1,*f2);
}
Answer:
16 16 16
Explanation:
f1 and f2 both refer to the same memory location a. So changes through f1 and f2 ultimately affects only the value of a.


143) main()
{
char *p="GOOD";
char a[ ]="GOOD";
printf("\n sizeof(p) = %d, sizeof(*p) = %d, strlen(p) = %d", sizeof(p), sizeof(*p), strlen(p));
printf("\n sizeof(a) = %d, strlen(a) = %d", sizeof(a), strlen(a));
}
Answer:
sizeof(p) = 2, sizeof(*p) = 1, strlen(p) = 4
sizeof(a) = 5, strlen(a) = 4
Explanation:
sizeof(p) => sizeof(char*) => 2
sizeof(*p) => sizeof(char) => 1
Similarly,
sizeof(a) => size of the character array => 5
When sizeof operator is applied to an array it returns the sizeof the array and it is not the same as the sizeof the pointer variable. Here the sizeof(a) where a is the character array and the size of the array is 5 because the space necessary for the terminating NULL character should also be taken into account.
144) #define DIM( array, type) sizeof(array)/sizeof(type)
main()
{
int arr[10];
printf(“The dimension of the array is %d”, DIM(arr, int));
}
Answer:
10
Explanation:
The size of integer array of 10 elements is 10 * sizeof(int). The macro expands to sizeof(arr)/sizeof(int) => 10 * sizeof(int) / sizeof(int) => 10.
145) int DIM(int array[])
{
return sizeof(array)/sizeof(int );
}
main()
{
int arr[10];
printf(“The dimension of the array is %d”, DIM(arr));
}
Answer:
1
Explanation:
Arrays cannot be passed to functions as arguments and only the pointers can be passed. So the argument is equivalent to int * array (this is one of the very few places where [] and * usage are equivalent). The return statement becomes, sizeof(int *)/ sizeof(int) that happens to be equal in this case.
146) main()
{
static int a[3][3]={1,2,3,4,5,6,7,8,9};
int i,j;
static *p[]={a,a+1,a+2};
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf("%d\t%d\t%d\t%d\n",*(*(p+i)+j),
*(*(j+p)+i),*(*(i+p)+j),*(*(p+j)+i));
}
}
Answer:
1 1 1 1
2 4 2 4
3 7 3 7
4 2 4 2
5 5 5 5
6 8 6 8
7 3 7 3
8 6 8 6
9 9 9 9
Explanation:
*(*(p+i)+j) is equivalent to p[i][j].
147) main()
{
void swap();
int x=10,y=8;
swap(&x,&y);
printf("x=%d y=%d",x,y);
}
void swap(int *a, int *b)
{
*a ^= *b, *b ^= *a, *a ^= *b;
}
Answer:
x=10 y=8
Explanation:
Using ^ like this is a way to swap two variables without using a temporary variable and that too in a single statement.
Inside main(), void swap(); means that swap is a function that may take any number of arguments (not no arguments) and returns nothing. So this doesn’t issue a compiler error by the call swap(&x,&y); that has two arguments.
This convention is historically due to pre-ANSI style (referred to as Kernighan and Ritchie style) style of function declaration. In that style, the swap function will be defined as follows,
void swap()
int *a, int *b
{
*a ^= *b, *b ^= *a, *a ^= *b;
}
where the arguments follow the (). So naturally the declaration for swap will look like, void swap() which means the swap can take any number of arguments.
148) main()
{
int i = 257;
int *iPtr = &i;
printf("%d %d", *((char*)iPtr), *((char*)iPtr+1) );
}
Answer:
1 1
Explanation:
The integer value 257 is stored in the memory as, 00000001 00000001, so the individual bytes are taken by casting it to char * and get printed.
149) main()
{
int i = 258;
int *iPtr = &i;
printf("%d %d", *((char*)iPtr), *((char*)iPtr+1) );
}
Answer:
2 1
Explanation:
The integer value 257 can be represented in binary as, 00000001 00000001. Remember that the INTEL machines are ‘small-endian’ machines. Small-endian means that the lower order bytes are stored in the higher memory addresses and the higher order bytes are stored in lower addresses. The integer value 258 is stored in memory as: 00000001 00000010.
150) main()
{
int i=300;
char *ptr = &i;
*++ptr=2;
printf("%d",i);
}
Answer:
556
Explanation:
The integer value 300 in binary notation is: 00000001 00101100. It is stored in memory (small-endian) as: 00101100 00000001. Result of the expression *++ptr = 2 makes the memory representation as: 00101100 00000010. So the integer corresponding to it is 00000010 00101100 => 556.

Test Your C and C ++ Skills - Set 5


Test Your C and C ++ Skills - Set 5
101) 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.
102) 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).
103) 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.
104) void 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.
105) #include<conio.h>
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.
Thumb Rule: Check all control paths to write bug free code.
106) 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 !
107) #define prod(a,b) a*b
main()
{
int x=3,y=4;
printf("%d",prod(x+2,y-1));
}
Answer:
10
Explanation:
The macro expands and evaluates to as:
x+2*y-1 => x+(2*y)-1 => 10
108) 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.


109) 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.


110) main()
{
int i=10;
void pascal f(int,int,int);
f(i++,i++,i++);
printf(" %d",i);
}
void pascal f(integer :i,integer:j,integer :k)
{
write(i,j,k);
}
Answer:
Compiler error: unknown type integer
Compiler error: undeclared function write
Explanation:
Pascal keyword doesn’t mean that pascal code can be used. It means that the function follows Pascal argument passing mechanism in calling the functions.
111) void pascal f(int i,int j,int k)
{
printf(“%d %d %d”,i, j, k);
}
void cdecl f(int i,int j,int k)
{
printf(“%d %d %d”,i, j, k);
}
main()
{
int i=10;
f(i++,i++,i++);
printf(" %d\n",i);
i=10;
f(i++,i++,i++);
printf(" %d",i);
}
Answer:
10 11 12 13
12 11 10 13
Explanation:
Pascal argument passing mechanism forces the arguments to be called from left to right. cdecl is the normal C argument passing mechanism where the arguments are passed from right to left.


112). What is the output of the program given below
main()
{
signed char i=0;
for(;i>=0;i++) ;
printf("%d\n",i);
}
Answer
-128
Explanation
Notice the semicolon at the end of the for loop. THe initial value of the i is set to 0. The inner loop executes to increment the value from 0 to 127 (the positive range of char) and then it rotates to the negative value of -128. The condition in the for loop fails and so comes out of the for loop. It prints the current value of i that is -128.


113) main()
{
unsigned char i=0;
for(;i>=0;i++) ;
printf("%d\n",i);
}
Answer
infinite loop
Explanation
The difference between the previous question and this one is that the char is declared to be unsigned. So the i++ can never yield negative value and i>=0 never becomes false so that it can come out of the for loop.
114) main()
{
char i=0;
for(;i>=0;i++) ;
printf("%d\n",i);

}
Answer:
Behavior is implementation dependent.
Explanation:
The detail if the char is signed/unsigned by default is implementation dependent. If the implementation treats the char to be signed by default the program will print –128 and terminate. On the other hand if it considers char to be unsigned by default, it goes to infinite loop.
Rule:
You can write programs that have implementation dependent behavior. But dont write programs that depend on such behavior.
115) 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.
Apply clock-wise rule to find the meaning of this definition.
116). What is the output for the program given below
typedef enum errorType{warning, error, exception,}error;
main()
{
error g1;
g1=1;
printf("%d",g1);
}
Answer
Compiler error: Multiple declaration for error
Explanation
The name error is used in the two meanings. One means that it is a enumerator constant with value 1. The another use is that it is a type name (due to typedef) for enum errorType. Given a situation the compiler cannot distinguish the meaning of error to know in what sense the error is used:
error g1;
g1=error;
// which error it refers in each case?
When the compiler can distinguish between usages then it will not issue error (in pure technical terms, names can only be overloaded in different namespaces).
Note: the extra comma in the declaration,
enum errorType{warning, error, exception,}
is not an error. An extra comma is valid and is provided just for programmer’s convenience.
117)typedef struct error{int warning, error, exception;}error;
main()
{
error g1;
g1.error =1;
printf("%d",g1.error);
}
Answer
1
Explanation
The three usages of name errors can be distinguishable by the compiler at any instance, so valid (they are in different namespaces).
Typedef struct error{int warning, error, exception;}error;
This error can be used only by preceding the error by struct kayword as in:
struct error someError;
typedef struct error{int warning, error, exception;}error;
This can be used only after . (dot) or -> (arrow) operator preceded by the variable name as in :
g1.error =1;
printf("%d",g1.error);
typedef struct error{int warning, error, exception;}error;
This can be used to define variables without using the preceding struct keyword as in:
error g1;
Since the compiler can perfectly distinguish between these three usages, it is perfectly legal and valid.
Note
This code is given here to just explain the concept behind. In real programming don’t use such overloading of names. It reduces the readability of the code. Possible doesn’t mean that we should use it!


118) #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.
119) #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.
120). What is the output for the following program
main()
{
int arr2D[3][3];
printf("%d\n", ((arr2D==* arr2D)&&(* arr2D == arr2D[0])) );
}
Answer
1
Explanation
This is due to the close relation between the arrays and pointers. N dimensional arrays are made up of (N-1) dimensional arrays.
arr2D is made up of a 3 single arrays that contains 3 integers each .
The name arr2D refers to the beginning of all the 3 arrays. *arr2D refers to the start of the first 1D array (of 3 integers) that is the same address as arr2D. So the expression (arr2D == *arr2D) is true (1).
Similarly, *arr2D is nothing but *(arr2D + 0), adding a zero doesn’t change the value/meaning. Again arr2D[0] is the another way of telling *(arr2D + 0). So the expression (*(arr2D + 0) == arr2D[0]) is true (1).
Since both parts of the expression evaluates to true the result is true(1) and the same is printed.
121) void main()
{
if(~0 == (unsigned int)-1)
printf(“You can answer this if you know how values are represented in memory”);
}
Answer
You can answer this if you know how values are represented in memory
Explanation
~ (tilde operator or bit-wise negation operator) operates on 0 to produce all ones to fill the space for an integer. –1 is represented in unsigned value as all 1’s and so both are equal.
122) 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.
123) main()
{
char *p = “ayqm”;
printf(“%c”,++*(p++));
}
Answer:
b
124) 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.
125) 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.