Вы находитесь на странице: 1из 12

Standard C and programming Questions

Will be useful for core CS and normal Software Companies Software Companies concentrate on programming (ques 1 5, 8, 11 13, 15, 16) Core CS Data Structures, Algorithms and OS 1. What are storage classes 2. What is a static variable 3. What is the difference between a[i] and i[a] 4. What does the const keyword do 5. Where are the static and automatic variables stored 6. What is the equivalent of malloc and free in C++ ans. new and delete 7. What happens when we take 100 bytes using malloc and use 200 bytes 8. What is the difference between const int *a and int *const a 9. Write a function for the inorder traversal of a binary search tree 10. Write a function to reverse a singly linked list 11. Given 2 strings write a program to see if the string2 is there in string1. Ex. String1 = Happy days, string2= day must print matching and String1 = trumple, string2=ample must not print anything 12. What are bit fields 13. Write a program to find the number of set bits(no. of ones in its binary representation) in a number. For ex. 25 i.e. 11001 has 3 set bits 14. Given a 16 bit number, how do you change n bits starting from the mth position from the right. a. reverse those n bits b. make all those n bits ones c. make them zeroes ex. 10 1010 0101010100 with m=3 and n =4. Answers will be a. 10 0101 0101010100 b. 10 1111 0101010100 c. 10 0000 0101010100 15. What is the difference between if (i=2) and if (i==2) 16. What is Object Oriented Programming? 17. What is a deadlock and semaphore

Some Answers
1 & 2. Every C variable has a storage class and a scope. The storage class determines the part of memory where storage is allocated for an object (variable) and how long the storage allocation continues to exist. It also determines the scope which specifies the part of the program over which a variable name is visible, i.e. the variable is accessible by name. There are four storage classes in C a. Automatic auto Auto is the default storage class for variables. These are visible only in the blocks in which they are defined and also in the blocks nested within these blocks.

auto int a; is the same as int a; b. Register - Register variables are a special case of automatic variables. Automatic variables are allocated storage in the memory of the computer; however, for most computers, accessing data in memory is considerably slower than processing in the CPU. These computers often have small amounts of storage within the CPU itself where data can be stored and accessed quickly. These storage cells are called registers. Normally, the compiler determines what data is to be stored in the registers of the CPU at what times. However, the C language provides the storage class register so that the programmer can ``suggest'' the compiler that particular automatic variables should be allocated to CPU registers, if possible. Thus, register variables provide a certain control over efficiency of program execution. Variables which are used repeatedly or whose access times are critical may be declared to be of storage class register. Eg. register int a;

c. Static. Static variables maintain their value between function calls. Variables not declared static get destroyed once the function is executed. Static variables are initialized once and if any change occurs the new value will be used when the function is called next. Ex. main () { int x, y; Func(); Func(); Func(); } Func () { int normal=10; static int special=10; normal = normal + 1; special++; printf (%d \t %d \n, normal, special); } Output: 11 11 11 11 12 13

d. External extern Suppose a C program has 32 files and you have a variable which needs to be accessed by some 10 functions which are in 10 different files. Let the variable be called x. First you have to declare x in one file outside any function in that file without using the keyword extern. This makes the variable global. Later you can declare the variable as extern int x; in the other files which need access to this variable.

Ex. File1

int count=5; /* count is a global variable */ main() { int a; /* a is a local variable */ Extern_usage(); /* function defined in another file */ } genfunction {/* I do nothing */} /* genfunction can access the global variable x */ File 2 void Extern_usage (void); extern int x; void Extern_usage (void) { x=12; printf ("x is %d\n", x); } /* function prototype */ /* you cannot have extern int x=23; compile error*/

If there are other functions in file 2 they too can modify the variable x; If we have a global variable and a local variable with the same name the local variable gets more preference. Ex. int s = 123; main() { int s =12; printf(%d,s); } prints 12. Where a global variable is declared in one file, but used by functions from another, then the variable is called an external variable in these functions, and must be declared as such. The declaration must be preceded by the word extern. The declaration is required so the compiler can find the type of the variable without having to search through several source files for the declaration. When you declare a variable as extern your program doesn't actually reserve any memory for it, extern means that the variable already exits external to the function or file. If you want to make a variable available to every file in a project you declare it globally in one file, that is, not inside a function, and add an extern declaration of that variable to a header file that is included in all the other files.

8& 4

int x = 4; x = 10; const int x = 2; x = 10;

// a normal variable that can be modified // legal // const var can be initialized, not modified // thereafter // error - cannot modify const variable

const int x; x = 2;

// constant int // illegal - can't modify x

const int* pX; is the same as const int *pX; const int* pX; *pX = 3; pX = &someOtherIntVar; int* const pY; *pY = 4; pY = &someOtherIntVar; const int* const pZ; *pZ = 5; pZ = &someOtherIntVar; // changeable pointer to constant int // illegal - can't use pX to modify an int // legal - pX can point somewhere else // constant pointer to changeable int // legal - can use pY to modify an int // illegal - can't make pY point elsewhere // const pointer to const int // illegal - can't use pZ to modify an int // illegal - can't make pZ point elsewhere

Further reading: http://www.possibility.com/Cpp/const.html

*5. Local Variables are stored in Stack. Register variables are stored in Register. Global & static variables are stored in data segment. The memory created dynamically are stored in Heap and the C program instructions get stored in code segment and the extern variables also stored in data segment. (* Not sure)

9. Data needs to be stored in some form on the computer. The way we store data defines a data structure. Data has to be stored in a way such that operations on the data are easier. If we were to store integers in some form, operations like finding the max and min. searching for an integer have to be fast. There are many ways of storing data arrays, stacks, queues, linked lists... singly linked list, doubly linked lists and circularly linked list, binary trees, hashing etc. Binary search tree is one such way. In this form there are nodes and every node has 2 branches leading to other nodes or ending in leaves. See below. It also has the property that every node to the left of a node has a value lesser than the nodes value and every node to the right of a node has a value greater than the nodes value. There are 3 ways of traversing this binary search tree. a. Inorder gives the ascending order b. Pre order c. Post order Generally data structures are defined using structures in C struct Tree { int data; struct Tree *left; /* self referential pointers can be there */

struct Tree *right; /* you cannot have something like struct Tree node; inside */ }; The function for inorder traversal is given below its a recursive function void Inorder ( struct Tree *node ) { if ( node == NULL ) return; Inorder (node->left); printf(%d, node->data); Inorder (node->right ); }

For the above tree Inorder traversal gives 5 6 8 10 12 15 17 22 Left Node Right Preorder traversal gives 15 10 6 5 8 12 22 17 Node Left Right Postorder traversal gives 5 8 6 12 10 17 22 15 Left Right Node Functions for Pre order and Post order traversals are similar void Preorder ( struct Tree *node ) { if ( node == NULL ) return; printf(%d, node->data); Preorder(node->left); Preorder (node->right); } } void Postorder (struct Tree *node ) { if ( node == NULL ) return; Postorder (node->left); Postorder (node->right ); printf (%d, node->data);

11. We have two strings string1 and string2. int count, i, j ; for (i=0; i<strlen (string1); i++) { count=0; for (j=0; j< strlen(string2); j++) { if(string1[ i+j ] == string2[j] ) count++; else break; } if(count == strlen(string2) ) Printf( matching ); }

12. Bit Fields allow the packing of data in a structure. This is especially useful when memory or data storage is at a premium. Typical examples:

Packing several objects into a machine word. E.g. 1 bit flags can be compacted -Symbol tables in compilers. Reading external file formats -- non-standard file formats could be read in. E.g. 9 bit integers.

C lets us do this in a structure definition by putting: bit length after the variable. i.e. struct packed_struct { unsigned int f1 : 1; unsigned int f2 : 1; unsigned int f3 : 1; unsigned int f4 : 1; unsigned int type : 4; unsigned int funny_int : 9; } pack;

Here the packed_struct contains 6 members: Four 1 bit flags f1 to f3, a 4 bit type and a 9 bit funny_int. C automatically packs the above bit fields as compactly as possible, provided that the maximum length of the field is less than or equal to the integer word length of the computer. If this is not the case then some compilers may allow memory overlap for the

fields whilst other would store the next field in the next word (see comments on bit fields portability below). Access members as usual via: pack.type = 7; NOTE:

Only n lower bits will be assigned to an n bit number. So type cannot take values larger than 15 (4 bits long). Bit fields are always converted to integer type for computation. You are allowed to mix ``normal'' types with bit fields. The unsigned definition is important - ensures that no bits are used as a +/- flag.

Further reading: http://www.cs.cf.ac.uk/Dave/C/node13.html#SECTION001321000000000000000

13. First version: int SetBits(int Num) /* this function returns integer */ { for( int count=0; Num; Num >>= 1) /* keep on right shifting unless */ /* the no. becomes zero */ { /* Num>>=1 is same as Num = Num>>1 */ if (Num & 1) count++; } return count; } Optimized version: int CountSetBits(int Num) { for(int count =0; Num; count++) { Num &= Num -1; } } Rotating a byte is another frequently asked question Further reading: http://www.shettysoft.com/interview/Algorithms_and_coding.doc

14. To reverse a bit do an exor ^ with 1. Other bits must not be affected so put 0s there To set a bit to 1 do an or | op with 1. Other bits must not be affected so put 0s there To set a bit to 0 do an and & op with 0. Put 1s elsewhere not to affect other bits.

216 m + 1 1 = 214 1 = 216 m


n+1

00 1111 1111111111 same as 216 1 right shifted by m-1

1 = 210 1 = 00 0000 1111111111 same as 216 1 right shifted by m+n-1

Subtract these two to get the required sequence - 00 1111 0000000000 a. Do exor operation: if the no. is p p exor 00 1111 0000000000 gives the answer i.e p ^ [( 216 m + 1 1) (216 m n + 1 1)] = p ^ ( 216 m + 1 216 m n + 1 ) b. Do or operation p | [( 216 m + 1 1) (216 m n + 1 1)] = p | ( 216 m + 1 216 m n + 1 ) c. Do and operation with the negated sequence which is 11 0000 1111111111 p & ~[( 216 m + 1 1) (216 m n + 1 1)] = p & ~( 216 m + 1 216 m n + 1 ) ~ tilde is used for bit wise complement Further reading: http://www.fredosaurus.com/notes-cpp/expressions/bitops.html

15. if ( i = 2) assigns a value of 2 to i and returns a value of 1 since the assignment has been successful effectively making the statement if (1) i.e. a true statement always. if ( i == 2) checks if i is equal to 2 and returns a value of 1 if so else it returns 0 making it either if(1) or if(0) ex. int k=23; if (k=12) printf (k is 12 \t); else printf (k is 23); if (k==12) printf (understood this problem); else printf(bulb); Output is: k is 12 understood this problem

http://aelinik.free.fr/c/index.html http://www.datastructures.info/ http://www.cs.sunysb.edu/~skiena/214/lectures/

/* to learn C quickly */

Standard Puzzles
1. You have 100 doors all closed initially. First you open all the doors, then you close all the even doors, then you open all the multiples of 3 then change the position of all the doors which are multiples of 4 and so on. What are all the doors that would remain open at the end? (TIBCO Interview) Ans. Take a door (number). This door will only be affected by all its factors. So if a number has even no. of factors it remains closed else it will be opened at the end. Every no. has factors to the left and right of its square root. For every factor to the left of the root there is a factor to its right. Now the door will remain closed because of these factors. The square root is the only one that affects the door finally. So if the root is an integer i.e. the number is a perfect square the door remains open. So the doors that open are 1, 4, 9, 16, 25, 36, 49, 64, 81 and 100. Others are closed This is true for any number of doors. 2. There are 3 boxes one having apples, one having oranges and the third a mix of apples and oranges. Each box is labeled wrongly with the labels interchanged. How do you find the correct labels for each box with the min no. of takes from any box (INTUIT Interview) Ans: Take 1 fruit from the box having the label mixed. Since it is a wrong label it has to have either apples or oranges. The fruit that you have taken out gives u the correct label for that box and the other 2 follow..... 3. You have to weigh all the weights from 1 kg to 263 kg. What is the min. no. of weights required to do this. Weights to be put on one side only (BECEEM Test) Ans. First you must be able to weigh 1 kg. So have a 1 kg. weight. Then 2 kg, so have a 2 kg. weight. 3kg is already there with 2+1. You need a 4kg. Weight to weigh 4kg. 5, 6, 7 are got by 4+1, 4+2, 4+2+1. So you need 8 kg. You get all the weights till 15 kg. using these. You find a pattern emerging. The weights needed are the powers of 2 until you reach the nearest power of 2. Here 263 is closest to 256 i.e. 28. So all you need is 9 (8+1) weights which are 1,2,4,8,16,32,64,128,256 Binary number approach 4. Four persons have to cross a bridge. The times each needs to cross it are 1 min, 2 min, 5 min and 10 min It is dark and they only have one lamp, we have the following constraints: - The bridge can only be crossed if one has a lamp, because it is too dark. - 2 persons at most are allowed to be on the bridge at the same time. - The speed of a pair is determined by the speed of the slower person. - The lamp can last only 17 mins. (GLOBAL ANALYTICS Interview)

Ans. 1. A & B cross first (total time: 2 minutes) 2. A leaves B on the other side and returns with the flashlight (time: 1 minute; total time: 3 minutes) 3. C & D cross with the flashlight(time: 10 minutes; total time: 13 minutes) 4. B returns with the flash light (time: 2 minutes; total time: 15 minutes) 5. Finally, A & B cross to the other side of the bridge (time: 2 minutes; total time: 17 minutes) 5. There are 10 prisoners about to be executed. The jailor gives them a chance of survival. The jailor puts a hat either black or white on each prisoners head and makes them stand one behind the other. He starts from the end and asks each prisoner to guess the color of the hat on his head. If he guesses the correct color he survives else he is shot dead. What is the strategy the prisoners can follow to maximize the no. of survivors. Each prisoner can only see the hats of the prisoners in front of him. He cannot see the hat on his head. What is the strategy to maximize the no. of survivors? (GA Interview) Ans. One strategy would be that the last person tells, out of the 9 hats which he can see, which are more either black or white and the 9 prisoners say the same color. In this way we can have a min. of 5 survivors. This is not the best strategy. 6. There are 120 marbles. All are of the same weight except one which has a lower weight. You have a balance using which you have to find the odd one out. In how many weighings with the balance can you find the odd one out. The balance is a simple two side balance. Ans: 3^n funda. Divide the marbles into 3 groups of 40 each. Weigh and find the odd set of the 3. This can be done by putting 40 one side and the other 40 on the other side. If they weigh the same the odd one is in the 3rd set else it is on the side which weighs lower. We have eliminated 80 in one weighing. For the next time divide the 40 into 2 sets of 13 leaving the rest aside. In the worst case you have 14 left after the 2nd weighing. For the next time divide the 14 into 2 sets of 5 each leaving the rest aside. In the worst case you have 5 left after the 3rd weighing. You need 2 more weightings to find the odd one out. So in all you need 5 weighings 7. The distance between Delhi and Hyderabad is 1000 miles. Your mission is to move a 10,000 kilograms load of grass from Delhi to Hyderabad using your camel, but you have two problems: 1. The camel won't budge unless you let it to continuously chew grass - it consumes 1 kilogram of grass per mile. 2. The camel's maximum load is 1000 kilograms. Can you manage to get ANY of the grass to Hyd? What is the maximum amount of grass that you can get there? Discussions: http://www.gamedev.net/community/forums/topic.asp?topic_id=346211

8. In puzzle 3 you could place the weights only on one side. Now assuming that you can place weights on both the sides find out the no. of weights needed to weigh all weights from 1 to 256 Ans. Take 1 to weigh 1 kg. To weigh 2 kg use (3 1) i.e. take a 3 kg weight. 4 is there (3 + 1). We need to weigh 5 kg. Have (9 4). i.e. take a 9 kg weight. We can weigh all weights till 13. We need to weigh 14 so have (x 13 = 14) i.e. 27 kg weight. Pattern is powers of 3.

9. In puzzle 6 one of the marbles was lighter. If we have a case where in the marble could be either lighter or heavier how would you go about Ans. http://www.mazes.com/scales/S301-1L.html

10. You were an enthu GOD once. Now you got mad, and decide to have a Party ONE MONTH from today. You have one thousand bottles of wine. Suddenly, you remembered about a give up thing you did, which POISONED one of the wine bottles. Of course you don't remember which one. The poison takes some arbit time less than 1 month to take effect. You cant reschedule the party because it might clash with the other hostel nights. You dont have the money to buy a new set. You cant kill junta whom you invited. You have a LOT of jobless junta at your disposal. The puzzle is to find the smallest number of junta that must drink from the bottles to find the poisoned one? Ans. You can see the original here http://trickofmind.com/2007/11/wine-bottle-puzzle.html Its a bit confusing. When will the poison start affecting. How long does it take for the poison to kill etc. Solution is also there in the link. Heres a different approach. Assuming the poison kills instantaneously and you need 1 drop of poison to kill a person and you start testing the night before the party. We can use the 3^n funda here (puzzle 6). Divide the bottles into 3 sets putting 1 aside. The 3 tasters take a sip from each of all the 333 bottles. The poisoned set is known by waiting for the death. Two are alive add one more to them to make it 3 tasters. Now each one has to taste 111 bottles. Go on and you have the answer.

This is generally how the puzzles in tests and interviews are. Some puzzles could be open ended (though it might have an exact answer, for the time given the puzzle could be considered an open ended one). Take an approach and try answering the puzzle.

Вам также может понравиться