Placement All

Download as pdf or txt
Download as pdf or txt
You are on page 1of 1132

First Job. Dream Job. Freshersworld.

com

Aptitude Questions
1.One of the following is my secret word:AIM DUE MOD OAT TIE.With the list in front of you, if I were to tell you any one of my secret word, then you would be able to tell me the number of vowels in my secret word.Which is my secret word? Ans.TIE

2.In the following figure:A B C D E F G H I Each of the digits 1, 2, 3, 4, 5, 6, 7, 8, and 9 is: a)Represented by a different letter in the figure above. b)Positioned in the figure above so that each of A + B + C,C + D +E,E + F + G, and G + H + I is equal to 13. Which digit does E represent? Ans.E is 4 3.One of Mr. Horton,his wife,their son,and Mr. Horton's mother is a doctor and another is a lawyer. a)If the doctor is younger than the lawyer, then the doctor and the lawyer are not blood relatives. b)If the doctor is a woman, then the doctor and the lawyer are blood relatives. c)If the lawyer is a man, then the doctor is a man. Whose occupation you know? Ans.Mr. Horton:he is the doctor. 4.Here is a picture of two cubes:

a)The two cubes are exactly alike. b)The hidden faces indicated by the dots have the same alphabet on them. Which alphabet-q, r, w, or k is on the faces indicated by the dots? Ans.q

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com

5.In the following figure: A B C G D E F

Each of the seven digits from 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9 is: a)Represented by a different letter in the figure above. b)Positioned in the figure above so that A*B*C,B*G*E, and D*E*F are equal. Which digit does G represent? Ans.G represents the digit 2. 6.Mr. and Mrs. Aye and Mr. and Mrs. Bee competed in a chess tournament.Of the three games played: a)In only the first game werethe two players married to each other. b)The men won two games and the women won one game. c)The Ayes won more games than the Bees. d)Anyone who lost game did not play the subsequent game. Who did not lose a game? Ans.Mrs.Bee did not lose a game. 7.Three piles of chips--pile I consists one chip, pile II consists of chips, and pile III consists of three chips--are to be used in game played by Anita and Brinda.The game requires: a)That each player in turn take only one chip or all chips from just one pile. b)That the player who has to take the last chip loses. c)That Anita now have her turn. From which pile should Anita draw in order to win? Ans.Pile II 8.Of Abdul, Binoy, and Chandini: a)Each member belongs to the Tee family whose members always tell the truth or to the El family whose members always lie. b)Abdul says ''Either I belong or Binoy belongs to a different family from the other two." Whose family do you name of? Ans.Binoy's family--El. 9.In a class composed of x girls and y boys what part of the class is composed of girls A.y/(x + y) B.x/xy C.x/(x + y) D.y/xy Ans.C
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com

10.What is the maximum number of half-pint bottles of cream that can be filled with a 4-gallon can of cream(2 pt.=1 qt. and 4 qt.=1 gal) A.16 B.24 C.30 D.64 Ans.D 11.If the operation,^ is defined by the equation x ^ y = 2x + y,what is the value of a in 2 ^ a = a ^ 3 A.0 B.1 C.-1 D.4 Ans.B 12.A coffee shop blends 2 kinds of coffee,putting in 2 parts of a 33p. a gm. grade to 1 part of a 24p. a gm.If the mixture is changed to 1 part of the 33p. a gm. to 2 parts of the less expensive grade,how much will the shop save in blending 100 gms. A.Rs.90 B.Rs.1.00 C.Rs.3.00 D.Rs.8.00 Ans.C 13.There are 200 questions on a 3 hr examination.Among these questions are 50 mathematics problems.It is suggested that twice as much time be spent on each maths problem as for each other question.How many minutes should be spent on mathematics problems A.36 B.72 C.60 D.100 Ans.B

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com

14.In a group of 15,7 have studied Latin, 8 have studied Greek, and 3 have not studied either.How many of these studied both Latin and Greek A.0 B.3 C.4 D.5 Ans.B 15.If 13 = 13w/(1-w) ,then (2w)2 = A.1/4 B.1/2 C.1 D.2 Ans.C 16. If a and b are positive integers and (a-b)/3.5 = 4/7, then (A) b < a (B) b > a (C) b = a (D) b >= a Ans. A 17. In june a baseball team that played 60 games had won 30% of its game played. After a phenomenal winning streak this team raised its average to 50% .How many games must the team have won in a row to attain this average? A. 12 B. 20 C. 24 D. 30 Ans. C 18. M men agree to purchase a gift for Rs. D. If three men drop out how much more will each have to contribute towards the purchase of the gift/ A. D/(M-3) B. MD/3

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com


C. M/(D-3) D. 3D/(M2-3M) Ans. D 19. A company contracts to paint 3 houses. Mr.Brown can paint a house in 6 days while Mr.Black would take 8 days and Mr.Blue 12 days. After 8 days Mr.Brown goes on vacation and Mr. Black begins to work for a period of 6 days. How many days will it take Mr.Blue to complete the contract? A. 7 B. 8 C. 11 D. 12 Ans.C

20. 2 hours after a freight train leaves Delhi a passenger train leaves the same station travelling in the same direction at an average speed of 16 km/hr. After travelling 4 hrs the passenger train overtakes the freight train. The average speed of the freight train was? A. 30 B. 40 C.58 D. 60 Ans. B

21. If 9x-3y=12 and 3x-5y=7 then 6x-2y = ? A.-5 B. 4 C. 2 D. 8 Ans. D 22. There are 5 red shoes, 4 green shoes. If one draw randomly a shoe what is the probability of getting a red shoe Ans 5c1/ 9c1 23. What is the selling price of a car? If the cost of the car is Rs.60 and a profit of 10% over selling price is earned Ans: Rs 66/Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com

24. 1/3 of girls , 1/2 of boys go to canteen .What factor and total number of classmates go to canteen. Ans: Cannot be determined. 25. The price of a product is reduced by 30% . By what percentage should it be increased to make it 100% Ans: 42.857% 26. There is a square of side 6cm . A circle is inscribed inside the square. Find the ratio of the area of circle to square. Ans. 11/14 27. There are two candles of equal lengths and of different thickness. The thicker one lasts of six hours. The thinner 2 hours less than the thicker one. Ramesh lights the two candles at the same time. When he went to bed he saw the thicker one is twice the length of the thinner one. How long ago did Ramesh light the two candles . Ans: 3 hours. 28. If M/N = 6/5,then 3M+2N = ? 29. If p/q = 5/4 , then 2p+q= ? 30. If PQRST is a parallelogram what it the ratio of triangle PQS & parallelogram PQRST . Ans: 1:2 31. The cost of an item is Rs 12.60. If the profit is 10% over selling price what is the selling price ? Ans: Rs 13.86/32. There are 6 red shoes & 4 green shoes . If two of red shoes are drawn what is the probability of getting red shoes Ans: 6c2/10c2 33. To 15 lts of water containing 20% alcohol, we add 5 lts of pure water. What is % alcohol.

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com


Ans : 15% 34. A worker is paid Rs.20/- for a full days work. He works 1,1/3,2/3,1/8.3/4 days in a week. What is the total amount paid for that worker ? Ans : 57.50 35. If the value of x lies between 0 & 1 which of the following is the largest? (a) x (b) x2 (c) -x (d) 1/x Ans : (d) 36. If the total distance of a journey is 120 km .If one goes by 60 kmph and comes back at 40kmph what is the average speed during the journey? Ans: 48kmph 37. A school has 30% students from Maharashtra .Out of these 20% are Bombey students. Find the total percentage of Bombay? Ans: 6% 38. An equilateral triangle of sides 3 inch each is given. How many equilateral triangles of side 1 inch can be formed from it? Ans: 9 39. If A/B = 3/5,then 15A = ? Ans : 9B 40. Each side of a rectangle is increased by 100% .By what percentage does the area increase? Ans : 300% 41. Perimeter of the back wheel = 9 feet, front wheel = 7 feet on a certain distance, the front wheel gets 10 revolutions more than the back wheel .What is the distance? Ans : 315 feet. 42. Perimeter of front wheel =30, back wheel = 20. If front wheel revolves 240 times. How many revolutions will the back wheel take? Ans: 360 times
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com


43. 20% of a 6 litre solution and 60% of 4 litre solution are mixed. What percentage of the mixture of solution Ans: 36% 44City A's population is 68000, decreasing at a rate of 80 people per year. City B having population 42000 is increasing at a rate of 120 people per year. In how many years both the cities will have same population? Ans: 130 years 45Two cars are 15 kms apart. One is turning at a speed of 50kmph and the other at 40kmph . How much time will it take for the two cars to meet? Ans: 3/2 hours 46A person wants to buy 3 paise and 5 paise stamps costing exactly one rupee. If he buys which of the following number of stamps he won't able to buy 3 paise stamps. Ans: 9 47There are 12 boys and 15 girls, How many different dancing groups can be formed with 2 boys and 3 girls. 48Which of the following fractions is less than 1/3 (a) 22/62 (b) 15/46 (c) 2/3 (d) 1 Ans: (b) 49There are two circles, one circle is inscribed and another circle is circumscribed over a square. What is the ratio of area of inner to outer circle? Ans: 1 : 2 50Three types of tea the a,b,c costs Rs. 95/kg,100/kg and70/kg respectively. How many kgs of each should be blended to produce 100 kg of mixture worth Rs.90/kg, given that the quntities of band c are equal a)70,15,15 b)50,25,25 c)60,20,20 d)40,30,30 Ans. (b)
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com


51. in a class, except 18 all are above 50 years. 15 are below 50 years of age. How many people are there (a) 30 (b) 33 (c) 36 (d) none of these. Ans. (d) 52. If a boat is moving in upstream with velocity of 14 km/hr and goes downstream with a velocity of 40 km/hr, then what is the speed of the stream ? (a) 13 km/hr (b) 26 km/hr (c) 34 km/hr (d) none of these Ans. A 53. Find the value of ( 0.75 * 0.75 * 0.75 - 0.001 ) / ( 0.75 * 0.75 - 0.075 + 0.01) (a) 0.845 (b) 1.908 (c) 2.312 (d) 0.001 Ans. A 54. A can have a piece of work done in 8 days, B can work three times faster than the A, C can work five times faster than A. How many days will they take to do the work together ? (a) 3 days (b) 8/9 days (c) 4 days (d) can't say Ans. B 55. A car travels a certain distance taking 7 hrs in forward journey, during the return journey increased speed 12km/hr takes the times 5 hrs.What is the distance travelled (a) 210 kms (b) 30 kms (c) 20 kms (c) none of these Ans. B
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com


56. Instead of multiplying a number by 7, the number is divided by 7. What is the percentage of error obtained ? 57. Find (7x + 4y ) / (x-2y) if x/2y = 3/2 ? (a) 6 (b) 8 (c) 7 (d) data insufficient Ans. C 58. A man buys 12 lts of liquid which contains 20% of the liquid and the rest is water. He then mixes it with 10 lts of another mixture with 30% of liquid.What is the % of water in the new mixture? 59. If a man buys 1 lt of milk for Rs.12 and mixes it with 20% water and sells it for Rs.15, then what is the percentage of gain? 60. Pipe A can fill a tank in 30 mins and Pipe B can fill it in 28 mins.If 3/4th of the tank is filled by Pipe B alone and both are opened, how much time is required by both the pipes to fill the tank completely ? 61. If on an item a company gives 25% discount, they earn 25% profit. If they now give 10% discount then what is the profit percentage. (a) 40% (b) 55% (c) 35% (d) 30% Ans. D 62. A certain number of men can finish a piece of work in 10 days. If however there were 10 men less it will take 10 days more for the work to be finished. How many men were there originally? (a) 110 men (b) 130 men (c) 100 men (d) none of these Ans. A 63. In simple interest what sum amounts of Rs.1120/- in 4 years and Rs.1200/in 5 years ? (a) Rs. 500 (b) Rs. 600 (c) Rs. 800 (d) Rs. 900
Freshersworld.com Resource Center

10

First Job. Dream Job. Freshersworld.com


Ans. C 64. If a sum of money compound annually amounts of thrice itself in 3 years. In how many years will it become 9 times itself. (a) 6 (b) 8 (c) 10 (d) 12 Ans A 65. Two trains move in the same direction at 50 kmph and 32 kmph respectively. A man in the slower train observes the 15 seconds elapse before the faster train completely passes by him. What is the length of faster train ? (a) 100m (b) 75m (c) 120m (d) 50m Ans B 66. How many mashes are there in 1 squrare meter of wire gauge if each mesh is 8mm long and 5mm wide ? (a) 2500 (b) 25000 (c) 250 (d) 250000 Ans B 67. x% of y is y% of ? (a) x/y (b) 2y (c) x (d) can't be determined Ans. C 68. The price of sugar increases by 20%, by what % should a housewife reduce the consumption of sugar so that expenditure on sugar can be same as before ? (a) 15% (b) 16.66% (c) 12% (d) 9% Ans B
Freshersworld.com Resource Center

11

First Job. Dream Job. Freshersworld.com


69. A man spends half of his salary on household expenses, 1/4th for rent, 1/5th for travel expenses, the man deposits the rest in a bank. If his monthly deposits in the bank amount 50, what is his monthly salary ? (a) Rs.500 (b) Rs.1500 (c) Rs.1000 (d) Rs. 900 Ans C 70. The population of a city increases @ 4% p.a. There is an additional annual increase of 4% of the population due to the influx of job seekers, find the % increase in population after 2 years ? 71. The ratio of the number of boys and girls in a school is 3:2 Out of these 10% the boys and 25% of girls are scholarship holders. % of students who are not scholarship holders.? 72. 15 men take 21 days of 8 hrs. each to do a piece of work. How many days of 6 hrs. each would it take for 21 women if 3 women do as much work as 2 men? (a) 30 (b) 20 (c) 19 (d) 29 Ans. A 73. A cylinder is 6 cms in diameter and 6 cms in height. If spheres of the same size are made from the material obtained, what is the diameter of each sphere? (a) 5 cms (b) 2 cms (c) 3 cms (d) 4 cms Ans C 74. A rectangular plank (2)1/2 meters wide can be placed so that it is on either side of the diagonal of a square shown below.(Figure is not available)What is the area of the plank? Ans :7*(2)1/2 75. The difference b/w the compound interest payble half yearly and the simple interest on a certain sum lent out at 10% p.a for 1 year is Rs 25. What is the sum? (a) Rs. 15000 (b) Rs. 12000 (c) Rs. 10000 (d) none of these Ans C
Freshersworld.com Resource Center

12

First Job. Dream Job. Freshersworld.com


76. What is the smallest number by which 2880 must be divided in order to make it into a perfect square ? (a) 3 (b) 4 (c) 5 (d) 6 Ans. C 77. A father is 30 years older than his son however he will be only thrice as old as the son after 5 years what is father's present age ? (a) 40 yrs (b) 30 yrs (c) 50 yrs (d) none of these Ans. A 78. An article sold at a profit of 20% if both the cost price and selling price would be Rs.20/- the profit would be 10% more. What is the cost price of that article? 29. If an item costs Rs.3 in '99 and Rs.203 in '00.What is the % increase in price? (a) 200/3 % (b) 200/6 % (c) 100% (d) none of these Ans. A 80. 5 men or 8 women do equal amount of work in a day. a job requires 3 men and 5 women to finish the job in 10 days how many woman are required to finish the job in 14 days. a) 10 b) 7 c) 6 d) 12 Ans 7 81. A simple interest amount of rs 5000 for six month is rs 200. what is the anual rate of interest? a) 10% b) 6%

Freshersworld.com Resource Center

13

First Job. Dream Job. Freshersworld.com


c) 8% d) 9% Ans 8% 82. In objective test a correct ans score 4 marks and on a wrong ans 2 marks are ---. a student score 480 marks from 150 question. how many ans were correct? a) 120 b) 130 c) 110 d) 150 Ans130. 83. 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 84. 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 85. 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. 22days 86. How many 1's are there in the binary form of 8*1024 + 3*64 + 3 Ans. 4 87. 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 ?

Freshersworld.com Resource Center

14

First Job. Dream Job. Freshersworld.com


88. 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 89. 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 90. 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) 91. What is the angle between the two hands of a clock when time is 8:30 Ans. 75(approx) 92. A student is ranked 13th from right and 8th from left. How many students are there in totality ? 93. 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 94. A student gets 70% in one subject, 80% in the other. To get an overall of 75% how much should get in third subject. 95. 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

Freshersworld.com Resource Center

15

First Job. Dream Job. Freshersworld.com


96. 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 97. 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) 99. 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) 100. 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)

Freshersworld.com Resource Center

16

Numbers
Introduction: Natural Numbers: All positive integers are natural numbers. Ex 1,2,3,4,8,...... There are infinite natural numbers and number 1 is the least natural number. Based on divisibility there would be two types of natural numbers. They are Prime and composite. Prime Numbers: A natural number larger than unity is a prime number if it does not have other divisors except for itself and unity. Note:-Unity i e,1 is not a prime number. Properties Of Prime Numbers: ->The lowest prime number is 2. ->2 is also the only even prime number. ->The lowest odd prime number is 3. ->The remainder when a prime number p>=5 s divided by 6 is 1 or 5.However, if a number on being divided by 6 gives a remainder 1 or 5 need not be prime. ->The remainder of division of the square of a prime number p>=5 divide by 24 is 1. ->For prime numbers p>3, p-1 is divided by 24. ->If a and b are any 2 odd primes then a-b is composite. Also a+b is composite. ->The remainder of the division of the square of a prime number p>=5 divided by 12 is 1. Process to Check A Number s Prime or not: Take the square root of the number. Round of the square root to the next highest integer call this number as Z. Check for divisibility of the number N by all prime numbers below Z. If there is no numbers below the value of Z which divides N then the number will be prime. Example 239 is prime or 239 lies between 15 or Prime numbers less than 239 is not divisible by is a prime number. not? 16.Hence take the value of Z=16. 16 are 2,3,5,7,11 and 13. any of these. Hence we can conclude that 239

Composite Numbers: The numbers which are not prime are known as composite numbers. Co-Primes: Two numbers a an b are said to be co-primes,if their H.C.F is 1. Example (2,3),(4,5),(7,9),(8,11)..... Place value or Local value of a digit in a Number: place value: Example 689745132 Place value of 2 is (2*1)=2 Place value of 3 is (3*10)=30 and so on. Face value:-It is the value of the digit itself at whatever place it may be. Example 689745132 Face value of 2 is 2. Face value of 3 is 3 and so on.

Top
Tests of Divisibility: Divisibility by 2:-A number is divisible by 2,if its unit's digit is any of 0,2,4,6,8. Example 84932 is divisible by 2,while 65935 is not. Divisibility by 3:-A number is divisible by 3,if the sum of its digits is divisible by 3. Example 1.592482 is divisible by 3,since sum of its digits 5+9+2+4+8+2=30 which is divisible by 3. Example 2.864329 is not divisible by 3,since sum of its digits 8+6+4+3+2+9=32 which is not divisible by 3. Divisibility by 4:-A number is divisible by 4,if the number formed by last two digits is divisible by 4. Example 1.892648 is divisible by 4,since the number formed by the last two digits is 48 divisible by 4. Example 2.But 749282 is not divisible by 4,since the number formed by the last two digits is 82 is not divisible by 4. Divisibility by 5:-A number divisible by 5,if its unit's digit is either 0 or 5. Example 20820,50345 Divisibility by 6:-If the number is divisible by both 2 and 3. example 35256 is clearly divisible by 2

sum of digits =3+5+2+5+21,which is divisible by 3 Thus the given number is divisible by 6. Divisibility by 8:-A number is divisible by 8 if the last 3 digits of the number are divisible by 8. Divisibility by 11:-If the difference of the sum of the digits in the odd places and the sum of the digitsin the even places is zero or divisible by 11. Example 4832718 (8+7+3+4) - (1+2+8)=11 which is divisible by 11. Divisibility by 12:-All numbers divisible by 3 and 4 are divisible by 12. Divisibility by 7,11,13:-The difference of the number of its thousands and the remainder of its division by 1000 is divisible by 7,11,13. BASIC FORMULAE: ->(a+b)=a+b+2ab ->(a-b)=a+b-2ab ->(a+b)-(a-b)=4ab ->(a+b)+(a-b)=2(a+b) ->a-b=(a+b)(a-b) ->(a+b+c)=a+b+c+2(ab+bc+ca) ->a+b=(a+b)(a+b-ab) ->a-b=(a-b)(a+b+ab) ->a+b+c-3abc=(a+b+c)(a+b+c-ab-b c-ca) ->If a+b+c=0 then a+b+c=3a b c DIVISION ALGORITHM If we divide a number by another number ,then Dividend = (Divisor * quotient) + Remainder

Top
MULTIPLICATION BY SHORT CUT METHODS 1.Multiplication by distributive law: a)a*(b+c)=a*b+a*c b)a*(b-c)=a*b-a*c Example a)567958*99999=567958*(100000-1) 567958*100000-567958*1 56795800000-567958 56795232042 b)978*184+978*816=978*(184+816) 978*1000=978000 2.Multiplication of a number by 5n:-Put n zeros to the right of the multiplicand and divide the number so formed by 2n

Example 975436*625=975436*54=9754360000/16=609647500. PROGRESSION: A succession of numbers formed and arranged in a definite order according to certain definite rule is called a progression. 1.Arithmetic Progression:-If each term of a progression differs from its preceding term by a constant. This constant difference is called the common difference of the A.P. The n th term of this A.P is Tn=a(n-1)+d. The sum of n terms of A.P Sn=n/2[2a+(n-1)d]. xImportant Results: a.1+2+3+4+5......................=n(n+1)/2. b.12+22+32+42+52......................=n(n+1)(2n+1)/6. c.13+23+33+43+53......................=n2(n+1)2/4 2.Geometric Progression:-A progression of numbers in which every term bears a constant ratio with ts preceding term. i.e a,a r,a r2,a r3............... In G.P Tn=a r n-1 Sum of n terms Sn=a(1-r n)/1-r Problems 1.Simplify a.8888+888+88+8 b.11992-7823-456 Solution: a.8888 888 88 8 9872 b.11992-7823-456=11992-(7823+456) =11992-8279=3713 2.What could be the maximum value of Q in the following equation? 5PQ+3R7+2Q8=1114 Solution: 5 P Q 3 R 7 2 Q 8 11 1 4 2+P+Q+R=11 Maximum value of Q =11-2=9 (P=0,R=0) 3.Simplify: a.5793405*9999 b.839478*625 Solution: a. 5793405*9999=5793405*(10000-1)

57934050000-5793405=57928256595 b. 839478*625=839478*54=8394780000/16=524673750. 4.Evaluate 313*313+287*287 Solution: a+b=1/2((a+b)+(a-b)) 1/2(313+287) +(313-287)=1/2(600 +26 ) (360000+676)=180338

Top
5.Which of the following is a prime number? a.241 b.337 c.391 Solution: a.241 16>241.Hence take the value of Z=16. Prime numbers less than 16 are 2,3,5,7,11 and 13. 241 is not divisible by any of these. Hence we can conclude that 241 is a prime number. b. 337 19>337.Hence take the value of Z=19. Prime numbers less than 16 are 2,3,5,7,11,13 and 17. 337 is not divisible by any of these. Hence we can conclude that 337 is a prime number. c. 391 20>391.Hence take the value of Z=20. Prime numbers less than 16 are 2,3,5,7,11,13,17 and 19. 391 is divisible by 17. Hence we can conclude that 391 is not a prime number. 6.Find the unit's digit n the product 24 7153 * 34172? Solution: Unit's digit in the given product=Unit's digit in 7 153 * 172 Now 7 4 gives unit digit 1 7 152 gives unit digit 1 7 153 gives 1*7=7.Also 172 gives 1 Hence unit's digit in the product =7*1=7. 7.Find the total number of prime factors in 411 *7 5 *112 ? Solution: 411 7 5 112= (2*2) 11 *7 5 *112 = 222 *7 5 *112 Total number of prime factors=22+5+2=29 8.Which of the following numbers s divisible by 3? a.541326 b.5967013 Solution: a. Sum of digits in 541326=5+4+1+3+2+6=21 divisible by 3. b. Sum of digits in 5967013=5+9+6+7+0+1+3=31 not divisible by 3. 9.What least value must be assigned to * so that th number 197*5462 is divisible by 9? Solution: Let the missing digit be x Sum of digits = (1+9+7+x+5+4+6+2)=34+x For 34+x to be divisible by 9 , x must be replaced by 2

The digit in place of x must be 2. 10.What least number must be added to 3000 to obtain a number exactly divisible by 19? Solution:On dividing 3000 by 19 we get 17 as remainder Therefore number to be added = 19-17=2. 11.Find the smallest number of 6 digits which is exactly divisible by 111? Solution:Smallest number of 6 digits is 100000 On dividing 10000 by 111 we get 100 as remainder Number to be added =111-100=11. Hence,required number =10011. 12.On dividing 15968 by a certain number the quotient is 89 and the remainder is 37.Find the divisor? Solution:Divisor = (Dividend-Remainder)/Quotient =(15968-37) / 89 =179. 13.A number when divided by 342 gives a remainder 47.When the same number is divided by 19 what would be the remainder? Solution:Number=342 K + 47 = 19 * 18 K + 19 * 2 + 9=19 ( 18K + 2) + 9. The given number when divided by 19 gives 18 K + 2 as quotient and 9 as remainder.

Top
14.A number being successively divided by 3,5,8 leaves remainders 1,4,7 respectively. Find the respective remainders if the order of divisors are reversed? Solution:Let the number be x. 3 x 5 y - 1 8 z y=5z+4 = 5*15+4 = 79 x=3y+1 = 3*79+1=238 Now 8 238 5 29 - 6 3 5 - 4 1 - 2 Respective remainders are 6,4,2. - 4 1 - 7 z=8*1+7=15

15.Find the remainder when 231 is divided by 5? Solution:210 =1024.unit digit of 210 * 210 * 210 is 4 as 4*4*4 gives unit digit 4 unit digit of 231 is 8. Now 8 when divided by 5 gives 3 as remainder. 231 when divided by 5 gives 3 as remainder.

16.How many numbers between 11 and 90 are divisible by 7? Solution:The required numbers are 14,21,28,...........,84 This is an A.P with a=14,d=7. Let it contain n terms then T =84=a+(n-1)d =14+(n-1)7 =7+7n 7n=77 =>n=11. 17.Find the sum of all odd numbers up to 100? Solution:The given numbers are 1,3,5.........99. This is an A.P with a=1,d=2. Let it contain n terms 1+(n-1)2=99 =>n=50 Then required sum =n/2(first term +last term) =50/2(1+99)=2500. 18.How many terms are there in 2,4,6,8..........,1024? Solution:Clearly 2,4,6........1024 form a G.P with a=2,r=2 Let the number of terms be n then 2*2 n-1=1024 2n-1 =512=29 n-1=9 n=10. 19.2+22+23+24+25..........+28=? Solution:Given series is a G.P with a=2,r=2 and n=8. Sum Sn=a(1-r n)/1-r=Sn=2(1-28)/1-2. =2*255=510. 20.A positive number which when added to 1000 gives a sum , which is greater than when it is multiplied by 1000.The positive integer is? a.1 b.3 c.5 d.7 Solution:1000+N>1000N clearly N=1. 21.The sum of all possible two digit numbers formed from three different one digit natural numbers when divided by the sum of the original three numbers is equal to? a.18 b.22 c.36 d. none Solution:Let the one digit numbers x,y,z Sum of all possible two digit numbers= =(10x+y)+(10x+z)+(10y+x)+(10y+z)+(10z+x)+(10z+y) = 22(x+y+z) Therefore sum of all possible two digit numbers when divided by sum of one digit numbers gives 22. 22.The sum of three prime numbers is 100.If one of them exceeds another by 36 then one of the numbers is?

a.7

b.29

c.41

d67.

Solution:x+(x+36)+y=100 2x+y=64 Therefore y must be even prime which is 2 2x+2=64=>x=31. Third prime number =x+36=31+36=67. 23.A number when divided by the sum of 555 and 445 gives two times their difference as quotient and 30 as remainder .The number is? a.1220 b.1250 c.22030 d.220030. Solution:Number=(555+445)*(555-445)*2+30 =(555+445)*2*110+30 =220000+30=220030. 24.The difference between two numbers s 1365.When the larger number is divided by the smaller one the quotient is 6 and the remainder is 15. The smaller number is? a.240 b.270 c.295 d.360 Solution:Let the smaller number be x, then larger number =1365+x Therefore 1365+x=6x+15 5x=1350 => x=270 Required number is 270. 25.In doing a division of a question with zero remainder,a candidate took 12 as divisor instead of 21.The quotient obtained by him was 35. The correct quotient is? a.0 b.12 c.13 d.20 Solution:Dividend=12*35=420. Now dividend =420 and divisor =21. Therefore correct quotient =420/21=20.

H.C.F and L.C.M


Facts And Formulae: Highest Common Factor:(H.C.F) or Greatest Common Meaure(G.C.M) : The H.C.F of two or more than two numbers is the greatest number that divides each of them exactly. There are two methods : i.Factorization method: Express each one of the given numbers as the product of prime factors. The product of least powers of common prime factors gives HCF. Example : Solution: Find HCF of 26 * 32*5*74 , 22 *35*52 * 76 , 2*52 *72 The prime numbers given common numbers are 2,5,7

Therefore HCF

is

22 * 5 *72 .

ii.Division Method : Divide the larger number by smaller one. Now divide the divisor by remainder. Repeat the process of dividing preceding number last obtained till zero is obtained as number. The last divisor is HCF. Example: Solution: 1134) 1215(1 1134 ---------81)1134(14 81 ----------324 324 ----------0 ----------HCF of this two numbers is 81. 81)513(6 486 -------27)81(3 81 ----0 --HCF of 81 and 513 is 27. Find HCF of 513, 1134, 1215

Least common multiple[LCM] : The least number which is divisible by each one of given numbers is LCM. There are two methods for this: i.Factorization method : Resolve each one into product of prime factors. Then LCM is product of highest powers of all factors. ii.Common Problems: 1.The HCF of 2 numbers is 77.find other. Sol: Other number = 11 * is 11 and LCM is 693/77=99. divisible by 12,15,18,27 693.If one of numbers division method.

Top

2.Find largest number of 4 digits Sol: The largest number is 9999. LCM of 12,15,18,27 is 540.

on dividing 9999 by 540 we get 279 as remainder. Therefore number =9999 279 =9720. 3.Find least number which when divided by 20,25,35,40 leaves remainders 14,19,29,34. Sol: 2014=6 25-19=6 35-29=6 40-34=6 Therefore number =LCM of (20,25,35,40) - 6=1394 can be expressed as prime as : 2 252 2 126 3 63 3 21 7 prime factor is 2 *2 * 3 * 3 *7 5.1095/1168 when expressed in simple form is 1095)1168(1 1095 -----73)1095(15 73 --------365 365 --------0 ---------So, HCF is 73 Therefore 1095/1168 = 1095/73/1168/73= 15/16 6.GCD of 1.08,0.36,0.9 is Sol: HCF of 108,36,90 72 ---18)36(2 36 ---0 ---HCF is 18. HCF of 18 and 108 is 18 18)108(6 108 ------0 -------Therefore HCF =0.18 36)90(2 4.252

7.Three numbers are in ratio 1:2:3 and HCF is 12.Find numbers. Sol: Let the numbers be x. Three numbers are x,2x,3x Therefore HCF is 2x)3x(1 2x ----x)2x(2 2x -------0 ------------HCF is x so, x is 12 Therefore numbers are 12,24,36.

Top
8.The Sol: sum of two numbers is 216 and HCF is 27. Let numbers are 27a + 27 b =216 a + b =216/27=8 Co-primes of 8 are (1,7) and (3,5) numbers=(27 * 1 ), (27 * 7) =27,89 9.LCM of two numbers is of numbers is Sol: Let the number be x. Numbers are 2x,3x LCM of 2x,3x is 6x Therefore 6x=48 x=8. Numbers are 16 and 24 Sum=16 +24=40. 10.HCF and LCM of two numbers are 84 and 21.If ratio of two numbers is 1:4.Then largest of two numbers is Sol: Let the numbers be x,4x Then x * 4x = 84 * 21 x2 =84 * 21 /4 x = 21 Largest number is 4 * 21. 11.HCF of two numbers is 23,and other factors of LCM Largest number is Sol: 23 * 14 is Largest number. 12.The maximum number of students among them 1001 pens and 910 pencils can be distributed in such a way that each student gets are 13,14. 48..The numbers are in ratio 2:3. The sum

same number of pens and pencils is ? Sol: HCF of 1001 and 910 910)1001(1 910 -----------91)910(10 910 -------0 --------Therefore HCF=91 13.The least number which should be added to 2497 so that sum is divisible by 5,6,4,3 ? Sol: LCM of 5,6,4,3 is 60. On dividing 2497 by 60 we get 37 as remainder. Therefore number to added is 60 37 =23. Answer is 23. 14.The least number which is a perfect square and is each of numbers 16,20,24 is ? Sol: LCM of 16,20,24 is 240. 2 * 2*2*2*3*5=240 To make it a perfect square multiply by 3 * 5 Therefore 240 * 3 * 5=3600 Answer is 3600. divisible by

Decimal Fractions
1.Decimal fractions: Fractionin which denominations are powers of 10 are decimal fractions. Example:1 /10 = 0.1, 1 / 100 = 0.01 2.Convertion of Decimal into fraction:Example: 0.25 = 25/100 = 1/4 3.i) If numerator and denominator contain same number of decimal places, then we remove decimal sign. Thus, 1.84/2.99 =184/299 Problems 1.0.75 =75/100 =3/4 2.Find porducts= 6.3204*100

= 632.04 3.2.61*1.3=261*13=3393 some of decimal places 2 +1 =3 sol: 3.393 4.If 1/3.718 =0.2689,then find value of 1/0.0003718 ? Sol: 10000/3.718 =10000*1/3.718 =10000*0.2689 = 2689 5.Find fractions : i) 0.37 = 37/99 ii)3.142857 =3+0.142857 =3 +142857/999999 = 3 142857/ 999999 iii) 0.17=17-1/90 =16/90=8/45 iv)0.1254 =1254 -12/9900 =1242/9900=69/550 6.Fraction 101 27/100000 Sol: 101+27/100000 =101+0.00027 =101.00027 7.If 47.2506 =4A + 7/B +2C + 5/D + 6E then 40+7+0.2+0.05+0.0006 Sol: compairing terms 4A= 40 => A=10 7/B = 7 => B=1 2C= 0.2=> C=0.1 5/D= 0.05=>D=5/0.05 =>5*100/5 =100 6E= 0.0006=> E= 0.0001 5A + 3B+6C+ D+ 3E = 5*10+ 3*1+ 6*0.1 + 100+ 3*0.0001 =50+3+0.6+100+0.0003 =153.6003

Top
8.4.036 divided by 0.04 Sol: 4.036/0.04 =4036/4 =100.9 9.[ 0.05/0.25 + 0.25/ 0.05]3 Sol: =>[5/25 + 25/5] = [1/5+ 5]3 =26/53 =5.23 = 140.603 10.The least among the following :a. 0.2 b.1/0.2 c. 0.2 d. 0.22 sol:10/2 =5 0.2222 0.04 0.04 < 0.2 < 0.22 --------<5 Since 0.04 is least (0.2)2 is least.

11.Let F= 0.84181 Sol: when F is written as a fraction in lowest terms, denominator exceeds numerator by 84181 -841 /99000 = 83340/99000 =463/550 Required distence = (550 463) = 87 12.2 .75 + 3.78 Sol: [-2+0.75]+[-3+0.78] =-5+[0.75+0.78] = -5+1.53 =-5+1+0.53 = -4+0.53 = 4.53 13.the sum of first 20 terms of series is 1/5*6 +1/6*7+1/7*8----Sol: [1/5 -1/6]+[1/6-1/7]+[1/7-1/8]+-----------------------= [1/5-1/25] =4/25=0.16 14.13 +23+ ------------+93 =2025 Sol: value of (0.11) 3+ (0.22) 3+---------(0.99)3 => (0.11) [1+2+--------+9] =0.001331*2025 =2.695275 15.(0.96)3 (0.1)3/ (0.96)2 +0.096 +(0.1)2 Sol: formula => a3 -b3/a2 +ab +b2 =a -b (0.96-0.1)=0.86 16.3.6*0.48*2.50 / 0.12*0.09*0.5 Sol: 36*48*250/12*9*5=800 17.find x/y = 0.04/1.5 = 4/150 =2/75 find y-x/y+x (1- x/y) / (1+ x/y) 1 - 2/75 /1 +2/75 =73/77 18.0.3467+0.1333 Sol: 3467 = = = -34/9900 + 1333-13/9900 3433 +1320/9900 4753/9900 4801 -48/9900 =0.4301

Simplifications

Introduction: 'BODMAS' rule: This rule depicts the correct sequence in which the operations are to be executed, so as to find out the value of a given expression. Here B stands for Bracket, O for Of, D for Division, M for Multiplication, A for Addition and S for Subtraction. First of all the brackets must be removed, strictly in the order () , {} , []. After removing the brackets, we want use the following operations: 1.Of 2. Division 3. Multiplication 4. Addition 5. Subtraction Modulus of a real number: Modulus of a real number is a defined as |a| = a, if a>0 or -a, if a < 0; Problems: 1.(5004 /139) 6= ? Sol: Expression = 5004/ 139 6 = 36 6 = 30; 2.What mathematical operations should come at the place of ? in the equation : (2 ? 6 12 / 4 + 2 = 11) ? Sol: 2 ? 6 = 11 + 12 / 4 2 = 11 + 3 2 = 12 2 * 6 = 12 3.( 8 / 88) * 8888088 = ? Sol : (1/11) * 8888088 = 808008 4.How many 1/8's are there in 371/2 ? Sol: (371/2) /(1/8)= (75/2) /(1/8) = 300 5.Find the values of 1/2*3 +1/3*4 +1/4*5+ .................+1/9*10 ? Sol: 1/2*3 +1/3*4+1/4*5+ ..................+1/9*10 = [ -1/3] +[ 1/3 ] + [- 1/5] +...............+[1/9-1/10] = [ 1/10] = 4/15 = 2/5

Top
6.The value of 999 of 995/999* 999 is: Sol: [1000- 4/1000]*999 = 999000-4

= 998996 7.Along a yard 225m long, 26 trees are planted at equal distance, one tree being at each end of the yard. what is the distance between two consecutive trees ? Sol: 26 trees have 25 gaps between them. Hence , required distance = 225/ 25 m= 9m 8.In a garden , there are 10 rows and 12 columns of mango trees. the distance between the two trees is 2 m and a distance of one meter is left from all sides of the boundary of the length of the garden is : Sol: Each row contains 12 plants. leaving 2 corner plants, 10 plants in between have 10 * 2 meters and 1 meter on each side is left. length = (20 + 2) m = 22m 9.Eight people are planning to share equally the cost of a rental car, if one person with draws from the arrangement and the others share equally the entire cost of the car, then the share of each of the remaining persons increased by? Sol: Original share of one person = 1/8 new share of one person = 1/7 increase = 1/7 1/8 = 1/56 required fractions = (1/56)/(1/8) = 1/7 10.A piece of cloth cost Rs 35. if the length of the piece would have been 4m longer and each meter cost Re 1 less , the cost would have remained unchanged. how long is the piece? Sol: Left the length of the piece be x m. then, cost of 1m of piece = Rs [35 / x] 35/ x 35 /x+4 = 1 x + 4 x = x(x+ 4)/35 x2 + 4x 140 = 0 x= 10 11.A man divides Rs 8600 among 5sons, 4 daughters and 2 nephews. If each daughter receives four times as much as each nephew, and each son receives five as much as each nephew. how much does each daughter receive ? Sol: Let the share of each nephew be Rs x. then, share of each daughter Rs 4x. share of each son = 5x Rs so, 5 *5x+ 4 * 4x + 2x =8600 2x + 16x + 25x= 8600 43x = 8600 x = 200 share of each daughter = 4 * 200 = Rs 800

12.A man spends 2/5 of his salary on house rent, 3/10 of his salary on food, and 1/8 of his salary on conveyance. if he has Rs 1400 left with him, find his expenditure on food and conveyance? Sol: Part of the salary left = 1-[2/5 +3/10+1/9] = 1- 33/40 =7/40 Let the monthly salary be rs x then, 7/40 of x = 1400 x= [1400*40]/7 x= 8000 Expenditure on food = 3/10*8000 =Rs 2400 Expenditure on conveyance= 1/8*8000 =Rs 1000

Square and Cube Roots


Formula: The Product of two same numbers in easiest way as follow. Example:let us calculate the product of 96*96 Solution: Here every number must be compare with the 100. See here the given number 96 which is 4 difference with the 100. so subtract 4 from the 96 we get 92 ,then the square of the number 4 it is 16 place the 16 beside the 92 we get answer as 9216. 9 6 4 -------------9 2 -------------4*4=16

9 2 1 6

therefore square of the two numbers 96*96=9216. Example: Calculate product for 98*98 Solution: Here the number 98 is having 2 difference when compare to 100 subtract 2 from the number then we get 96 square the number 2 it is 4 now place beside the 96 as 9604 9 8 2 ------------9 6 ------------2*2=4 9 6 0 4. so, we get the product of 98*98=9604.

Example: Calculate product for 88*88 Solution: Here the number 88 is having 12 difference when compare to 100 subtract 12 from the 88 then we get 76 the square of the number 12 is 144 (which is three digit number but should place only two digit beside the 76) therefore in such case add one to 6 then it becomes 77 now place 44 beside the number 77 we will get 7744. 88 -12 -----------76 ----------12*12=144 76 + 144 -------------------7744 -------------------Example: Find the product of the numbers 46 *46? Solution:consider the number 50=100/2. Now again go comparision with the number which gets when division with 100.here consider the number 50 which is nearer to the number given. 46 when compared with the number 50 we get the difference of 4. Now subtract the number 4 from the 46, we get 42. As 50 got when 100 get divided by 2. so, divided the number by 2 after subtraction. 42/2=21 now square the the number 4 i.e, 4*4=16 just place the number 16 beside the number 21 we get 2116. 4 6 4 ---------------4 2 as 50 = 100/2 42/2=21 now place 4*4=16 beside 21 2 1 1 6 Example: Find the product of the numbers 37*37 Solution: consider the number 50=100/2 now again go comparision with the number which division with 100. here consider the number 50 which is nearer to 37 when compared with the number 50 we get the now subtract the number 13 from the 37, we get as 50 got when 100 get divided by 2. so, divided the number by 2 after subtraction. 24/2=12 now square the the number 13 i.e, 13*13=169 just place the number 169 beside the number 21 now as 169 is three digit number then add 1 to 1t as 13 then place 69 beside the 13 we get 1369. 3 7

gets when the number given. difference of 13. 24.

2 we get

1 3 ----------------2 4 24/2=12 square 13* 13=169

as

50

100/2

1 2 + 1 6 9 ----------------------1 3 6 9 -------------------------

Top
Example: Find the product of 106*106 Solution: now compare it with 100 , The given number is more then 100 then add the extra number to the given number. That is 106+6=112 then square the number 6 that is 6*6=36 just place beside the number 36 beside the 112,then we get 11236. 1 0 6 + 6 --------------------1 1 2 -------------------now 6* 6=36 place this beside the number 112, we get 1 1 2 3 6 Square root: If x2=y ,we say that the square root of y is x and we write ,y=x. Cube root: The cube root of a given number x is the number whose cube is x. we denote the cube root of x by x1/3 . Examples: 1.Evaluate 60841/2 by factorization method. Solution: Express the given number as the product of prime factors. Now, take the product of these prime factors choosing one out of every pair of the same primes. This product gives the square root of the given number. Thus resolving 6084 in the prime factors ,we get 6084 2 6024 2 3042 3 1521 3 507 13 169 13 6084=21/2 *31/2 *131/2 60841/2=2*3*13=78. Answer is 78. 2.what will come in place of question mark in each of the following questions?

i)(32.4/?)1/2 = 2 ii)86.491/2 + (5+?1/2)2 =12.3 Solution: 1) (32.4/x)1/2=2 Squaring on both sides we get 32.4/x=4 =>4x=32.4 =>x=8.1 Answer is 8.1 ii)86.491/2 + (5+x2)=12.3 solutin:86.491/2 + (5+x1/2 )=12.3 9.3+ (5+x1/2 )=12.3 => (5+x1/2 ) =12.3-9.3 => (5+x1/2 )=3 Squaring on both sides we get (5+x1/2 )=9 x1/2 =9-5 x1/2 =4 x=2. Answer is 2. 3. 0.00004761 equals: Solution: (4761/108) 4761/ 108 . 69/10000 0.0069. Answer is 0.0069 4.If 18225=135,then the value of 182.25 + 1.8225 + 0.018225 + 0.00018225. Solution: (18225/100) +(18225/10000) + (18225/1000000) +(18225/100000000) =(18225)/10 + (18225)1/2/100 + (18225)/1000 + (18225)/10000 =135/10 + 135/100 + 135/1000 + 135/10000 =13.5+1.35+0.135+0.0135=14.9985. Answer is 14.9985. 5.what should come in place of both the question marks in the equation (?/ 1281/2= (162)1/2/?) ? Solution: x/ 1281/2= (162)1/2/x =>x1/2= (128*162)1/2 => x1/2= (64*2*18*9)1/2 =>x2= (82*62*32) =>x2=8*6*3 =>x2=144 =>x=12. 6.If 0.13 / p1/2=13 then p equals

Solution: 0.13/p2=13 =>p2=0.13/13 =1/100 p2=(1/100) =>p=1/10 therefore p=0.1 Answer is 0.1

Top
7.If 13691/2+(0.0615+x)1/2=37.25 then x is equals to: Solution 37+(0.0615+x)1/2=37.25(since 37*37=1369) =>(0.0615+x)1/2=0.25 Squaring on both sides (0.0615+x)=0.0625 x=0.001 x=10-3. Answer is 10-3. 8.If (x-1)(y+2)=7 x& y being positive whole numbers then values of x& y are? Solution: (x-1)(y+2)=7 Squaring on both sides we get (x-1)(y+2)=72 x-1=7 and y+2=7 therefore x=8 , y=5. Answer x=8 ,y=5. 9.If 3*51/2+1251/2=17.88.then what will be the value of 801/2+6*51/2? Solution: 3*51/2+1251/2=17.88 3*51/2+(25*5)1/2=17.88 3*51/2+5*51/2=17.88 8*51/2=17.88 51/2=2.235 therefore 801/2+6 51/2=(16*51/2)+6*1/25 =4 51/2+6 51/2 =10*2.235 =22.35 Answer is 22.35 10.If 3a=4b=6c and a+b+c=27*29 then Find c value is: Solution: 4b=6c =>b=3/2*c 3a=4b =>a=4/3b =>a=4/3(3/2c)=2c therefore a+b+c=27*291/2 2c+3/2c+c=27*291/2 =>4c+3c+2c/2=27*291/2 =>9/2c=27*291/2 c=27*291/2*2/9 c=6*291/2

11.If 2*3=131/2 and 3*4=5 then value of 5*12 is Solution: Here a*b=(a2+b2)1/2 therefore 5*12=(52+122)1/2 =(25+144)1/2 =1691/2 =13 Answer is 13. 12.The smallest number added to 680621 to make the sum a perfect square is Solution: Find the square root number which is nearest to this number 8 680621 824 64 162 406 324 1644 8221 6576 1645 therefore 824 is the number ,to get the nearest square root number take (825*825)-680621 therefore 680625-680621=4 hence 4 is the number added to 680621 to make it perfect square. 13.The greatest four digit perfect square number is Solution: The greatest four digit number is 9999. now find the square root of 9999. 9 9999 99 81 189 1819 1701 198 therefore 9999-198=9801 which is required number. Answer is 9801. 14.A man plants 15376 apples trees in his garden and arranges them so, that there are as many rows as there are apples trees in each row .The number of rows is. Solution: Here find the square root of 15376. 1 15376 124 1 22 53 44 244 976 976 0 therefore the number of rows are 124. 15.A group of students decided to collect as many paise from each member of the group as is the number of members. If the total collection amounts to Rs 59.29.The number of members

in the group is: Solution: Here convert Money into paise. 59.29*100=5929 paise. To know the number of member ,calculate the square root of 5929. 7 5929 77 49 147 1029 1029 0 Therefore number of members are 77. 16.A general wishes to draw up his 36581 soldiers in the form of a solid square ,after arranging them ,he found that some of them are left over .How many are left? Solution: Here he asked about the left man ,So find the square root of given number the remainder will be the left man 1 36581 191 1 29 265 261 381 481 381 100(since remaining) Therefore the left men are 100. 17.By what least number 4320 be multiplied to obtain number which is a perfect cube? Solution: find l.c.m for 4320. 2 4320 2 2160 2 1080 2 540 2 270 3 135 3 45 3 15 5 4320=25 * 33 * 5 =23 * 33 * 22 *5 so make it a perfect cube ,it should be multiplied by 2*5*5=50 Answer is 50. 18.3(4*12/125)1/2=? Solution: 3(512/125)1/2 3(8*8*8)1/2/(5*5*5) 3(83)1/2/(53) ((83)/(53))1/3 =>8/5 or 1 3/5.

Averages

Formula: 1.Average=Sum of quantities/Number of quantities. 2.Suppose a man covers a certain distance at x kmph and an equal distance at y kmph ,then the average speed during the whole journey is (2xy/x+y) kmph. Examples: 1.Find the average of all these numbers.142,147,153,165,157. Solution: 142 147 153 165 157 Here consider the least number i.e, 142 comparing with others, 142 147 153 165 157 +5 +11 +23 +15 Now add 5+11+23+15 = 52/5 = 10.8 Now add 10.8 to 142 we get 152.8 (Average of all these numbers). Answer is 152.8 2.Find the average of all these numbers.4,10,16,22,28 Solution: 4,10,16,22,28 As the difference of number is 6 Then the average of these numbers is central one i.e, 16. Answer is 16. 3.Find the average of all these numbers.4,10,16,22,28,34. Solution: Here also difference is 6. Then middle numbers 16,22 take average of these two numbers 16+22/2=19 Therefore the average of these numbers is 19. Answer is 19. 4.The average marks of a marks of a student in 4 Examination is 40.If he got 80 marks in 5th Exam then what is his new average. Solution: 4*40+80=240 Then average means 240/5=48. Answer is 48. 5.In a group the average income of 6 men is 500 and that of 5 women is 280, then what is average income of the group. Solution: 6*500+5*280=4400 then average is 4400/11=400. Another Method: here consider for 6 men 6 men each 500. so 5th women is 280.

then 500-280=220. then 220*6/11=120. therefore 120+280=400. Answer is 400. 6.The average weight of a class of 30 students is 40 kgs if the teacher weight is included then average increases by 2 kgs then find the weight of the teacher? Solution: 30 students average weight is 40 kgs. So,when teacher weight is added it increases by 2 kgs so total 31 persons ,therefore 31*2=62. Now add the average weight of all student to it we get teachers weight i.e, 62+40=102 kgs. Answer is 102 kgs. 7.The average age of Mr and Mrs Sharma 4 years ago is 28 years . If the present average age of Mr and Mrs Sharma and their son is 22 years. What is the age of their son. Solution: 4 years ago their average age is 28 years. So their present average age is 32 years. 32 years for Mr and Mrs Sharma then 32*2=64 years. Then present age including their son is 22 years. So 22*3 =66 years. Therefore son age will be 66-64 = 2 years. Answer is 2 years. 8.The average price of 10 books is increased by 17 Rupees when one of them whose value is Rs.400 is replaced by a new book. What is the price of new book? Solution: 10 books Average increases by 17 Rupees so 10*17= 170. so the new book cost is more and by adding its cost average increase,therefore the cost of new book is 400+170=570Rs. Answer is 570 Rs. 9.The average marks of girls in a class is 62.5. The average marks of 4 girls among them is 60.The average marks of remaining girls is 63,then what is the number of girls in the class? Solution: Total number of girls be x+4. Average marks of 4 girls is 60. therefore 62.5-60=2.5 then 4*2.5 =10. the average of remaining girls is 63 here 0.5 difference therefore 0.5*x=10(since we got from 4 girls) (this is taken becoz both should be equal) x=10/0.5 x=20. This clear says that remaining are 20 girls therefore total is x+4=20+4=24 girls

Answer is 24 girls.

Top
10.Find the average of first 50 natural numbers. Solution: Sum of the Natural Numbers is n(n+1)/2 therefore for 50 Natural numbers 50*51/2=775. the average is 775/50=15.5 Answer is 15.5 . 11.The average of the first nine prime number is? Solution: Prime numbers are 2,3,5,7,11,13,17,19,23 therefore 2+3+5+7+11+13+17+19+23=100 then the average 100/9= 11 1/9. Answer is 11 1/9. 12.The average of 2,7,6 and x is 5 and the average of and the average of 18,1,6,x and y is 10 .what is the value of y? Solution: 2+7+6+x/4=5 =>15+x=20 =>x=5. 18+1+6+x+y/5=10 =>25+5+y=50 =>y=20. 13.The average of a non-zero number and its square is 5 times the number.The number is Solution: The number be x then x+x2/2=5x =>x2-9x=0 =>x(x-9)=0 therefore x=0 or x=9. The number is 9. 14.Nine persons went to a hotel for taking their meals . Eight of them spent Rs.12 each on their meals and the ninth spent Rs.8 then the average expenditure of all the nine. What was the total money spent by them? Solution: The average expenditure be x. then 8*12+(x+8)=9x =>96+x+8=9x. =>8x=104 =>x=13 Total money spent =9x=>9*13=117 Answer is Rs.117 15.The average weight of A.B.C is 45 Kgs.If the average weight of A and B be 40 Kgs and that of Band C be 43 Kgs. Find the weight of B?

Solution: The weight of A,B,Care 45*3=135 Kgs. The weight of A,B are 40*2=80 Kgs. The weight of B,C are 43*2=86 Kgs. To get the Weight of B. (A+B)+(B+C)-(A+B+C)=80+86-135 B=31 kgs. Answer is 31 Kgs. 16.The sum of three consecutive odd number is 48 more than the average of these number .What is the first of these numbers? Solution: let the three consecutive odd numbers are x, x+2, x+4. By adding them we get x+x+2+x+4=3x+6. Then 3x+6-(3x+6)/3=38(given) =>2(3x+6)=38*3. =>6x+12=114 =>6x=102 =>x=17. Answer is 17. 17.A family consists of grandparents,parents and three grandchildren. The average age of the grandparents is 67 years,that of parents is 35 years and that of the grand children is 6 years . What is the average age of the family? Solution: grandparents age is 67*2=134 parents age is 35*2=70 grandchildren age is 6*3=18 therefore age of family is 134+70+18=222 average is 222/7=31 5/7 years. Answer is 31 5/7 years.

Top
18.A library has an average of 510 visitors on Sundays and 240 on other days .The average number of visitors per day in a month 30 days beginning with a Sunday is? Solution: Here specified that month starts with Sunday so, in a month there are 5 Sundays. Therefore remaining days will be 25 days. 510*5+240*25=2550+6000 =8550 visitors. The average visitors are 8550/30=285. Answer is 285. 19.The average age of a class of 39 students is 15 years . If the age of the teacher be included ,then average increases by 3 months. Find the age of the teacher. Solution: Total age for 39 persons is 39*15=585 years. Now 40 persons is 40* 61/4=610 years (since 15 years 3 months=15 3/12=61/4) Age of the teacher =610-585 years

=>25 years. Answer is 25 years. 20.The average weight of a 10 oarsmen in a boat is increases by 1.8 Kgs .When one of the crew ,who weighs 53 Kgs is replaced by new man. Find the weight of the new man. Solution: Weight of 10 oars men is increases by 1.8 Kgs so, 10*1.8=18 Kgs therefore 53+18=71 Kgs will be the weight of the man. Answer is 71 Kgs. 21.A bats man makes a score of 87 runs in the 17th inning and thus increases his average by 3. Find the average after 17th inning. Solution: Average after 17 th inning =x then for 16th inning is x-3. Therefore 16(x-3)+87 =17x =>x=87-48 =>x=39. Answer is 39. 22.The average age of a class is 15.8 years .The average age of boys in the class is 16.4 years while that of the girls is 15.4 years .What is the ratio of boys to girls in the class. Solution: Ratio be k:1 then k*16.4 + 1*15.4 = (k+1)*15.8 =>(16.4-15.8)k=15.8-15.4 =>k=0.4/0.6 =>k=2/3 therefore 2/3:1=>2:3 Answer is 2:3 23.In a cricket eleven ,the average of eleven players is 28 years .Out of these ,the average ages of three groups of players each are 25 years,28 years, and 30 years respectively. If in these groups ,the captain and the youngest player are not included and the captain is eleven years older than the youngest players , what is the age of the captain? Solution: let the age of youngest player be x then ,age of the captain =(x+11) therefore 3*25 + 3*28 + 3*30 + x + x+11=11*28 =>75+84+90+2x+11=308 =>2x=48 =>x=24. Therefore age of the captain =(x+11)= 24+11= 35 years. Answer is 35 years.

Top
24.The average age of the boys in the class is the number of girls in the class .If the ratio boys and girls in the class of 36 be 5:1, what the total of the age (in years) of the boys in twice of is the class?

Solution: Number of boys=36*5/6=30 Number of girls =6 Average age of boys =2*6=12 years Total age of the boys=30*12=360 years Answer is 360 years. 25.Five years ago, the average age of P and Q was 15 years ,average age of P,Q, and R today is 20 years,how old will R be after 10 years? Solution: Age of P and Q are 15*2=30 years Present age of P and Q is 30+5*2=40 years. Age of P Q and R is 20*3= 60 years. R ,present age is 60-40=20 years After 10 years =20+10=30 years. Answer is 30 years. 26.The average weight of 3 men A,B and C is 84 Kgs. Another man D joins the group and the average now becomes 80 Kgs.If another man E whose weight is 3 Kgs more than that of D ,replaces A then the average weight B,C,D and E becomes 79 Kgs. The weight of A is. Solution:Total weight of A, B and C is 84 * 3 =252 Kgs. Total weight of A,B,C and Dis 80*4=320 Kgs Therefore D=320-252=68 Kgs. E weight (68+3)=71 kgs Total weight of B,C,D and E = 79*4=316 Kgs (A+B+C+D)-(B+C+D+E)=320-316 =4Kgs A-E=4Kgs A-71=4 kgs A=75 Kgs Answer is 75 kgs 27.A team of 8 persons joins in a shooting competition. The best marksman scored 85 points.If he had scored 92 points ,the average score for the team would have been 84.The team scored was. Solution: Here consider the total score be x. therefore x+92-85/8=84 =>x+7=672 =>x=665. Answer is 665 28.A man whose bowling average is 12.4,takes 5 wickets for 26 runs and there by decrease his average by 0.4. The number of wickets,taken by him before his last match is: Solution: Number of wickets taken before last match be x. therefore 12.4x26/x+5=12(since average decrease by 0.4 therefore 12.4-0.4=12) =>12.4x+2612x+60 =>0.4x=34 =>x=340/4 =>x=85.

Answer is 85. 29.The mean temperature of Monday to Wednesday was 37 degrees and of Tuesday to Thursday was 34 degrees .If the temperature on Thursday was 4/5th that of Monday. The temperature on Thursday was: Solution: The total temperature recorded on Monday,Wednesday was 37*3=111. The total temperature recorded on Tuesday, Wednesday,Thursday was 34*3=102. and also given that Th=4/5M =>M=5/4Th (M+T+W)-(T+W+Th)=111-102=9 M-Th=9 5/4Th-Th=9 Th(1/4)=9 =>Th=36 degrees. 30. 16 children are to be divided into two groups A and B of 10 and 6 children. The average percent marks obtained by the children of group A is 75 and the average percent marks of all the 16 children is 76. What is the average percent marks of children of groups B? Solution: Here given average of group A and whole groups . So,(76*16)-(75*10)/6 =>1216-750/6 =>466/6=233/3=77 2/3 Answer is 77 2/3. 31.Of the three numbers the first is twice the second and the second is twice the third .The average of the reciprocal of the numbers is 7/72,the number are. Solution:Let the third number be x Let the second number be 2x. Let the first number be 4x. Therefore average of the reciprocal means 1/x+1/2x+1/4x=(7/72*3) 7/4x=7/24 =>4x=24 x=6. Therefore First number is 4*6=24. Second number is 2*6=12 Third number is 1*6=6 Answer is 24,12,6. 32.The average of 5 numbers is 7.When 3 new numbers are added the average of the eight numbers is 8.5. The average of the three new number is: Solution: Sum of three new numbers=(8*8.5-5*7)=33 Their average =33/3=11. Answer is 11.

33.The average temperature of the town in the first four days of a month was 58 degrees. The average for the second ,third,fourth and fifth days was 60 degree .If the temperature of the first and fifth days were in the ratio 7:8 then what is the temperature on the fifth day? Solution : Sum of temperature on 1st 2nd 3rd and 4th days =58*4=232 degrees. Sum of temperature on 2nd 3rd 4th and 5th days =60*4=240 degrees Therefore 5th day temperature is 240-232=8 degrees. The ratio given for 1st and 5th days be 7x and 8x degrees then 8x-7x=8 =>x=8. therefore temperature on the 5th day =8x=8*8=64 degrees.

Problems on Numbers
Simple problems: 1.What least number must be added to 3000 to obtain a number exactly divisible by 19? Solution: On dividing 3000 by 19 we get 17 as remainder Therefore number to be added = 19-17=2. 2.Find the unit's digit n the product 2467 153 * 34172? Solution: Unit's digit in the given product=Unit's digit in 7 153 * 172 Now 7 4 gives unit digit 1 7 152 gives unit digit 1 7 153 gives 1*7=7.Also 172 gives 1 Hence unit's digit in the product =7*1=7. 3.Find the total number of prime factors in 411 *7 5 *112 ? Solution: 411 7 5 112= (2*2) 11 *7 5 *112 = 222 *7 5 *112 Total number of prime factors=22+5+2=29 4.The least umber of five digits which is exactly divisible by 12,15 and 18 is? a.10010 b.10015 c.10020 d.10080 Solution: Least number of five digits is 10000 L.C.Mof 12,15,18 s 180.

On dividing 10000 by 180,the remainder is 100. Therefore required number=10000+(180-100) =10080. Ans (d). 5.The least number which is perfect square and is divisible by each of the numbers 16,20 and 24 is? a.1600 b.3600 c.6400 d.14400 Solution: The least number divisible by 16,20,24 = L.C.M of 16,20,24=240 =2*2*2*2*3*5 To make it a perfect square it must be multiplied by 3*5. Therefore required number =240*3*5=3600. Ans (b). 6.A positive number which when added to 1000 gives a sum , which is greater than when it is multiplied by 1000. The positive integer is? a.1 b.3 c.5 d.7 Solution: 1000+N>1000N clearly N=1. 7.How many numbers between 11 and 90 are divisible by 7? Solution: The required numbers are 14,21,28,...........,84. This is an A.P with a=14,d=7. Let it contain n terms then T =84=a+(n-1)d =14+(n-1)7 =7+7n 7n=77 =>n=11. 8.Find the sum of all odd numbers up to 100? Solution: The given numbers are 1,3,5.........99. This is an A.P with a=1,d=2. Let it contain n terms 1+(n-1)2=99 =>n=50 Then required sum =n/2(first term +last term) =50/2(1+99)=2500. 9.How many terms are there in 2,4,6,8..........,1024? Solution: Clearly 2,4,6........1024 form a G.P with a=2,r=2 Let the number of terms be n then 2*2 n-1=1024 2n-1 =512=29 n-1=9 n=10. 10.2+22+23+24+25..........+28=?

Solution: Given series is a G.P with a=2,r=2 and n=8. Sum Sn=a(1-r n)/1-r=Sn=2(1-28)/1-2. =2*255=510. 11.Find the number of zeros in 27!? Solution: Short cut method : number of zeros in 27!=27/5 + 27/25 =5+1=6zeros.

Top
Medium Problems: 12.The difference between two numbers 1365.When the larger number is divided by the smaller one the quotient is 6 and the remainder is 15.The smaller number is? a.240 b.270 c.295 d.360 Solution: Let the smaller number be x, then larger number =1365+x Therefore 1365+x=6x+15 5x=1350 => x=270 Required number is 270. 13.Find the remainder when 231 is divided by 5? Solution: 210 =1024. unit digit of 210 * 210 * 210 is 4 as 4*4*4 gives unit digit 4 unit digit of 231 is 8. Now 8 when divided by 5 gives 3 as remainder. 231 when divided by 5 gives 3 as remainder. 14.The largest four digit number which when divided by 4,7 or 13 leaves a remainder of 3 in each case is? a.8739 b.9831 c.9834 d.9893. Solution: solution: Greatest number of four digits is 9999 L.C.M of 4,7, and 13=364. On dividing 9999 by 364 remainder obtained is 171. Therefore greatest number of four digits divisible by 4,7,13 =9999-171=9828. Hence required number=9828+3=9831. Ans (b). 15.What least value must be assigned to * so that th number 197*5462 is divisible by 9? Solution: Let the missing digit be x Sum of digits = (1+9+7+x+5+4+6+2)=34+x For 34+x to be divisible by 9 , x must be replaced by 2 The digit in place of x must be 2.

16.Find the smallest number of 6 digits which is exactly divisible by 111? Solution: Smallest number of 6 digits is 100000 On dividing 10000 by 111 we get 100 as remainder Number to be added =111-100=11. Hence,required number =10011. 17.A number when divided by 342 gives a remainder 47.When the same number is divided by 19 what would be the remainder? Solution: Number=342 K + 47 = 19 * 18 K + 19 * 2 + 9=19 ( 18K + 2) + 9. The given number when divided by 19 gives 18 K + 2 as quotient and 9 as remainder. 18.In doing a division of a question with zero remainder,a candidate took 12 as divisor instead of 21.The quotient obtained by him was 35. The correct quotient is? a.0 b.12 c.13 d.20 Solution: Dividend=12*35=420. Now dividend =420 and divisor =21. Therefore correct quotient =420/21=20. 19.If a number is multiplied by 22 and the same number is added to it then we get a number that is half the square of that number. Find the number. a.45 b.46 c.47 d. none Solution: Let the required number be x. Given that x*22+x = 1/2 x2 23x = 1/2 x2 x = 2*23=46 Ans (b) 20.Find the number of zeros in the factorial of the number 18? Solution: 18! contains 15 and 5,which combined with one even number gives zeros. Also 10 is also contained in 18! which will give additional zero .Hence 18! contains 3 zeros and the last digit will always be zero. 21.The sum of three prime numbers is 100.If one of them exceeds another by 36 then one of the numbers is? a.7 b.29 c.41 d67. Solution: x+(x+36)+y=100 2x+y=64 Therefore y must be even prime which is 2 2x+2=64=>x=31.

Third prime number =x+36=31+36=67. 22.A number when divided by the sum of 555 and 445 gives two times their difference as quotient and 30 as remainder . The number is? a.1220 b.1250 c.22030 d.220030. Solution: Number=(555+445)*(555-445)*2+30 =(555+445)*2*110+30 =220000+30=220030. 23.The difference of 1025-7 and 1024+x is divisible by 3 for x=? a.3 b.2 c.4 d.6 Solution: The difference of 1025-7 and 1024+x is =(1025-7)-(1024-x) =1025-7-1024-x =10.1024-7 -1024-x =1024(10-1)-(7-x) =1024*9-(7+x) The above expression is divisible by 3 so we have to replace x with 2. Ans (b).

Top
Complex Problems: 24.Six bells commence tolling together and toll at intervals of 2,4,6,8,10,12 seconds respectively. In 30 minutes how many times do they toll together? Solution: To find the time that the bells will toll together we have to take L.C.M of 2,4,6,8,10,12 is 120. So,the bells will toll together after every 120 seconds i e, 2 minutes In 30 minutes they will toll together [30/2 +1]=16 times 25.The sum of two numbers is 15 and their geometric mean is 20% lower than their arithmetic mean. Find the numbers? a.11,4 b.12,3 c.13,2 d.10,5 Solution: Sum of the two numbers is a+b=15. their A.M = a+b / 2 and G.M = (ab)1/2 Given G.M = 20% lower than A.M =80/100 A.M (ab)1/2=4/5 a+b/2 = 2*15/5= 6 (ab)1/2=6 ab=36 =>b=36/a a+b=15 a+36/a=15 a2+36=15a a2-15a+36=0 a2-3a-12a+36=0 a(a-3)-12(a-3)=0

a=12 or 3. If a=3 and a+b=15 then b=12. If a=12 and a+b=15 then b=3. Ans (b). 26.When we multiply a certain two digit number by the sum of its digits 405 is achieved. If we multiply the number written in reverse order of the same digits by the sum of the digits,we get 486.Find the number? a.81 b.45 c.36 d. none Solution: Let the number be x y. When we multiply the number by the sum of its digit 405 is achieved. (10x+y)(x+y)=405....................1 If we multiply the number written in reverse order by its sum of digits we get 486. (10y+x)(x+y)=486......................2 dividing 1 and 2 (10x+y)(x+y)/(10y+x)(x+y) = 405/486. 10x+y / 10y+x = 5/6. 60x+6y = 50y+5x 55x=44y 5x = 4y. From the above condition we conclude that the above condition is satisfied by the second option i e b. 45. Ans (b). 27.Find the HCF and LCM of the polynomials x2-5x+6 and x2-7x+10? a.(x-2),(x-2)(x-3)(x-5) b.(x-2),(x-2)(x-3) c.(x-3),(x-2)(x-3)(x-5) d. none Solution: The given polynomials are x2-5x+6=0................1 x2-7x+10=0...............2 we have to find the factors of the polynomials x2-5x+6 and x2-7x+10 x2-2x-3x+6 x2-5x-2x+10 x(x-2)-3(x-2) x(x-5)-2(x-5) (x-3)(x-2) (x-2)(x-5) From the above factors of the polynomials we can easily find the HCF as (x-3)and LCM as (x-2)(x-3)(x-5). Ans (c) 28.The sum of all possible two digit numbers formed from three different one digit natural numbers when divided by the sum of the original three numbers is equal to? a.18 b.22 c.36 d. none Solution: Let the one digit numbers x,y,z Sum of all possible two digit numbers =(10x+y)+(10x+z)+(10y+x)+(10y+z)+(10z+x)+(10z+y) = 22(x+y+z)

Therefore sum of all possible two digit numbers when divided by sum of one digit numbers gives 22. 29.A number being successively divided by 3,5,8 leaves remainders 1,4,7 respectively. Find the respective remainders if the order of divisors are reversed? Solution: Let the number be x. 5 8 z=8*1+7=15 y=5z+4 = 5*15+4 = 79 x=3y+1 = 3*79+1=238 Now 8 3 y z 1 x 1 4 7

29 5 1 Respective remainders are 6,4,2.

5 3

238

6 4 2

30.The arithmetic mean of two numbers is smaller by 24 than the larger of the two numbers and the GM of the same numbers exceeds by 12 the smaller of the numbers. Find the numbers? a.6,54 b.8,56 c.12,60 d.7,55 Solution: Let the numbers be a,b where a is smaller and b is larger number. The AM of two numbers is smaller by 24 than the larger of the two numbers. AM=b-24 AM of two numbers is a+b/2. a+b/2 = b-24 a+b = 2b-48 a = b-48...................1 The GM of the two numbers exceeds by 12 the smaller of the numbers GM = a+12 GM of two numbers is (ab)1/2 (ab) 1/2= a+12 ab = a2+144+24a from 1 b=a+48 a(a+48)= a2+144+24a a2+48a = a2+144+24a 24a=144=>a=6 Therefore b=a+48=54. Ans (a). 31.The sum of squares of the digits constituting a positive two digit number is 13,If we subtract 9 from that number we shall get a number written by the same digits in the reverse order. Find the number? a.12 b.32 c.42 d.52.

Solution: Let the number be x y. the sum of the squares of the digits of the number is 13 x2+y2=13 If we subtract 9 from the number we get the number in reverse order x y-9=y x. 10x+y-9=10y+x. 9x-9y=9 x-y=1 (x-y)2 =x2+y2-2x y 1 =13-2x y 2x y = 12 x y = 6 =>y=6/x x-y=1 x-6/x=1 x2-6=x x2-x-6=0 x+2x-3x-6=0 x(x+2)-3(x+2)=0 x=3,-2. If x=3 and x-y=1 then y=2. If x=-2 and x-y=1 then y=-3. Therefore the number is 32. Ans (b).

Top
32.If we add the square of the digit in the tens place of the positive two digit number to the product of the digits of that number we get 52,and if we add the square of the digit in the unit's place to the same product of the digits we get 117.Find the two digit number? a.18 b.39 c.49 d.28 Solution: Let the digit number be x y Given that if we add square of the digit in the of a number to the product of the digits we get x2+x y=52. x(x+y)=52....................1 Given that if we add the square of the digit in e to the product is 117. y2+x y= 117 y(x+y)=117.........................2 dividing 1 and 2 x(x+y)/y(x+y) = 52/117=4/9 x/y=4/9 from the options we conclude that the two digit because the condition is satisfied by the third Ans (c)

tens place 52. the unit's plac

number is 49 option.

33.The denominators of an irreducible fraction is greater than the numerator by 2.If we reduce the numerator of the reciprocal fraction by 3 and subtract the given fraction from the resulting one,we get 1/15.Find the given fraction? Solution: Let the given fraction be x / (x+2) because given that

denominator of the fraction is greater than the numerator by 2 1 [(x 1/(x+2))/3] = 1/15. 1 (x2+2x-1) /3(x+2) = 1/15 (3x+6-x2-2x+1)/3(x+2) = 1/15 (7-x2+2x)/(x+2) = 1/5 -5x2+5x+35 = x+2 5x2-4x-33 = 0 5x2-15x+11x-33 = 0 5x(x-3)+11(x-3) = 0 (5x+11)(x-3) = 0 Therefore x=-11/5 or 3 Therefore the fraction is x/(x+2) = 3/5. 34.Three numbers are such that the second is as much lesser than the third as the first is lesser than the second. If the product of the two smaller numbers is 85 and the product of two larger numbers is 115. Find the middle number? Solution: Let the three numbers be x,y,z Given that z y = y x 2y = x+z.....................1 Given that the product of two smaller numbers is 85 x y = 85................2 Given that the product of two larger numbers is 115 y z = 115...............3 Dividing 2 and 3 x y /y z = 85/115 x / z = 17 / 23 From 1 2y = x+z 2y = 85/y + 115/y 2y2 = 200 y2 = 100 y = 10 35.If we divide a two digit number by the sum of its digits we get 4 as a quotient and 3 as a remainder. Now if we divide that two digit number by the product of its digits we get 3 as a quotient and 5 as a remainder . Find the two digit number? Solution: Let the two digit number is x y. Given that x y / (x+y) quotient=4 and remainder = 3 we can write the number as x y = 4(x+y) +3...........1 Given that x y /(x*y) quotient = 3 and remainder = 5 we can write the number as x y = 3 x*y +5...............2 By trail and error method For example take x=1,y=2 1............12=4(2+3)+3 =4*3+3 ! =15 let us take x=2 y=3

1..............23=4(2+3)+3 =20+3 =23 2.............23=3*2*3+5 =18+5 =23 the above two equations are satisfied by x=2 and y=3 Therefore the required number is 23. 36.First we increased the denominator of a positive fraction by 3 and then it by 5.The sum of the resulting fractions proves to be equal to 2/3. Find the denominator of the fraction if its numerator is 2. Solution: Let us assume the fraction is x/y First we increasing the denominator by 3 we get x/(y-3) Then decrease it by 5 we get the fraction as x/(y-5) Given that the sum of the resulting fraction is 2/3 x/(y+3) + x/(y-5) = 2/3 Given numerator equal to 2 2*[ 1/y+3 + 1/y-5] =2/3 (y-5+y+3) / (y-3)(y+5) =1/3 6y 6 = y2-5y+3y-15 y2-8y-9 = 0 y2-9y+y-9 = 0 y(y-9)+1(y-9) = 0 Therefore y =-1 or 9. 37.If we divide a two digit number by a number consisting of the same digits written in the reverse order,we get 4 as quotient and 15 as a remainder. If we subtract 1 from the given number we get the sum of the squares of the digits constituting that number. Find the number? a.71 b.83 c.99 d. none Solution: Let the number be x y. If we divide 10x+y by a number in reverse order i e,10y+x we get 4 as quotient and 15 as remainder. We can write as 10x+y = 4(10y+x)+15......................1 If we subtract 1 from the given number we get square of the digits 10x+y = x2+y2.....................................2 By using above two equations and trail and error method we get the required number. From the options also we can solve the problem. In this no option is satisfied so answer is d. Ans (d)

Problems on Ages
Simple problems:

1.The present age of a father is 3 years more than three times the age of his son.Three years hence,fathers age will be 10 years more than twice the age of the son.Find the present age of the father. Solution: Let the present age be 'x' years. Then father's present age is 3x+3 years. Three years hence (3x+3)+3=2(x+3)+10 x=10 Hence father's present age = 3x+3 = 33 years. 2. One year ago the ratio of Ramu & Somu age was 6:7respectively. Four years hence their ratio would become 7:8. How old is Somu. Solution: Let us assume Ramu &Somu ages are x &y respectively. One year ago their ratio was 6:7 i.e x-1 / y-1 = 7x-6y=1 Four years hence their ratios,would become 7:8 i.e x-4 / y-4 = 7 / 8 8x-7y=-4 From the above two equations we get y= 36 years. i.e Somu present age is 36 years. 3. The total age of A &B is 12 years more than the total age of B&C. C is how many year younger than A. Solution: From the given data A+B = 12+(B+C) A+B-(B+C) = 12 A-C=12 years. C is 12 years younger than A

4. The ratio of the present age of P & Q is 6:7. If Q is 4 years old than P. what will be the ratio of the ages of P & Q after 4 years. Solution: The present age of P & Q is 6:7 i.e P / Q = 6 / 7 Q is 4 years old than P i.e Q = P+4. P/ P+4 = 6/7 7P-6P = 24, P = 24 , Q = P+4 =24+4 = 28 After 4 years the ratio of P &Q is P+4:Q+4 24+4 : 28+4 = 28:32 = 7:8

5. The ratio of the age of a man & his wife is 4:3.After 4 years this ratio will be 9:7. If the time of marriage the ratio was 5:3, then how many years ago were they married.

Solution:

The age of a man is 4x . The age of his wife is 3x. After 4 years their ratio's will be 9:7 i.e 4x+4 / 3x+4 = 9 / 7 28x-27x=36-28 x = 8. Age of a man is 4x = 4*8 = 32 years. Age of his wife is 3x = 3*8 = 24 years. Let us assume 'y' years ago they were married , the ratio was 5:3 ,i.e 32-y / 24-y = 5/ 3 y=12 years i.e 12 years ago they were married Top

6. Sneh's age is 1/6th of her father's age.Sneh's father's age will be twice the age of Vimal's age after 10 years. If Vimals eight birthday was celebrated two years before,then what is Sneh's present age. a) 6 2/3 years b) 24 years c) 30 years d) None of the above

Solution:

Assume Snehs age is 'x' years. Assume her fathers age is 'y' years. Snehs age is 1/6 of her fathers age i.e x = y /6. Fathers age will be twice of Vimal's age after 10 years. i.e y+10 = 2( V+10)( where 'V' is the Vimal's age) Vimal's eight birthday was celebrated two years before, Then the Vimal's present age is 10 years. Y+10 = 2(10+10) Y=30 years. Sneh's present age x = y/6 x = 30/6 = 5 years. Sneh's present age is 5 years.

7.The sum of the ages of the 5 children's born at the intervals of 3 years each is 50 years what is the age of the youngest child. a) 4 years Solution: b) 8 years c) 10 years d)None of the above

Let the age of the children's be x ,x+3, x+6, x+9, x+12. x+(x+3)+(x+6)+(x+9)+(x+12) = 50 5x+30 = 50 5x = 20 x=4. Age of the youngest child is x = 4 years.

8. If 6 years are subtracted from the present age of Gagan and the remainder is divided by 18,then the present age of his grandson Anup is obtained. If Anup is 2 years younger to Madan

whose age is 5 years,then a) 48 years Solution: b)60 years

what is Gagan's present age. c)84 years d)65 years

Let us assume Anup age (x-6) x-6 x=60

Gagan present age is 'x' years. = 5-2 = 3 years. / 18 = 3 = 54 years

9.My brother is 3 years elder to me. My father was 28 years of age when my sister was born while my father was 26 years of age when i was born. If my sister was 4 years of age when my brother was born,then what was the age my father and mother respectively when my brother was born. a) 32 yrs, 23yrs b)32 yrs, 29yrs c)35 yrs,29yrs d)35yrs,33 yrs

Solution: My brother was born 3 years before I was born & 4 years after my sister was born. Father's age when brother was born = 28+4 = 32 years. Mother's age when brother was born = 26-3 = 23 years.

SURDS AND INDICES


Simple problems: 1. Laws of Indices: (i) (ii) (iii) (iv) (v) (vi) am * an am / an (am)n (ab)n (a/b)n a0 = = = = = = a(m+n) a(m-n) a(m*n) an * bn an / bn 1

2.Surds :Let 'a' be a rational number & 'n' be a positive integer such that a1/n = nth root a is irrational.Then nth root a is called 'a' surd of 'n'. Problems:(1) (i) (27)2/3 = (33)2/3 = 32 = 9. (ii) (1024)-4/5 = (45)-4/5 = (4)-4= 1/(4)4 = 1/256. (iii)(8/125)-4/3 =((2/5)3)-4/3 = (2/5)-4 = (5/2)4 = 625/16 (2) If 2(x-1)+ 2(x+1) = 1280 then find the value of x .

Solution: 2x/2+2x.2 = 1280 2x(1+22) = 2*1280 2x = 2560/5 2x = 512 => 2x = 29 x = 9 (3) Find the value of [5[81/3+271/3]3]1/4 Solution: [5[(23)1/3+(33)1/3]3]1/4 [5[2+3]3]1/4 [54]1/4 => 5. (4) If (1/5)3y= 0.008 then find the value of (0.25)y Solution: (1/5)3y = 0.008 (1/5)3y =[0.2]3 (1/5)3y =(1/5)3 3y= 3 => y=1. (0.25)y = (0.25)1 =>

0.25 = 25/100 32n+1 / / (32)n 9n

= 1/4

(5) Find the value of (243)n/5 * Solution: (35)n/5 * 32n +1 33n+1 / 33n-1 3 33n+1 * 3-3n+1

* 3 n-1 * 3n-1

=> 32

=>9.

(6) Find the value of Solution:

(21/4-1)( 23/4 +21/2+21/4+1)

Let us say 21/4 = x (x-1)(x3+x2+x+1) (x-1)(x2(x+1)+(x+1)) (x-1) (x2+1) (x+1) [(x-1)(x+1) = (x2-1)] (x2+1) (x2-1) => (x4-1) ((21/4))4 - 1) = > (2-1) = > 1. , z = xc then find the value

(7)

If x= ya , y = zb of abc. Solution:

z= xc z= (ya)c [ z= (y)ac z= (zb)ac z= zabc abc = 1

x= ya ] [y= zb]

(8)Simplify (xa/xb)a2+ab+b2*(xb/xc)b2+bc+c2*(xc/xa)c2+ca+a2 Solution:[xa-b]a2+ab+b2 * [xb-c]b2+bc+c2 * [xc-a]c2+ca+a2 [ (a-b)(a2+ab+b2) = a3-b3]

from the above formula => xa3-b3 xb3-c3 xc3-a3 => xa3-b3+b3-c3+c3-a3 => x0 = 1 (9) (1000)7 (a) 10 /1018 (b) = ? 100 (c ) 1000 = > (10)21 / (d) 10000 (10)18 1000

Solution: (1000)7 / 1018 (103)7 / (10)18 Ans :( c ) (10) The => (10)21-18

=> (10)3 =>

value

of

(8-25-8-26)

is (d) None

(a) 7* 8-25

(b) 7*8-26

(c ) 8* 8-26

Solution: ( 8-25 - 8-26 ) => 8-26 (8-1 ) => 7* 8-26 Ans: (b) Top (11) 1 / (1+ an-m ) +1/ (1+am-n) (a) 0 (b) 1/2 (c ) 1 1/ => => => = ? (d) an+m

Solution:

Ans: ( c)

(1+ an/am) + 1/ ( 1+ am/an) am / (am+ an ) + an /(am +an ) (am +an ) /(am + an) 1

(12) 1/(1+xb-a+xc-a)+1/(1+xa-b+xc-b)+1/(1+xb-c+xa-c)=? (a) 0 (b) 1 ( c ) xa-b-c (d) None of the above

Solution:

1/ (1+xb/xa+xc/xa) + 1/(1+xa/xb +xc/xb) + 1/(1+xb/xc +xa/xc) => xa /(xa +xb+xc) + xb/(xa +xb+xc) +xc/(xa +xb+xc) =>(xa +xb+xc) /(xa +xb+xc) =>1 Ans: (b) (13) If x=3+2 2 then the value of (x 1/ x) is [ =root] (a) 1 (b) 2 (c ) = 22 ( d) 33

Solution:

(x-1/x)2

x+ 1/x-2

=> => =>

Ans : (b) (14)

3+22 + (1/3+22 )-2 3+22 + 3-22 -2 6-2 = 4 (x-1/x)2 = 4 =>(x-1/x)2 = 22 (x-1/x) = 2.

(xb/xc)b+c-a (xc/xa)c+a-b (xa/xb)b+a-c (a) xabc (b) 1

= ?

( c) xab+bc+ca (d) xa+b+c [xc-a]c+a-b [xa-b]a+b-c

Solution: [xb-c]b+c-a

=>x(b-c)(b+c-a) x(c-a)(c+a-b) x(a-b)(a+b-c) =>x(b2-c2-ab-ac) x(c2-a2-bc-ab) x(a2-b2-ac-bc) =>x(b2-c2-ab-ac+c2-a2-bc-ab+a2-b2-ac-bc) => x0 =>1 Ans: (b) (15) If 3x-y (a) Solution: 0 = 27 and (b) 2 3x+y = 243 then x is equal to (d) 6

(c ) 4

3x-y = 27 => 3x-y = 33 x-y= 3 3x+y = 243 => 3x+y = 35 x+y = 5 From above two equations x = 4 , y=1

Ans: (c ) (16) If ax = by = cz and b2 = ac then yequals

(a)xz/x+z (b)xz/2(x-z) (c)xz/2(z-x) (d)2xz/x+z Solution: Let us say ax = by = cz = k ax =k => [ax]1/x = k1/x => a = k1/x Simillarly b = k1/y c = k1/z b2 = ac [k1/y]2=k1/xk1/z =>k2/y = k1/x+1/z => 2/y = 1/x+1/y =>y= 2xz/x+z

Ans: (17)

(d) ax = b,by = c ,cz = a then the value of xyz is is

(a) 0

(b) 1

(c ) 1/abc

(d) abc

Solution:

ax = b (cz)x = b by)xz = b =>xyz =1

[cz = a] [by = c]

Ans: (b) (18) If 2x = 4y =8z and (1/2x +1/4y +1/6z) =24/7 then the value of 'z' is (a) 7/16 (b) 7 / 32 (c ) 7/48 (d) 7/64

Solution:

Ans: ( c)

2x = 4y=8z 2x = 22y = 23z x= 2y = 3z Multiply above equation with 2 2x = 4y= 6z (1/2x+1/4y+1/6z) = 24/7 =>(1/6z+1/6z+1/6z) = 24/7 => 3 / 6z = 24/7 => z= 7/48

Problems on Percentages
Simple problems: 1 . Express the following a) 56% SOLUTION: b) 4% 56/100=14/25 as a fraction.

SOLUTION: 4/100=1/25

c) 0.6%

SOLUTION:

0.6/100=6/1000=3/500

d) 0.08% SOLUTION: 0.08/100=8/10000=1/1250

2. a)

Express the following as decimals 6% SOLUTION: 6% = 6/100=0.06

b) 0.04%

SOLUTION: 0.04% = 0.04/100=0.0004

3 . Express the following as rate percent. i).23/36 SOLUTION: ii).6 = (23/36*100) % = 63 8/9%

SOLUTION: 6 =27/4 (27/4 *100) % =675 % 4. Evaluate the following: 28% of 450 + 45% of 280 ? SOLUTION: =(28/100) *450 + (45/100) *280 = 28 * 45 / 5 = 252

5. 2 is what percent of 50? SOLUTION: Formula : (IS / OF ) *100 % = 2/50 *100 = 4%

6. is what percent of 1/3? SOLUTION: =( ) / (1/3) *100 % = 3/2 *100 % = 150 % is 40 Quintals?

7. What percent of 2 Metric tonnes

SOLUTION: 1 metric tonne =10 Quintals So required percentage=(40/(2*10))*100% = 200% 8. Find the missing figure . i) ? % of 25 = 2.125 SOLUTION : Let x% of 25 = 2.125.then (x/100) *25 =2.125 x = 2.125 * 4 = 8.5 9% of ? =6.3

ii)

SOLUTION:

Let 9 % of x = 6.3. Then 9/100 of x= 6.3 so x = 6.3 *100/7 = 70.

9. Which is the greatest in 16 2/3 %, 2/15,0.17? SOLUTION: 16 2/3 % = 50/3 % =50/3 * 1/100 =1/6 = 0.166 2 / 15 =0.133 So 0.17 is greatest number in the given series. 10.If the sales tax be reduced from 3 % to 3 1/3 % , then what difference does it make to a person who purchases an article with marked price of RS 8400? SOLUTION: Required difference = 3 % of 8400 3 1/3 % of 8400 =(7/2-10/3)% of 8400 =1/6 % of 8400 = 1/6* 1/100* 8400 = Rs 14. 11. A rejects 0.08% of the meters as defective .How many will he examine to reject 2? SOLUTION: Let the number of meters to be examined be x. Then 0.08% of x=2. 0.08/100*x= 2 x= 2 * 100/0.08 =2 * 100 * 100/8 = 2500 12.65 % of a number is 21 less than 4/5 of that number. What is the number? SOLUTION: Let the number be x. 4/5 x- (65% of x) = 21 4/5x 65/100 x=21 15x=2100 x=140

13. Difference of two numbers is 1660.If 7.5 % of one number is 12.5% of the other number. Find two numbers? SOLUTION: Let the two numbers be x and y. 7.5% of x=12.5% of y' So 75x=125 y 3x=5y x=5/3y.

Now x-y=1660 5/3y-y=1660 2/3y=1660 y=2490 So x= 2490+1660 =4150. So the numbers are 4150 , 1660. 14. In expressing a length 81.472 KM as nearly as possible with 3 significant digits ,Find the % error? SOLUTION: Error= 81.5-81.472=0.028 So the required percentage = 0.028/81.472*100% = 0.034% Top 15. In an election between two persons ,75% of the voters cast their votes out of which 2% are invalid. A got 9261 which 75% of the total valid votes. Find total number of votes? SOLUTION: Let x be the total votes. valid votes are 98% of 75% of x. So 75%(98%(75% of x))) = 9261 ==> 75/100 *98 /100 * 75 100 *x = 9261 x= 1029 * 4 *100 *4 / 9 = 16800 So total no of votes = 16800

16 . A's maths test had 75 problems i.e 10 arithmetic, 30 algebra and 35 geometry problems.Although he answered 70% of arithmetic ,40% of algebra and 60 % of geometry problems correctly he didn't pass the test because he got less than 60% of the problems right. How many more questions he would have needed to answer correctly to get a 60% passing grade. SOLUTION: 70% of 10 =70/100 * 10 =7 40% of 30 = 40 / 100 * 30 = 12 60 % of 35 = 60 / 100 *35 = 21 So correctly attempted questions = 7 + 12 + 21 =40. Questions to be answered correctly for 60% grade =60% of 75 = 60/100 *75 =45. So required questions=45-40 = 5

17 . If 50% of (x y) = 30% of (x + y) then what percent of x is y ?

SOLUTION: 50/100(x-y) =30/100(x+y) (x-y)= 3/10(x+y) 5x-5y=3x+3y x=4y So Required percentage =y/x*100 % =y/4y *100 % = 25%. 18 .If the price of tea is increased by 20% ,find how much percent must a householder reduce her consumption of tea so as not to increase the expenditure? SOLUTION: Reduction in consumption= R/(100+R) *100% =20/120 *100 = 16 2/3 % 19.The population of a town is 176400 . If it increases at the rate of 5% per annum ,what will be the population 2 years hence? What was it 2 years ago? SOLUTION: Population After 2 years = 176400[1+5/100]2 =176400 * 21/20 *21/20 =194481 Population 2 years ago = 176400/(1+5/100)2 = 176400 * 20/21 *20/ 21 =160000 20.1 liter of water is add to 5 liters of a 20 % solution of alcohol in water . Find the strength of alcohol in new solution? SOLUTION: Alcohol in 5 liters = 20% of 5 =1 liter Alcohol in 6 liters of new mixture = 1liter So % of alcohol is =1/6 *100=16 2/3% 21.If A earns 33 1/3 more than B .Then B earns less than A by what percent? SOLUTION: 33 1/3 =100 / Required Percentage = (100/3)/(100 + (100/3)) *100 % = 100/400 *100 = 25 % 22.A school has only three classes which contain 40,50,60 students respectively.The pass percent of these classes are 10, 20 and 10 respectively . Then

find the pass percent in the school. SOLUTION: Number of passed candidates = 10/100*40+20/100 *50+10/100 * 60 =4+10+6 =20 Total students in school = 40+50+60 =150 So required percentage = 20/150 *100 = 40 /3 =13 1/3 % 23. There are 600 boys in a hostel . Each plays either hockey or football or both .If 75% play hockey and 45 % play football ,Find how many play both? SOLUTION: n(A)=75/100 *600 =450 n(B) = 45/100 *600 = 270 n(A^B)=n(A) + n(B) n(AUB) =450 + 270 -600 =120 So 120 boys play both the games.

24.A bag contains 600 coins of 25p denomination and 1200 coins of 50p denomination. If 12% of 25p coins and 24 % of 50p coins are removed, Find the percentage of money removed from the bag ? SOLUTION: Total money = (600 * 25/100 +1200 *50/100) =Rs 750 25p coins removed = 12/100 *600 =72 50p coins removed = 24/100 *1200 =288 So money removed =72 *1/4 +288 *1/2 = Rs 162 So required percentage=162/750 *100 =21 .6% 25. P is six times as large as Q.Find the percent that Q is less than P? SOLUTION: Given that P= 6Q So Q is less than P by 5Q. Required percentage= 5Q/P*100 % =5/6 * 100 % =83 1/3%

26.For a sphere of radius 10 cm ,the numerical value of surface area is what percent of the numerical value of its volume? SOLUTION: Surface area = 4 *22/7 *r2 = 3/r(4/3 * 22/7 * r3) =3/r * VOLUME Where r = 10 cm So we have S= 3/10 V =3/10 *100 % of V = 30 % of V So surface area is 30 % of Volume.

27. A reduction of 21 % in the price of wheat enables a person to buy 10 .5 kg more for Rs 100.What is the reduced price per kg. SOLUTION: Let the original price = Rs x/kg Reduced price =79/100x /kg ==> 100/(79x/100)-100/x =10.5 ==> 10000/79x-100/x=10.5 ==> 10000-7900=10.5 * 79 x ==> x= 2100/10.5 *79 So required price = Rs (79/100 *2100/10.5 *79) /kg = Rs 2 per kg. 28.The length of a rectangle is increased by 60 % . By what percent would the width have to be decreased to maintain the same area? SOLUTION: Let the length =l,Breadth= b. Let the required decrease in breadth then 160/100 l *(100-x)/100 b=lb 160(100-x)=100 *100 or 100-x =10000/160 =125/2 so x = 100-125/2 =75/2=37.5

be x %

Profit and Loss


Important Facts: Cost Price: The price at which an article is purchased, is called its cost price,abbreviated as C.P. Selling Price: The price at which an article is sold, is called its selling price,abbreviated as S.P. Profit or Gain: If S.P. Is greater than C.P. The seller is said to have a profit or gain.

Loss:if S.P. Is less than C.P., the seller is said to have incurred a loss. Formulae 1.Gain=(S.P-C.P) 2.Loss=(C.P-S.P) 3.Loss or Gain is always reckoned on C.P. 4.Gain%=(gain*100)/C.P 5.Loss%=(loss*100)/C.P 6.S.P=[(100+gain%)/100]*C.P 7.S.P=[(100-loss%)/100]*C.P 8.C.P=(100*S.P)/(100+gain%) 9.C.P=(100*S.P)/(100-loss%) 10.If an article is sold at a gain of say,35%,then S.P=135% of C.P. 11.If an article is sold at a loss of say,35%,then S.P=65% of C.P. 12.When a person sells two similar items, one at a gain of say, x%,and the other at a loss of x%,then the seller always incurs a loss given by Loss%=[common loss and gain %/10]2=(x/10)2 13.If a trader professes to sell his goods at cost price,but uses false weight,then Gain%=[(error/(true value-error))*100]% 14.Net selling price=Marked price-Discount

Top
Simple Problems 1.A man buys an article for Rs.27.50 and sells it for Rs.28.60 Find the gain percent. Sol: C.P=Rs 27.50 S.P=Rs 28.60 then Gain=S.P-C.P=28.60-27.50=Rs 1.10 Gain%=(gain*100)/C.P% =(1.10*100)/27.50%=4%

2.If a radio is purchased for Rs 490 and sold for Rs 465.50 Find the loss%? Sol: C.P=Rs 490 S.P=Rs 465.50 Loss=C.P-S.P=490-465.50=Rs 24.50 Loss%=(loss*100)/C.P% =(24.50*100)/490%=5%

3.Find S.P when C.P=Rs 56.25 and Gain=20% Sol: S.P=[(100+gain%)/100]*C.P S.P=[(100+20)/100]56.25=Rs 67.50

4.Find S.P when C.P=Rs 80.40,loss=5% Sol: S.P=[(100-loss%)/100]*C.P S.P=[(100-5)/100]*80.40=Rs 68.34

5.Find C.P when S.P=Rs 40.60,gain=16%? Sol: C.P=(100*S.P)/(100+gain%)

C.P=(100*40.60)/(100+16)=Rs 35 6.Find C.P when S.P=Rs 51.70 ,loss=12%? Sol: C.P=(100*S.P)/(100-loss%) C.P=(100*51.70)/(100-12)=Rs 58.75

7.A person incurs 5% loss by selling a watch for Rs 1140 . At what price should the watch be sold to earn 5% profit? Sol: Let the new S.P be Rs x then, (100-loss%):(1st S.P)=(100+gain%):(2nd S.P) (100-5)/1140=(100+5)/x x=(105*1140)/95=Rs 1260

8.If the cost price is 96% of the selling price,then what is the profit percent? Sol: let S.P=Rs 100 then C.P=Rs 96 profit=S.P-C.P=100-96=Rs 4 profit%=(profit*C.P)/100% =(4*96)/100=4.17%

9.A discount dealer professes to sell his goods at cost price but uses a weight of 960 gms for a Kg weight .Find his gain %? Sol: Gain%=[(error*100)/(true value-error)]% =[(40*100)/1000-40)]%=25/6%

10.A man sold two flats for Rs 675,958 each .On one he gains 16% while on the other he losses 16%.How much does he gain or lose in the whole transaction? Sol: loss%=[common loss or gain%/10]2=(16/10)2=2.56%

11.A man sold two cows at Rs 1995 each. On one he lost 10% and on the other he gained 10%.what his gain or loss percent? Sol: If loss% and gain% is equal to 10 then there is no loss or no gain.

12.The price of an article is reduced by 25% in order to restore the must be increased by ? Sol: [x/(100-x)]*100 =[25/(100-25)]*100 =(25/75)*100=100/3%

13.Two discounts of 40% and 20% equal to a single discount of? Sol: {[(100-40)/100]*[(100-20)/100]}%=(60*80)/(100*100)% =48% single discount is equal to (100-48)%=52%

Top
Difficult Problems 1.The cost of an article including the sales tax is Rs 616.The rate of sales tax is 10%,if the shopkeeper has made a profit

of 12%,then the cost price of the article is? Sol: 110% of S.P=616 S.P=(616*100)/110=Rs 560 C.P=(100*S.P)/(100+gain%) C.P. =(100*560)/(100+12)=Rs 500

2.Sam purchased 20 dozens of toys at the rate of 375 Rs per dozen. He sold each one of then at the rate of Rs 33.What was his percentage profit? Sol: C.P of one toy=Rs 375/12=Rs 31.25 S.P of one toy=Rs 33 profit=S.P-C.P=33-31.25=Rs 1.75 profit %=(profit/C.P)*100 =(1.75/31.25)*100 profit% =5.6%

3.Two third of consignment was sold at a profit of 5% and the remainder at a loss of 2%.If the total was Rs 400,the value of the consignment was? Sol: let the value total total total value be Rs x of 2/3=2x/3, value of 1/3=x/3 S.P value be Rs x S.P=[(105% of 2x/3)+(98% of x/3)] =(105*2x)/(100*3)+(98/100)+x/3 =308x/300 (308x/300)-x=400 8x/300=400 x=(300*400)/8=Rs 15000

4.Kunal bought a suitcase with 15% discount on the labelled price. He sold the suitcase for Rs 2880 with 20% profit on the labelled price .At what price did he buy the suitcase? Sol: let the labelled price be Rs x then 120% of x=2880 x=(2880*100)/120=Rs 2400 C.P=85% of the 2400 (85*2400)/100=Rs 2040

5.A tradesman gives 4% discount on the marked price and gives article free for buying every 15 articles and thus gains 35%. The marked price is above the cost price by Sol: let the C.P of each article be Rs 100 then C.P of 16 articles=Rs (100*16)=Rs 1600 S.P of 15 articles =1600*(135/100)=Rs 2160 S.P of each article =2160/15=Rs 144 If S.P is Rs 96, marked price =Rs 100 If S.P is Rs 144,marked price =(100/96)*144=Rs 15000 therefore marked price=50% above C.P

6.By selling 33m of cloth ,one gains the selling price of 11m.Find the gain percent?

Sol:

gain=S.P of 33m-C.P of 33m =11m of S.P S.P of 22m=C.P of 33m let C.P of each meter be Rs 1,then C.P of 22m=Rs 22 S.P of 22m=Rs 33 gain=S.P-C.P=33-22=Rs 11 gain%=(gain/C.P)*100 =(11/22)*100=50%

Top
7.The price of a jewel, passing through three hands, rises on the whole by 65%.if the first and second sellers earned 20% and 25% profit respectively,find the percentage profit earned by the third seller? Sol: let the original price of the jewel be Rs P and let the profit earned by the third seller be x% then (100+x)% of 125% of P=165% of P [(100+x)/100]*(125/100)*(120/100)*P=(165/100)*P 100+x=(165*100*100)/(125*120) 100+x=110 x=10%

8.When a producer allows 36% commission on the retail price of his product ,he earns a profit of 8.8%.what would be his profit percent if the commission is reduced by 24% Sol: let retail price =Rs 100 commission=Rs 36 S.P=retail price-commission=100-36=Rs 64 But profit=8.8% C.P=(100*C.P)/(gain+100)=(100*64)/(100+8.8)=Rs 1000/17 new commission=Rs 12 new S.P=100-12=Rs 88 gain=88-(1000/17)=Rs 496/17 gain%=gain*100/C.P =(496*17*100)(17*1000) gain%=49.6%

9.Vikas bought paper sheets for Rs 7200 and spent Rs 200 on transport. Paying Rs 600,he had 330 boxes made,which he sold at Rs 28 each. His profit percentage is Sol: total investments=7200+200+600=Rs 8000 total receipt=330*28=Rs 9240 gain=S.P-C.P =total receipt-total investments gain=9240-8000=Rs 1240 gain% =gain*100/C.P=1240*100/8000=15.5%

10.A person earns 15% on investment but loses 10% on another investment .If the ratio of the two investments be 3:5 ,what is the gain or loss on the two investments taken together? Sol: let the investments be 3x and 5x then total investment=8x total receipt=115% of 3x+90% of 5x

=115*3x/100+90*5x/100=7.95x loss=C.P-S.P=8x-7.95x=0.05x loss%=.05x*100/8x=0.625% 11.The profit earned by selling an article for Rs 900 is double the loss incurred when the same article is sold for Rs 490 .At what price should the article be sold to make 25% profit? Sol: let C.P be Rs x 900-x=2(x-450) 3x=1800 x=Rs 600 C.P=Rs 600 , gain required=25% S.P=(100+gain%)*C.P/100 S.P=(100+25)*600/100=Rs 750

12.If an article is sold at 5% gain instead of 5% loss,the seller gets Rs 6.72 more. The C.P of the article is? Sol: let C.P be Rs x 105% of x-95% of x=6.72 (105/100)*x-(95/100)*x=6.72 x/10=6.72 x=Rs 67.21.

Ratio and Proportions


Important Facts: Ratio: The ratio of two qualities a and b in the same units, is the fraction a/b and we write it as a:b. In the ratio, a:b, we call a as the first term of antecedent and b, the second term consequent. Ex: The ratio 5:9 represents 5/9 with antecedent=5 ,consequent=9 Rule: The multiplication or division of each term of 9 ratio by the same non-zero number does not affect the ratio. Proportion: The equality of two ratios is called proportion. If a:b=c:d, we write a:b::c:d and we say that a,b,c and d are in proportion. Here a and b are called extremes, while b and c are called mean terms. Product of means=product of extremes Thus, a:b::c:d => (b*c)=(a*d) Fourth proportional: If a:b::c:d, then d is called the fourth proportional to a,b and c. Third proportional: If a:b::b:c, then c is called third proportional to a and b. Mean proportional: Mean proportional between a and b is SQRT(a*b). Comparision of Ratios:

We say that (a:b)>(c:d)

=>

(a/b)>(c/d)

Compounded ratio: The compounded ratio of the ratios (a:b), (c:d),(e:f) is (ace:bdf). Duplicate Ratio: If (a:b) is (a2: b2 ) Sub-duplicate ratio of (a:b) is (SQRT(a):SQRT(b)) Triplicate ratio of (a:b) is (a3: b3 )

Sub-triplicate ratio of (a:b) is (a1/3: b1/3 ). If a/b=c/d, then (a+b)/(a-b)=(c+d)/(c-d) (componend o and dividend o) Variation: we say that x is directly proportional to y, if x=ky for some constant k and we write. We say that x is inversely proportional to y, if xy=k for some constant and we write. X is inversely proportional to y. If a/b=c/d=e/f=g/h=k then k=(a+c+e+g)/(b+d+f+h) If a1/b1,a2/b2, a3/b3..............an/bn are unequal fractions then the ratio. a1+a2+a3+..........an/(b1+b2+b3+...............bn) lies between the lowest & the highest of the three fractions.

Top
Simple Problems 1.If a:b =5:9 and b:c=4:7 Find a:b:c? Sol: a:b=5:9 and b:c=4:7=4*9/4:9*4/9=9:63/9 a:b:c=5:9:63/9=20:36:63

2.Find the fourth proportion to 4,9,12 Sol: d is the fourth proportion to a,b,c a:b=c:d 4:9=12:x 4x=9*12=>x=27

3.Find third proportion to 16,36 Sol: If a:b=b:c then c is the third proportion to a,b 16:36=36:x 16x=36*36 x=81 4.Find mean proportion between 0.08 and 0.18 Sol: mean proportion between a and b=square root of ab

mean proportion =square root of 0.08*0.18=0.12 5.If Sol: a:b=2:3 b:c=4:5, c:d=6:7 then a:b:c:d is a:b=2:3 and b:c=4:5=4*3/4:5*3/4=3:15/4 c:d=6:7=6*15/24:7*15/24=15/4:35/8 a:b:c:d=2:3:15/4:35/8=16:24:30:35

6.2A=3B=4C then A:B:C? Sol: let 2A=3B=4C=k then A=k/2, B=k/3, C=k/4 A:B:C=k/2:k/3:k/4=6:4:3

7.15% of x=20% of y then x:y is Sol: (15/100)*x=(20/100)*y 3x=4y x:y=4:3

8.a/3=b/4=c/7 then (a+b+c)/c= Sol: let a/3=b/4=c/7=k (a+b+c)/c=(3k+4k+7k)/7k=2

9.Rs 3650 is divided among 4 engineers, 3 MBAs and 5 CAs such that 3 CAs get as much as 2 MBAs and 3 Engs as much as 2 CAs .Find the share of an MBA. Sol: 4E+3M+5C=3650 3C=2M, that is M=1.5C 3E=2C that is E=.66 C Then, (4*0.66C)+(3*1.5C)+5C=3650 C=3650/12.166 C=300 M=1.5 and C=450.

Top
Difficule Problems 1.Three containers A,B and C are having mixtures of milk and water in the ratio of 1:5 and 3:5 and 5:7 respectively. If the capacities of the containers are in the ratio of all the three containers are in the ratio 5:4:5, find the ratio of milk to water, if the mixtures of all the three containers are mixed together. Sol: Assume that there are 500,400 and 500 liters respectively in the 3 containers. Then ,we have, 83.33, 150 and 208.33 liters of milk in each of the three containers. Thus, the total milk is 441.66 liters. Hence, the amount of water in the mixture is 1400-441.66=958.33liters. Hence, the ratio of milk to water is 441.66:958.33 => 53:115(using division by .3333) The calculation thought process should be (441*2+2):(958*3+1)=1325:2875 Dividing by 25 => 53:115.

2.A certain number of one rupee,fifty parse and twenty five paise coins are in the ratio of 2:5:3:4, add up to Rs 210. How many 50 paise coins were there? Sol: the ratio of 2.5:3:4 can be written as 5:6:8 let us assume that there are 5 one rupee coins,6 fifty paise coins and 8 twenty-five paise coins in all. their value=(5*1)+(6*.50)+(8*.25)=5+3+2=Rs 10 If the total is Rs 10,number of 50 paise coins are 6. if the total is Rs 210, number of 50 paise coins would be 210*6/10=126. 3.The incomes of A and B are in the ratio of 4:3 and their expenditure are in the ratio of 2:1 . if each one saves Rs 1000,what are their incomes? Sol: Ratio of incomes of A and B=4:3 Ratio of expenditures of A and B=2:1 Amount of money saved by A=Amount of money saved by B=Rs 1000 let the incomes of A and B be 4x and 3x respectively let the expense of A and B be 2y and 1yrespectively Amount of money saved by A=(income-expenditure)=4x-2y=Rs 1000 Amount of money saved by B=3x-y=Rs 1000 this can be even written as 6x-2y=Rs 2000 now solve 1 and 3 to get x=Rs 500 therefore income of A=4x=4*500=Rs 2000 income of B=3x=3*500=Rs 1500 4.A sum of Rs 1162 is divided among A,B and C. Such that 4 times A's share share is equal to 5 times B's share and 7 times C's share . What is the share of C? Sol: 4 times of A's share =5 times of B's share=7 times of C's share=1 therefore , the ratio of their share =1/4:1/5:1/7 LCM of 4,5,7=140 therefore, :1/5:1/7=35:28:20 the ratio now can be written as 35:28:20 therefore C's share=(20/83)*1162=20*14=Rs 280. 5.The ratio of the present ages of saritha and her mother is 2:9, mother's age at the time of saritha's birth was 28 years, what is saritha's present age? Sol: ratio of ages of saritha and her mother =2:9 let the present age of saritha be 2x years. then the mother's present age would be 9x years Difference in their ages =28 years 9x-2x=28 years 7x=28=>x=4 therefore saritha's age =2*4=8 years

Partnership

Important Facts: Partnership:When two or more than two persons run a business jointly, they are called partners and the deal is known as partnership. Ratio of Division of Gains: 1.When the investments of all the partners are do the same time, the gain or loss is distributed among the partners in the ratio of their investments. Suppose A and B invest Rs x and Rs y respectively for a year in a business, then at the end of the year: (A's share of profit):(B's share of profit)=x:y 2.When investments are for different time periods, then equivalent capitals are calculated for a unit of time by taking (capital*number of units of time). Now gain or loss is divided in the ratio of these capitals. Suppose A invests Rs x for p months and B invests Rs y for q months, then (A's share of profit):(B's share of profit)=xp:yq 3.Working and sleeping partners:A partner who manages the business is known as working partner and the one who simply invests the money is a sleeping partner. Formulae 1.When investments of A and B are Rs x and Rs y for a year in a business ,then at the end of the year (A's share of profit):(B's share of profit)=x:y 2.When A invests Rs x for p months and B invests Rs y for q months, then A's share profit:B's share of profit=xp:yq Short cuts: 1.In case of 3 A,B,C investments then individual share is to be found then A=16000 , B=32,000 , C=40,000 Sol: A:B:C=16:32:40 =2:4:5` then individual share can be easily known. 2.If business mans A contributes for 5 months and B contributes for 9 months then share of B in the total profit of Rs 26,8000 ,A = Rs 15000, B =Rs 12000 Sol: 15000*5 : 12000*9 25 : 36 for 36 parts=268000*(36/61) =Rs 158.16 Back Difficult problems:

Top

1.P and Q started a business investing Rs 85,000 and Rs 15,000 respectively. In what ratio the profit earned after 2 years be divided between P and Q respectively? Sol: 85,000*2 : 15,000*2 17*2 : 3*2=34:6

2.A,B and C started a business by investing Rs 1,20,000, Rs 1,35,000 and Rs 1,50,000.Find the share of each ,out of an annual profit of Rs 56,700? Sol: Ratio of shares of A,B and C=Ratio of their investments 120,000:135,000:150,000 =8:9:10 A's share=Rs 56,700*(8/27)=Rs 16,800 B's share =Rs 56,700*(9/27)=Rs 18,900 C's share =Rs 56,700*(10/27)=Rs 21,000 3.3 milkman A,B,C rented a pasture A grazed his 45 cows for 12 days B grazed his 36 cows for 15 days and c 60 cows for 10 days.If b's share of rent was Rs 540 What is the total rent? Sol: 45*12:36*15:60*10 =9:9:10 9 parts is equal to Rs 540 then one part is equal to Rs 60 total rent=60*28=Rs 1680

4.Ramu and Krishna entered into a partnership with Rs 50,000 and Rs 60,000, after 4 months Ramu invested Rs 25,000 more while Krishna withdraw Rs 20,000 . Find the share of Ramu in the annual profit of Rs 289,000. Sol: Ramu : Krishna=50,000*4+75,000*8:60,000*4+40,000*8 =10:7 Ramu's annual profit=289000*(10/17)=Rs 170,000 5.A,B,C enter into partnership .A invests 3 times as much as B invests and B invests two third of what C invests. At the end of the year ,the profit earned is Rs 6600. what is the share of B? Sol: let C's capital =Rs x B's capital=Rs (2/3)*x A's capital =3*(2/3)*x=Rs 2x ratio of their capitals=2x:(2/3)*x:x =6x:2x;3x B's share =Rs 6600(2/11)=Rs 1200

6.A,B and C enter into a partnership by investing in the ratio of 3:2:4. After one year ,B invests another Rs 2,70,000 and C,at the end of 2 years, also invests Rs 2,70,000.At the end of 3 years ,profit are shared in the ratio of 3:4:5.Find the initial investment of each? Sol: Initial investments of A,B,c be Rs 3x, Rs 2x, Rs 4x then for 3 years

(3x*36):[(2x*12)+(2x+270000)*24]:[(4x*24)+(4x+270000)*12]=3:4:5 108x:(72x+640,000):(144x+3240000)=3:4:5 108x:72x+6480000:144x+3240000=3:4:5 (108x)/(72x+6480000)=3/4 432x=216x+19440000 216x=19440000 x=Rs 90000 A's initial investment=3x=3*90,000=Rs 2,70,000 B's initial investment=2x=2*90,000=Rs 1,80,000 C's initial investment=4x=4*90,000=Rs 3,60,000

Chain Rule
Important Facts: Direct Proportion: Two Quantities are said to be directly proportional, if on the increase (or decrease) of th one, the other increases(or decreases) to the same extent. Ex:(i) Cost is directly proportional to the number of articles. (More articles, More cost). (ii) Work done is directly proportional to the number of men working on it. (More men, more work). Indirect Proportion: Two Quantities are said to be indirectly proportional,if on the increase of the one , the other decreases to the same extent and vice-versa. Ex:(i) The time taken by a car covering a certain distance is inversely proportional to th speed of the car.(More speed, less is the time taken to cover the distance). (ii) Time taken to finish a work is inversely proportional to the number of persons working at it. (More persons, less is the time taken to finish a job). Nte: In solving Questions by chain rule, we compare every item with the term to be found out. Problems 1)If 15 toys cost Rs.234, what do 35 toys cost ? Sol: Let the required cost be Rs. x then more toys more cost(direct proportion) 15:35:: 234:x (15*x)=(234*35) x=(234*35) /(15)= 546 Rs

2)If 36 men can do a piece of work in 25hours, in how many hours will 15men do it? Sol: Let the required number of hours be x.

less men more hours(Indirect proportion). 15:36::25:x (15*x)=(36*25) x=(36*25) /15 x=60 For 15 men it takes 60 hours. 3)If 9 engines consume 24metric tonnes of coal, when each is working 8 hours a day, how much coal will be required for 8 engines, each running 13 hours a day, it being given that 3 engines of former type consume as much as 4 engines of latter type? Sol: Let 3 engines of former type consume 1 unit in 1 hour. 4 engines of latter type consume 1 unit in 1 hour. 1 engine of former type consumes 1/3 unit in 1 hour. 1 engine of latter type consumes unit in 1 hour. Let required consumption of coal be x units. Less engines, less coal consumed.(direct) More working hours, more coal consumed(direct) Less rate of consumption, less coal consumed (direct) 9:8 8:13 1/3:1/4 :: 24:x

(9*8*(1/3)*x)=(8*13*(1/4)*24) 24x=624 x=26 metric tonnes.

Top
Complex Problems 1)A contract is to be completed in 46 days and 117 men were set to work, each working 8 hours a day. After 33 days, 4/7 of the work is completed. How many additional men may be employed so that the work may be completed in time, each man now working 9 hours a day? Sol: 4/7 of work is completed . Remaining work=1- 4/7 =3/7 Remaining period= 46-33 =13 days Less work, less men(direct proportion) less days, more men(Indirect proportion) More hours/day, less men(Indirect proportion) work 4/7:3/7 Days 13:33 hrs/day 9:8 :: 117:x

(4/7)*13*9*x=(3/7)*33*8*117 x=(3*33*8*117) / (4*13*9) x=198 men So, additional men to be employed=198 -117=81

2)A garrison had provisions for a certain number of days. After 10 days, 1/5 of the men desert and it is found that the provisions will now last just as long as before. How long was that? Sol: Let initially there be x men having food for y days. After, 10 days x men had food for ( y-10)days Also, (x -x/5) men had food for y days. x(y-10)=(4x/5)*y => (x*y) -50x=(4(x*y)/5) 5(x*y)-4(x*y)=50x x*y=50x y=50

3)A contractor undertook to do a certain piece of work in 40 days. He engages 100 men at the beginning and 100 more after 35 days and completes the work in stipulated time. If he had not engaged the additional men, how many days behind schedule would it be finished? Sol: 40 days- 35 days=5 days =>(100*35)+(200*5) men can finish the work in 1 day. 4500 men can finish it in 4500/100= 45 days This s 5 days behind the schedule.

4)12 men and 18 boys,working 7 hors a day, can do a piece if work in 60 days. If a man works equal to 2 boys, then how many boys will be required to help 21 men to do twice the work in 50 days, working 9 hours a day? Sol: 1man =2 boys 12men+18boys=>(12*2+18)boys=42 boys let the required number of boys=x 21 men+x boys =>((21*2)+x) boys =>(42+x) boys less days, more boys(Indirect proportion) more hours per day, less boys(Indirect proportion) days 50:60 hrs/day 9:15/2 :: 42:(42+x) work 1:2 (50*9*1*(42+x))=60*(15/2)*2*42 (42+x)= (60*15*42)/(50*9)= 84 x=84-42= 42 =42 42 days behind the schedule it will be finished.

Time and Work


Important Facts:

1.If A can do a piece of work in n days, then A's 1 day work=1/n 2.If A's 1 day's work=1/n, then A can finish the work in n days. Ex: If A can do a piece of work in 4 days,then A's 1 day's work=1/4. If A's 1 days work=1/5, then A can finish the work in 5 days 3.If A is thrice as good workman as B,then: Ratio of work done by A and B =3:1. Ratio of time taken by A and B to finish a work=1:3 4.Definition of Variation: The change in two different variables follow some definite rule. It said that the two variables vary directly or inversely.Its notation is X/Y=k, where k is called constant. This variation is called direct variation. XY=k. This variation is called inverse variation. 5.Some Pairs of Variables: i)Number of workers and their wages. If the number of workers increases, their total wages increase. If the number of days reduced, there will be less work. If the number of days is increased, there will be more work. Therefore, here we have direct proportion or direct variation. ii)Number workers and days required to do a certain work is an example of inverse variation. If more men are employed, they will require fewer days and if there are less number of workers, more days are required. iii)There is an inverse proportion between the daily hours of a work and the days required. If the number of hours is increased, less number of days are required and if the number of hours is reduced, more days are required. 6.Some Important Tips: More Men -Less More Men -More More Days-More Number of days days work. Days and Work and Work and required Conversely More Conversely More Conversely More to complete the Day-Less Men. Work-More Men. Work-More Days. given work=Total work/One

Since the total work is assumed to be one(unit), the number of days required to complete the given work would be the reciprocal of one days work. Sometimes, the problems on time and work can be solved using the proportional rule ((man*days*hours)/work) in another situation. 7.If men is fixed,work is proportional to time. If work is fixed, then time is inversely proportional to men therefore, (M1*T1/W1)=(M2*T2/W2) Problems 1)If 9 men working 6 hours a day can do a work in 88 days. Then 6 men working 8 hours a day can do it in how many days?

Sol:

From the above formula i.e (m1*t1/w1)=(m2*t2/w2) so (9*6*88/1)=(6*8*d/1) on solving, d=99 days. 2)If 34 men completed 2/5th of a work in 8 days working 9 hours a day. How many more man should be engaged to finish the rest of the work in 6 days working 9 hours a day? Sol: From the above formula i.e (m1*t1/w1)=(m2*t2/w2) so, (34*8*9/(2/5))=(x*6*9/(3/5)) so x=136 men number of men to be added to finish the work=136-34=102

men 3)If 5 women or 8 girls can do a work in 84 days. In how many days can 10 women and 5 girls can do the same work? Sol: Given that 5 women is equal to 8 girls to complete a work so, 10 women=16 girls. Therefore 10women +5girls=16girls+5girls=21girls. 8 girls can do a work in 84 days then 21 girls ---------------? answer= (8*84/21)=32days. Therefore 10 women and 5 girls can a work in 32days

4)Worker A takes 8 hours to do a job. Worker B takes 10hours to do the same job. How long it take both A & B, working together but independently, to do the same job? Sol: A's one hour work=1/8. B's one hour work=1/10 (A+B)'s one hour work=1/8+1/10 =9/40 Both A & B can finish the work in 40/9 days

5)A can finish a work in 18 days and B can do the same work in half the time taken by A. Then, working together, what part of the same work they can finish in a day? Sol: time Given that B alone can complete the same work in days=half the taken by A=9days A's one day work=1/18 B's one day work=1/9 (A+B)'s one day work=1/18+1/9=1/6 6)A is twice as good a workman as B and together they finish a piece of work in 18 days.In how many days will A alone finish the work. Sol: if A takes x days to do a work then B takes 2x days to do the same work =>1/x+1/2x=1/18 =>3/2x=1/18 =>x=27 days. Hence, A alone can finish the work in 27 days.

7)A can do a certain work in 12 days. B is 60% more efficient than A. How many days does B alone take to do the same job? Sol: Ratio of time taken by A&B=160:100 =8:5 Suppose B alone takes x days to do the job. Then, 8:5::12:x => 8x=5*12 => x=15/2 days.

8)A can do a piece of work n 7 days of 9 hours each and B alone can do it in 6 days of 7 hours each. How long will they take to do it working together 8 2/5 hours a day? Sol: A can complete the work in (7*9)=63 days B can complete the work in (6*7)=42 days => A's one hour's work=1/63 and B's one hour work=1/42 (A+B)'s one hour work=1/63+1/42=5/126 Therefore, Both can finish the work in 126/5 hours. Number of days of 8 2/5 hours each=(126*5/(5*42))=3days

9)A takes twice as much time as B or thrice as much time to finish a piece of work. Working together they can finish the work in 2 days. B can do the work alone in ? Sol: the Suppose A,B and C take x,x/2 and x/3 hours respectively finish work then 1/x+2/x+3/x=1/2 => 6/x=1/2 =>x=12 So, B takes 6 hours to finish the work. 10)X can do of a work in 10 days, Y can do 40% of work in 40 days and Z can do 1/3 of work in 13 days. Who will complete the work first? Sol: Whole work will be done by X in 10*4=40 days. Whole work will be done by Y in (40*100/40)=100 days. Whole work will be done by Z in (13*3)=39 days Therefore,Z will complete the work first.

Top
Complex Problems 1)A and B undertake to do a piece of workfor Rs 600.A alone can do it in 6 days while B alone can do it in 8 days. With the help of C, they can finish it in 3 days, Find the share of each? Sol: C's one day's work=(1/3)-(1/6+1/8)=1/24

Therefore, A:B:C= Ratio of their one days work=1/6:1/8:1/24=4:3:1 A's share=Rs (600*4/8)=300 B's share= Rs (600*3/8)=225 C's share=Rs[600-(300+225)]=Rs 75 2)A can do a piece of work in 80 days. He works at it for 10 days & then B alone finishes the remaining work in 42 days. In how much time will A and B, working together, finish the work? Sol: Work done by A in 10 days=10/80=1/8 Remaining work=(1-(1/8))=7/8 Now, work will be done by B in 42 days. Whole work will be done by B in (42*8/7)=48 days Therefore, A's one day's work=1/80 Bs one day's work=1/48 (A+B)'s one day's work=1/80+1/48=8/240=1/30 Hence, both will finish the work in 30 days.

3)P,Q and R are three typists who working simultaneously can type 216 pages in 4 hours In one hour , R can type as many pages more than Q as Q can type more than P. During a period of five hours, R can type as many pages as P can during seven hours. How many pages does each of them type per hour? Sol:Let the number of pages typed in one hour by P, Q and R be x,y and z respectively Then x+y+z=216/4=54 ---------------1 z-y=y-x => 2y=x+z -----------2 5z=7x => x=5x/7 ---------------3 Solving 1,2 and 3 we get x=15,y=18, and z=21 4)Ronald and Elan are working on an assignment. Ronald takes 6 hours to type 32 pages on a computer, while Elan takes 5 hours to type 40 pages. How much time will they take, working together on two different computers to type an assignment of 110 pages? Sol: Number of pages typed Number of pages typed Number of pages typed Time taken by both to by Ronald in one hour=32/6=16/3 by Elan in one hour=40/5=8 by both in one hour=((16/3)+8)=40/3 type 110 pages=110*3/40=8 hours.

5)Two workers A and B are engaged to do a work. A working alone takes 8 hours more to complete the job than if both working together. If B worked alone, he would need 4 1/2 hours more to compete the job than they both working together. What time would they take to do the work together. Sol: (1/(x+8))+(1/(x+(9/2)))=1/x

=>(1/(x+8))+(2/(2x+9))=1/x => x(4x+25)=(x+8)(2x+9) => 2x2 =72 => x2 = 36 => x=6 Therefore, A and B together can do the work in 6 days. 6)A and B can do a work in12 days, B and C in 15 days, C and A in 20 days. If A,B and C work together, they will complete the work in how many days? Sol: (A+B)'s one day's work=1/12; (B+C)'s one day's work=1/15; (A+C)'s one day's work=1/20; Adding we get 2(A+B+C)'s one day's work=1/12+1/15+1/20=12/60=1/5 (A+B+C)'s one day work=1/10 So, A,B,and C together can complete the work in 10 days. 7)A and B can do a work in 8 days, B and C can do the same wor in 12 days. A,B and C together can finish it in 6 days. A and C together will do it in how many days? Sol: (A+B+C)'s one day's work=1/6; (A+B)'s one day's work=1/8; (B+C)'s one day's work=1/12; (A+C)'s one day's work=2(A+B+C)'s one day's work-((A+B)'s work+(B+C)'s one day work) = (2/6)-(1/8+1/12) =(1/3)- (5/24) =3/24 =1/8 So, A and C together will do the work in 8 days.

one day

8)A can do a certain work in the same time in which B and C together can do it. If A and B together could do it in 10 days and C alone in 50 days, then B alone could do it in how many days? Sol: (A+B)'s one day's work=1/10; C's one day's work=1/50 (A+B+C)'s one day's work=(1/10+1/50)=6/50=3/25 Also, A's one day's work=(B+C)s one day's work From i and ii ,we get :2*(A's one day's work)=3/25 => A's one day's work=3/50 B's one days work=(1/10-3/50) =2/50 =1/25 B alone could complete the work in 25 days.

9) A is thrice as good a workman as B and therefore is able to finish a job

in 60 days less than B. Working together, they can do it in: Sol: Ratio of times taken by A and B=1:3. If difference of time is 2 days , B takes 3 days If difference of time is 60 days, B takes (3*60/2)=90 days So, A takes 30 days to do the work=1/90 A's one day's work=1/30; B's one day's work=1/90; (A+B)'s one day's work=1/30+1/90=4/90=2/45 Therefore, A&B together can do the work in 45/2days

Top
10) A can do a piece of work in 80 days. He works at it for 10 days and then B alone finishes the remaining work in 42 days. In how much time will A&B, working together, finish the work? Sol: Work Done by A n 10 days =10/80=1/8 Remaining work =1-1/8=7/8 Now 7/8 work is done by B in 42 days Whole work will be done by B in 42*8/7= 48 days => A's one day's work =1/80 and B's one day's work =1/48 (A+B)'s one day's work = 1/80+1/48 = 8/240 = 1/30 Hence both will finish the work in 30 days.

11) 45 men can complete a work in 16 days. Six days after they started working, so more men joined them. How many days will they now take to complete the remaining work? Sol: M1*D1/W1=M2*D2/W2 =>45*6/(6/16)=75*x/(1-(6/16)) => x=6 days

12)A is 50% as efficient as B. C does half the work done by A&B together. If C alone does the work n 40 days, then A,B and C together can do the work in: Sol: respectively. A's one day's work:B's one days work=150:100 =3:2 Let A's &B's one day's work be 3x and 2x days

Then C's one day's work=5x/2 => 5x/2=1/40 => x=((1/40)*(2/5))=1/100 A's one day's work=3/100 B's one day's work=1/50 C's one day's work=1/40 So, A,B and C can do the work in 13 1/3 days. 13)A can finish a work in 18 days and B can do the same work in 15 days. B

worked for 10 days and left the job. In how many days A alone can finish the remaining work? Sol: B's 10 day's work=10/15=2/3 Remaining work=(1-(2/3))=1/3 Now, 1/18 work is done by A in 1 day. Therefore 1/3 work is done by A in 18*(1/3)=6 days.

14)A can finish a work in 24 days, B n 9 days and C in 12 days. B&C start the work but are forced to leave after 3 days. The remaining work done by A in: Sol: (B+C)'s one day's work=1/9+1/12=7/36 Work done by B & C in 3 days=3*7/36=7/12 Remaining work=1-(7/12)=5/12 Now , 1/24 work is done by A in 1 day. So, 5/12 work is done by A in 24*5/12=10 days

15)X and Y can do a piece of work n 20 days and 12 days respectively. X started the work alone and then after 4 days Y joined him till the completion of work. How long did the work last? Sol: work done by X in 4 days =4/20 =1/5 Remaining work= 1-1/5 =4/5 (X+Y)'s one day's work =1/20+1/12 =8/60=2/15 Now, 2/15 work is done by X and Y in one day. So, 4/5 work will be done by X and Y in 15/2*4/5=6 days Hence Total time taken =(6+4) days = 10 days

16)A does 4/5 of work in 20 days. He then calls in B and they together finish the remaining work in 3 days. How long B alone would take to do the whole work? Sol: Whole work is done by A in 20*5/4=25 days Now, (1-(4/5)) i.e 1/5 work is done by A& B in days. Whole work will be done by A& B in 3*5=15 days =>B's one day's work= 1/15-1/25=4/150=2/75 So, B alone would do the work in 75/2= 37 days.

17) A and B can do a piece of work in 45 days and 40 days respectively. They began to do the work together but A leaves after some days and then B completed the remaining work n 23 days. The number of days after which A left the work was Sol: (A+B)'s one day's work=1/45+1/40=17/360 Work done by B in 23 days=23/40 Remaining work=1-(23/40)=17/40 Now, 17/360 work was done by (A+B) in 1 day. 17/40 work was done by (A+B) in (1*(360/17)*(17/40))= 9 days So, A left after 9 days.

18)A can do a piece of work in 10 days, B in 15 days. They work for 5 days. The rest of work finished by C in 2 days. If they get Rs 1500 for the whole work, the daily wages of B and C are Sol: Part of work done by A= 5/10=1/2 Part of work done by B=1/3 Part of work done by C=(1-(1/2+1/3))=1/6 A's share: B's share: C's share=1/2:1/3:1/6= 3:2:1 A's share=(3/6)*1500=750 B's share=(2/6)*1500=500 C's share=(1/6)*1500=250 A's daily wages=750/5=150/B's daily wages=500/5=100/C's daily wages=250/2=125/Daily wages of B&C = 100+125=225/-

19)A alone can complete a work in 16 days and B alone can complete the same in 12 days. Starting with A, they work on alternate days. The total work will be completed in how many days? (a) 12 days (b) 13 days (c) 13 5/7 days (d)13 days Sol: (A+B)'s 2 days work = 1/16 + 1/12 =7/48 work done in 6 pairs of days =(7/48) * 6 = 7/8 remaining work = 1- 7/8 = 1/8 work done by A on 13th day = 1/16 remaining work = 1/8 1/16 = 1/16 on 14th day, it is Bs turn 1/12 work is done by B in 1 day. 1/16 work is done by B in day. Total time taken= 13 days. So, Answer is: D

Top
20)A,B and C can do a piece of work in 20,30 and 60 days respectively. In how many days can A do the work if he is assisted by B and C on every third day? Sol: A's two day's work=2/20=1/10 (A+B+C)'s one day's work=1/20+1/30+1/60=6/60=1/10 Work done in 3 days=(1/10+1/10)=1/5 Now, 1/5 work is done in 3 days Therefore, Whole work will be done in (3*5)=15 days.

21)Seven men can complete a work in 12 days. They started the work and after 5 days, two men left. In how many days will the work be completed by the remaining men?

(A) 5 (B) 6 (C ) 7 (D) 8 (E) none Sol: 7*12 men complete the work in 1 day. Therefore, 1 man's 1 day's work=1/84 7 men's 5 days work = 5/12 =>remaining work = 1-5/12 = 7/12 5 men's 1 day's work = 5/84 5/84 work is don by them in 1 day 7/12 work is done by them in ((84/5) * (7/12)) = 49/5 days = 9 4/5 days. Ans: E 22).12 men complete a work in 9 days. After they have worked for 6 days, 6 more men joined them. How many days will they take to complete the remaining work? (a) 2 days (b) 3 days (c) 4 days (d) 5days Sol : 1 man's 1 day work = 1/108 12 men's 6 days work = 6/9 = 2/3 remaining work = 1 2/3 = 1/3 18 men's 1 days work = 18/108 = 1/6 1/6 work is done by them in 1 day therefore, 1/3 work is done by them in 6/3 = 2 days. Ans : A

23).A man, a woman and a boy can complete a job in 3,4 and 12 days respectively. How many boys must assist 1 man and 1 woman to complete the job in of a day? (a). 1 (b). 4 (c). 19 (d). 41 Sol : (1 man + 1 woman)'s 1 days work = 1/3+1/4=7/12 Work done by 1 man and 1 women n 1/4 day=((7/12)*(1/4))=7/48 Remaining work= 1- 7/48= 41/48 Work done by 1 boy in day= ((1/12)*(1/4)) =1/48 Therefore, Number of boys required= ((41/48)*48)= 41 days So,Answer: D 24)12 men can complete a piece of work in 4 days, while 15 women can complete the same work in 4 days. 6 men start working on the job and after working for 2 days, all of them stopped working. How many women should be put on the job to complete the remaining work, if it is to be completed in 3 days. (A) 15 (B) 18 (C) 22 (D) data inadequate Sol: one man's one day's work= 1/48 one woman's one day's work=1/60 6 men's 2 day's work=((6/48)*2)= Remaining work=3/4 Now, 1/60 work s done in 1 day by 1 woman.

woman.

So, work will be done in 3 days by (60*(3/4)*(1/3))= 15 So, Answer: A

25)Twelve children take sixteen days to complete a work which can be completed by 8 adults in 12 days. Sixteen adults left and four children joined them. How many days will they take to complete the remaining work? (A) 3 (B) 4 ( C) 6 (D) 8 Sol: one child's one day work= 1/192; one adult's one day's work= 1/96; work done in 3 days=((1/96)*16*3)= 1/2 Remaining work= 1 =1/2 (6 adults+ 4 children)'s 1 day's work= 6/96+4/192= 1/12 1/12 work is done by them in 1 day. work is done by them 12*(1/2)= 6 days So, Answer= C

26)Sixteen men can complete a work in twelve days. Twenty four children can complete the same work in 18 days. 12 men and 8 children started working and after eight days three more children joined them. How many days will they now take to complete the remaining work? (A) 2 days (B) 4 days ( C) 6 days (D) 8 days ol: one man's one day's work= 1/192 one child's one day's work= 1/432 Work done in 8 days=8*(12/192+ 8/432)=8*(1/16+1/54) =35/54 Remaining work= 1 -35/54= 19/54 (12 men+11 children)'s 1 day's work= 12/192 + 11/432 =

19/216

Now, 19/216 work is done by them in 1 day. Therefore, 19/54 work will be done by them in ((216/19)*(19/54))= 4 days So,Answer: B 27)Twenty-four men can complete a work in 16 days. Thirty- two women can complete the same work in twenty-four days. Sixteen men and sixteen women started working and worked for 12 days. How many more men are to be added to complete the remaining work in 2 days? (A) 16 men (B) 24 men ( C) 36 men (D) 48 men Sol: 12*(3/48)=3/4 one man's one day's work= 1/384 one woman's one day's work=1/768 Work done in 12 days= 12*( 16/384 + 16/768) = Remaining work=1 =1/4

(16 men+16 women)'s two day's work =12*( 16/384+16/768)=2/16=1/8 Remaining work = 1/4-1/8 =1/8 1/384 work is done n 1 day by 1 man. Therefore, 1/8 work will be done in 2 days in 384*(1/8)*(1/2)=24men 28)4 men and 6 women can complete a work in 8 days, while 3 men and 7 women can complete it in 10 days. In how many days will 10 women complete it? (A) 35 days (B) 40 days ( C) 45 days (D) 50 days Sol: Let 1 man's 1 day's work =x days and 1 woman's 1 day's work=y Then, 4x+6y=1/8 and 3x+7y=1/10. Solving these two equations, we get: x=11/400 and y= Therefore, 1 woman's 1 day's work=1/400 => 10 women will complete the work in 40 days. Answer: B

1/400

29)One man,3 women and 4 boys can do a piece of work in 96hrs, 2 men and 8 boys can do it in 80 hrs, 2 men & 3 women can do it in 120hr. 5Men & 12 boys can do it in? (A) 39 1/11 hrs (B) 42 7/11 hrs ( C) 43 7/11 days (D) 44hrs Sol: Let 1 man's 1 hour's work=x 1 woman's 1 hour's work=y 1 boy's 1 hour's work=z Then, x+3y+4z=1/96 -----------(1) 2x+8z= 1/80 ----------(2) adding (2) & (3) and subtracting (1) 3x+4z=1/96 ---------(4) From (2) and (4), we get x=1/480 Substituting, we get : y=1/720 and z= 1/960 (5 men+ 12 boy)'s 1 hour's work=5/480+12/960 =1/96 + Therefore, 5 men and 12 boys can do the work in 480/11 or So,Answer: C

1/80=11/480 43 7/11hours.

Pipes and Cisterns


Important Facts: 1.INLET:A pipe connected with a tank or cistern or a reservoir, that fills it, it is known as Inlet. OUTLET:A pipe connected with a tank or a cistern or a reservoir, emptying it, is known as Outlet.

2. i) If a pipe can fill a tank in x hours, then : part filled in 1 hour=1/x. ii)If a pipe can empty a tank in y hours, then : part emptied in 1 hour=1/y. iii)If a pipe can fill a tank in x hours and another pipe can empty the full tank in y hours( where y>x), then on opening both the pipes, the net part filled in 1 hour=(1/x -1/y). iv)If a pipe can fill a tank in x hours and another pipe can empty the full tank in y hours( where x>y), then on opening both the pipes, the net part filled in 1 hour=(1/y -1/x). v) If two pipes A and B can fill a tank in x hours and y hours respectively. If both the pipes are opened simultaneously, part filled by A+B in 1 hour= 1/x +1/y.

To p
Simple Problems 1)Two pipes A& B can fill a tank in 36 hours and 45 hours respectively. If both the pipes are opened simultaneously, how much time will be taken to fill the tank? Sol: Part filled Part filled Part filled Hence, both the by A in 1 hour=1/36 by B in 1 hour= 1/45; by (A+B)'s in 1 hour=1/36 +1/45= 9/180 =1/20 pipes together will fill the tank in 20 hours.

2)Two pipes can fill a tank in 10 hours & 12 hours respectively. While 3rd pipe empties the full tank n 20 hours. If all the three pipes operate simultaneously,in how much time will the tank be filled? Sol: Net part filled in 1 hour=1/10 +1/12 -1/20 =8/60=2/15 The tank be filled in 15/2hours= 7 hrs 30 min

3)A cistern can be filled by a tap in 4 hours while it can be emptied by another tap in 9 hours. If both the taps are opened simultaneously, then after how much time will the cistern get filled? Sol: Net part filled in 1 hour= 1/4 -1/9= 5/36 Therefore the cistern will be filled in 36/5 hours or 7.2 hours.

4)If two pipes function simultaneously, the reservoir will be filled in 12 days.One pipe fills the reservoir 10 hours faster than the other. How many hours does it take the second pipe to fill the reservoir. Sol: => Let the reservoir be filled by the 1st pipe in x hours. The second pipe will fill it in (x+10) hours 1/x + (1/(x+10))= 1/12 (2x+10)/((x)*(x+10))= 1/12

=> x=20 So, the second pipe will take 30 hours to fill the reservoir. 5)A cistern has two taps which fill it in 12 min and 15 min respectively. There is also a waste pipe in the cistern. When all the three are opened, the empty cistern is full in 20 min. How long will the waste pipe take to empty the full cistern? Sol: Work done by a waste pipe in 1 min =1/20 -(1/12+1/15)= -1/10 (-ve means emptying)

6)A tap can fill a tank in 6 hours. After half the tank is filled, three more similar taps are opened. What is the total time taken to fill the tank completely? Sol: Time taken by one tap to fill the half of the tank =3 hours Part filled by the four taps in 1 hour=4/6=2/3 Remaining part=1 -1/2=1/2 Therefore, 2/3:1/2::1:x or x=(1/2)*1*(3/2)=3/4 hours. i.e 45 min So, total time taken= 3hrs 45min.

7)A water tank is two-fifth full. Pipe A can fill a tank in 10 min. And B can empty it in 6 min. If both pipes are open, how long will it take to empty or fill the tank completely ? Sol: Clearly, pipe B is faster than emptied. Part to be emptied=2/5. Part emptied by (A+B) in Therefore, 1/15:2/5::1:x So, the tank be emptied A and So, the tank will be 1 min= 1/6 -1/10=1/15 or x=((2/5)*1*15)=6 min. in 6 min.

8)Bucket P has thrice the capacity as Bucket Q. It takes 60 turns for Bucket P to fill the empty drum. How many turns it will take for both the buckets P&Q, having each turn together to fill the empty drum? Sol: Let the capacity of P be x lit. Then capacity of Q=x/3 lit Capacity of the drum=60x lit Required number of turns= 60x/(x+(x/3))= 60x*3/4x=45

To p
Complex Problems 1)Two pipes can fill a cistern in 14 hours and 16 hours respectively. The

pipes are opened simultaneously and it is found that due to leakage in the bottom it took 32min more to fill the cistern. When the cistern is full, in what time will the leak empty it? Sol: Work done by the two pipes in 1 hour= 1/14+1/16=15/112 Time taken by these two pipes to fill the tank=112/15 hrs. Due to leakage, time taken = 7 hrs 28 min+ 32 min= 8 hours Therefore, work done by (two pipes + leak) in 1 hr= 1/8 work done by leak n 1 hour=15/112 -1/8=1/112 Leak will empty full cistern n 112 hours.

2)Two pipes A&B can fill a tank in 30 min. First, A&B are opened. After 7 min, C also opened. In how much time, the tank s full. Sol: Part filled n 7 min = 7*(1/36+1/45)=7/20 Remaining part= 1-7/20=13/20 Net part filled in 1 min when A,B and C are opened=1/36 +1/451/30=1/60 Now, 1/60 part is filled in 1 min. 13/20 part is filled n (60*13/20)=39 min Total time taken to fill the tank=39+7=46 min 3)Two pipes A&B can fill a tank in 24 min and 32 min respectively. If both the pipes are opened simultaneously, after how much time B should be closed so that the tank is full in 18 min. Sol: Let B be closed after x min, then part filled by (A+B) in x min+ part filled by A in (18-x) min=1 x(1/24+1/32) +(18-x)1/24 =1 => x=8 Hence B must be closed after 8 min.

4)Two pipes A& B together can fill a cistern in 4 hours. Had they been opened separately, then B would have taken 6 hours more than A to fill the cistern. How much time will be taken by A to fill the cistern separately? Sol: Let the cistern be filled by pipe A alone in x hours. Pipe B will fill it in x+6 hours 1/x + 1/x+6=1/4 Solving this we get x=6. Hence, A takes 6 hours to fill the cistern separately.

5)A tank is filled by 3 pipes with uniform flow. The first two pipes operating simultaneously fill the tan in the same time during which the tank is filled by the third pipe alone. The 2nd pipe fills the tank 5 hours faster than first pipe and 4 hours slower than third pipe. The time required by first pipe is : Sol: Suppose, first pipe take x hours to fill the tank then B & C will take (x-5) and (x-9) hours respectively. Therefore, 1/x +1/(x-5) =1/(x-9) On solving, x=15 Hence, time required by first pipe is 15 hours.

To p
6)A large tanker can be filled by two pipes A& B in 60min and 40 min respectively. How many minutes will it take to fill the tanker from empty state if B is used for half the time & A and B fill it together for the other half? Sol: Part filled by (A+B) n 1 min=(1/60 +1/40)=1/24 Suppose the tank is filled in x minutes Then, x/2(1/24+1/40)=1 => (x/2)*(1/15)=1 => x=30 min.

7)Two pipes A and B can fill a tank in 6 hours and 4 hours respectively. If they are opened on alternate hours and if pipe A s opened first, in how many hours, the tank shall be full. Sol: =5/12 (A+B)'s 2 hours work when opened alternatively =1/6+1/4 (A+B)'s 4 hours work when opened alternatively=10/12=5/6 Remaining part=1 -5/6=1/6. Now, it is A's turn and 1/6 part is filled by A in 1 hour. So, total time taken to fill the tank=(4+1)= 5 hours.

8)Three taps A,B and C can fill a tank in 12, 15 and 20 hours respectively. If A is open all the time and B and C are open for one hour each alternatively, the tank will be full in. Sol: (A+B)'s 1 hour's (A+C)'s 1 hour's Part filled in 2 Part filled in 2 Part filled in 6 Remaining part=1 Now, it is the turn of A & hour. Therefore, total work=1/12+1/15=9/60=3/20 work=1/20+1/12=8/60=2/15 hours=3/20+2/15=17/60 hours=3/20+2/15= 17/60 hours=3*17/60 =17/20 -17/20=3/20 B and 3/20 part is filled by A& B in 1 time taken to fill the tank=6+1=7 hours filling as well as for emptying a m3. The emptying capacity of the tank filling capacity and the pump needs 8 than it needs to fill it. What is the

9)A Booster pump can be used for tank. The capacity of the tank is 2400 is 10 m3 per minute higher than its minutes lesser to empty the tank filling capacity of the pump? Sol:

Let, the filling capacity of the pump be x m3/min Then, emptying capacity of the pump=(x+10) m3/min. So,2400/x 2400/(x+10) = 8 on solving x=50.

10)A leak in the bottom of a tank can empty the full tan in 8 hr. An inlet

pipe fills water at the rate of 6 lits a minute. When the tank is full, the inlet is opened and due to the leak, the tank is empty in 12 hrs. How many liters does the cistern hold? Sol: Work done by the inlet in 1 hr= 1/8 -1/12=1/24 Work done by the inlet in i min= (1/24)*(1/60)=1/1440 Therefore, Volume of 1/1440 part=6 lit Volume of whole=(1440*6) lit=8640 lit.

11)Two pipes A and B can fill a cistern in 37 min and 45 minutes respectively. Both the pipes are opened. The cistern will be filled in just half an hour, if the pipe B is turned off after: sol: Let B be turned off after x min. Then, Part filled by (A+B) in x min+ part filled by A in (30-x)min=1 Therefore, x(2/75+1/45)+(30-x)(2/75)=1 11x/225 + (60-2x)/75=1 11x+ 180-6x=225 x=9. So, B must be turned off after 9 minutes.

Time and Distance


Formulae: I)Speed = Distance/Time II)Time = Distance/speed III) Distance = speed*time IV) 1km/hr = 5/18 m/s V)1 m/s = 18/5 Km/hr VI)If the ratio of the speed of A and B is a:b,then the ratio of the time taken by them to cover the same distance is 1/a : 1/b or b:a VII) suppose a man covers a distance at x kmph and an equal distance at y kmph.then the average speed during the whole journey is (2xy/x+y)kmph Problems 1)A person covers a certain distance at 72kmph .How many meters does he cover in 2 minutes. Solution:: speed=72kmph=72*5/18 = 20m/s distance covered in 2min =20*2*60 = 2400m 2)If a man runs at 3m/s. How many km does he run in 1hr 40min

Solution:: speed of the man = 3*18/5 kmph = 54/5kmph Distance covered in 5/3 hrs=54/5*5/3 = 18km 3)Walking at the rate of 4knph a man covers certain distance in 2hr 45 min. Running at a speed of 16.5 kmph the man will cover the same distance in. Solution:: Distance=Speed* time 4*11/4=11km New speed =16.5kmph therefore Time=D/S=11/16.5 = 40min

Top
Complex Problems 1)A train covers a distance in 50 min ,if it runs at a speed of 48kmph on an average.The speed at which the train must run to reduce the time of journey to 40min will be. Solution:: Time=50/60 hr=5/6hr Speed=48mph distance=S*T=48*5/6=40km time=40/60hr=2/3hr New speed = 40* 3/2 kmph= 60kmph 2)Vikas can cover a distance in 1hr 24min by covering 2/3 of the distance at 4 kmph and the rest at 5kmph.the total distance is? Solution:: Let total distance be S total time=1hr24min A to T :: speed=4kmph diistance=2/3S T to S :: speed=5km distance=1-2/3S=1/3S 21/15 hr=2/3 S/4 + 1/3s /5 84=14/3S*3 S=84*3/14*3 = 6km 3)walking at of his usual speed ,a man is late by 2 hr. the usual time is. Solution:: Usual speed = S Usual time = T Distance = D New Speed is S New time is 4/3 T 4/3 T T = 5/2 T=15/2 = 7

4)A man covers a distance on scooter .had he moved 3kmph faster he would have taken 40 min less. If he had moved 2kmph slower he would have taken 40min more.the distance is. Solution:: Let distance = x m Usual rate = y kmph x/y x/y+3 = 40/60 hr 2y(y+3) = 9x --------------1 x/y-2 x/y = 40/60 hr y(y-2) = 3x -----------------2 divide 1 & 2 equations by solving we get x = 40 5)Excluding stoppages,the speed of the bus is 54kmph and including stoppages,it is 45kmph.for how many min does the bus stop per hr. Solution:: Due to stoppages,it covers 9km less. time taken to cover 9 km is [9/54 *60] min = 10min 6)Two boys starting from the same place walk at a rate of 5kmph and 5.5kmph respectively.wht time will they take to be 8.5km apart, if they walk in the same direction Solution:: The relative speed of the boys = 5.5kmph 5kmph = 0.5 kmph Distance between them is 8.5 km Time= 8.5km / 0.5 kmph = 17 hrs 7)2 trains starting at the same time from 2 stations 200km apart and going in opposite direction cross each other ata distance of 110km from one of the stations.what is the ratio of their speeds. Solution:: In same time ,they cover 110km & 90 km respectively so ratio of their speed =110:90 = 11:9 8)Two trains start from A & B and travel towards each other at speed of 50kmph and 60kmph resp. At the time of the meeting the second train has traveled 120km more than the first.the distance between them. Solution:: Let the distance traveled by the first train be x km then distance covered by the second train is x + 120km x/50 = x+120 / 60 x= 600 so the distance between A & B is x + x + 120 = 1320 km 9)A thief steals a ca r at 2.30pm and drives it at 60kmph.the theft is discovered at 3pm and the owner sets off in another car at 75kmph when will he overtake the thief

Solution:: Let the thief is overtaken x hrs after 2.30pm distance covered by the thief in x hrs = distance covered by the owner in x-1/2 hr 60x = 75 ( x- ) x= 5/2 hr thief is overtaken at 2.30 pm + 2 hr = 5 pm 10)In covering distance,the speed of A & B are in the ratio of 3:4.A takes 30min more than B to reach the destion.The time taken by A to reach the destinstion is. Solution:: Ratio of speed = 3:4 Ratio of time = 4:3 let A takes 4x hrs,B takes 3x hrs then 4x-3x = 30/60 hr x = hr Time taken by A to reach the destination is 4x = 4 * = 2 hr 11)A motorist covers a distance of 39km in 45min by moving at a speed of xkmph for the first 15min.then moving at double the speed for the next 20 min and then again moving at his original speed for the rest of the journey .then x=? Solution:: Total distance = 39 km Total time = 45 min D = S*T x * 15/60 + 2x * 20/60 + x * 10/60 = 39 km x = 36 kmph 12)A & B are two towns.Mr.Fara covers the distance from A t0 B on cycle at 17kmph and returns to A by a tonga running at a uniform speed of 8kmph.his average speed during the whole journey is. Solution:: When same distance is covered with different speeds,then the average speed = 2xy / x+y =10.88kmph 13)A car covers 4 successive 3km stretches at speed of 10kmph,20kmph,30kmph&:60kmph resp. Its average speed is. Solution:: Average speed = total distance / total time total distance = 4 * 3 = 12 km total time = 3/10 + 3/20 + 3/30 + 3/60 = 36/60 hr speed =12/36 * 60 = 20 kmph

Top
14)A person walks at 5kmph for 6hr and at 4kmph for 12hr. The average speed is. Solution:: avg speed = total distance/total time

= 5*6 + 4*12 / 18 =4 1/3 mph 15)A bullock cart has to cover a distance of 80km in 10hrs. If it covers half of the journeyin 3/5th time.wht should be its speed to cover the remaining distance in the time left. Solution:: Time left = 10 - 3/5*10 = 4 hr speed =40 km /4 hr =10 kmph 16)The ratio between the speeds of the A& B is 2:3 an therefore A takes 10 min more than the time taken by B to reach the destination.If A had walked at double the speed ,he would have covered the distance in ? Solution:: Ratio of speed = 2:3 Ratio of time = 3:2 A takes 10 min more 3x-2x = 10 min A's time=30 min --->A covers the distance in 30 min ,if its speed is x -> He will cover the same distance in 15 min,if its speed doubles (i.e 2x) 17)A is twice as fast as B and B is thrice as fast as C is. The journey covered by B in? Solution:: speed's ratio a : b = 2: 1 b : c = 3:1 Time's ratio b : c = 1:3 b : c = 18:54 (if c covers in 54 min i..e twice to 18 min ) 18)A man performed 3/5 of the total journey by ratio 17/20 by bus and the remaining 65km on foot.wht is his total journey. Solution:: Let total distance is x x-(3/5x + 17/20 x) =6.5 x- 19x/20 = 6.5 x=20 * 6.5 =130 km 19)A train M leaves Meerat at 5 am and reaches Delhi at 9am . Another train N leaves Delhi at 7am and reaches Meerut at 1030am At what time do the 2 trains cross one another Solution:: Let the distance between Meerut & Delhi be x they meet after y hr after 7am

M covers x in 4hr N covers x in 3 i.e 7/2 hr speed of M =x/4 speed of N = 2x/7 Distance covered by M in y+2 hr + Distance covered by N in y hr is x x/4 (y+2) +2x/7(y)=x y=14/15hr or 56 min 20)A man takes 5hr 45min in walking to certain place and riding back. He would have gained 2hrs by riding both ways.The time he would take to walk both ways is? Solution:: Let x be the speed of walked Let y be the speed of ride Let D be the distance Then D/x + D/y = 23/4 hr -------1 D/y + D/y = 23/4 2 hr D/y = 15/8 --------2 substitute 2 in 1 D/x + 15/8 = 23/4 D/x = 23/4 -15/8 =46-15/8 =31/8 Time taken for walk one way is 31/8 hr time taken to walk to and fro is 2*31/8 = 31/4 hr =7 hr 45 min

Trains
General Concept: (1) Time taken by a train x mt long in passing a signal post or a pole or a standing man = time taken by the train to cover x mt (2) Time taken by a train x mt long in passing a stationary object of length y mt = time taken by the train to cover x+y mt (3) Suppose two trains or two bodies are moving in the same direction at u kmph and v kmph such that u > v then their relative speed is u-v kmph (4)If two trains of length x km and y km are moving in opposite diredtions at u kmph and vmph,then time taken by the train to cross each other = (x+y)/(u+v) hr (5) Suppose two trains or two bdies are moving in opposite direction at u kmph and v kmph then,their relative speed = (u+v) kmph (6)If two train start at the same time from 2 points A & B towards each other and after crossing they take a & b hours in reaching B & A respectively then A's speed : B's speed = (b^1/2 : a^1/2 )

Problems (1)Find the time taken by a train 180m long,running at 72kmph in crossing an electric pole Solution: Speed of the train =72*5/18m/s =20 m/s Distance move din passing the pole = 180m Requiredtime = 180/20 = 9 seconds

(2)A train 140 m long running at 60kmph.In how much time will it pass a platform 260m long. Solution: Distance travelled =140 + 260 m =400 m, speed = 60 * 5/18 = 50//3 m time=400*3 / 50 = 24 Seconds (3)A man is standing on a railway bridge which is 180 m.He finds that a train crosses the bridge in 20 seconds but himself in 8 sec. Find the length of the train and its sppeed Solution: i)D=180+x ii)D=x T = 20 seconds S= 180+x / 20 ------------ 1

T=8 seconds D=ST x=8S ------------- 2 Substitute 2 in 1 S=180 + 8 S / 20 S=15 m/s Length of the train,x is 8 *15 = 120 m (4)A train 150m long is running with a speed of 68 mphIn wht time will it pass a man who is running at a speed of 8kmph in the same direction in which the train is going Solution: Relative Speed = 68-8=60kmph*5/18 = 50/3 m/s time= 150 * 3 /50 =9sec 5)A train 220m long is running with a speed of 59 k mph /..In what time will it pass a man who is running at 7 kmph in the direction opposite to that in which train is going. Solution: Relative Speed = 59+7=66kmph*5/18 = 55/3 m/s time= 220/55 * 3 =12sec

Top
(6)Two trains 137m and 163m in length are running towards each other on parallel lines,one at the rate of 42kmph & another at 48 mph.In wht time will they be clear of each other from the

moment they meet. Solution: Relative speed =42+48 = 90 *5/18 = 25m/s time taken by the train to pass each other = time taken to cover (137+163)m at 25 m/s = 300 /25 s =12 s

(7)A train running at 54 kmph takes 20 sec to pass a platform. Next it takes 12 sec to pass a man walking at 6kmph in the same direction in which the train is going.Find length of the train and length of platform Solution: Relative speed w.r.t man = 54-6=48kmph the length of the train is 48 * 5/18 * 12 =160m time taken to pass platform =20 sec Speed of the train = 54 * 5/18 =15m/s 160+x =20 *15 x=140m length of the platform is 140m (8)A man sitting in a train which is travelling at 50mph observes that a goods train travelling in opposite irection takes 9 sec to pass him .If the goos train is 150m long fin its speed Solution: Relative speed =150/9 m/s =60 mph speed of the train = 60-50 =10kmph (9)Two trains are moving in the sam e direction at 65kmph and 45kmph. The faster train crosses a man in slower train in18sec.the length of the faster train is Solution: Relative speed =65-45 kmph = 50/9 m/s Distancce covered in18 s =50/9 * 18 = 100m the length of the train is 100m

(10)Atrain overtakes two persons who are walking in the same direction in which the train is going at the rate of 2kmph an 4kmph and passes them completely in 9 sec an 10 sec respectively. The length of train is Solution: 2kmph = 5/9 m/s 4 mph =10/9 m/s Let the length of the trainbe x meters and its speed is y m/s then x / (y- 5/9) = 9 and x / (y- 10/9) = 10 9y-5 =x and 10(9y-10)=9x 9y-x=5 and 90y-9x=100 on solving we get x=50,lenght of trains

(11) Two stations A & B are 110 km apart on a straight line. One train starts from A at 7am and travels towards B at 20kmph. Another train starts from B at 8am an travels toward A at a speed of 25kmph.At what time will they meet

Solution: Suppose the train meet x hr after 7am Distance covered by A in x hr=20x km 20x+25(x-1) = 110 45x=135 x=3 So they meet at 10 am (12)A traintravelling at 48kmph completely crosses another train having half its length an travelling inopposite direction at 42kmph in12 sec.It also passes a railway platform in 45sec.the length of platform is Solution: Let the length of the first train be x mt then,the length of second train is x/2 mt relative speed = 48+42 kmph =90 * 5/18 m/s = 25m/s (x+ x/2)/25 =12 x=200 Length of the train is 200m Let the length of the platform be y mt speed f the first train = 48*5/18 m/s = 40/3 m/s 200+y * 3/40 = 45 y=400m

Top
(13)The length of a running trsain in 30% more than the length of another train B runnng in the opposite direction.To find out the speed of trtain B,which of the following information given in the statements P & Q is sufficient P : The speed of train A is 80 kmph Q : They too 90 sec to cross each other (a) Either P & Q is sufficient (b)Both P & Q are not sufficient (c)only Q is sufficient (d)Both P & Q are neeed Ans: B Solution: Let the length of th e train A be x mt Length of the train B = 130/100 x mt =13x/10 mt Let the speed of B be y mph,speed of the train A=80mph relative speed= y+80 * 5/18 m/s time taken by the trains t cross each other is gven by 90 = (x + 13x/10)/ (5y+400 / 18) to find y,clearly xis also needed so,both P & Q are not sufficient 40% more than then the speed opposite direction.To fin out given in statements P & Q is in 6 seconds of the trains is 26kmph

(14)The speed of a train A,100m long is of another train B,180m long running in the speed of B,which of the information sufficient P :The two trains crossed each other Q : The difference between the spee (a)Only P is sufficient

(b)Only Q is sufficient (c)Both P & Q are needed (d)Both P & Q are not sufficient Ans : A Solution: Let speed of B be x kmph then,speed of A =140x/100 kmph =7x/5 mph relative speed = x + 7x/5 =2x/3 m/s time taken to cross each other = (100+180)*3/2x s =420/x s now,420/x = 6 x=70 mph thus,only P is sufficient (15)The train running at certain speed crosses astationary enginein 20 seconds.to find out the sped of the train,which of the following information is necessary (a)Only the length of the train (b)only the length of the engine (c)Either the length of the train or length of engine (d)Both the length of the train or length of engine Ans : D Solution: Since the sum of lengths of the tran and the engine is needed, so both the length must be known

Boats and Streams


Important facts: 1)In water, the direction along the stream is called down stream. 2)Direction against the stream is called upstream. 3)The speed of boat in still water is U km/hr and the speed of stream is V km/hr then speed down stream =U + V km/hr speed up stream = U V km/hr Formulae: If the speed down stream is A km/hr and the speed up stream is B km/hr then speed in still water = (A+B) km/hr rate of stream =1/2(A-B) km/hr Problems:

1. In one hour a boat goes 11 km long the stream and 5 km against the stream. The speed of the boat in still water is? Sol: Speed in still water = ( 11+5) km/hr= 8 kmph 2.A man can row 18 kmph in still water. It takes him thrice as long as row up as to row down the river. find the rate of stream. Sol: Let man's rate up stream be xkmph then, in still water =1/2[3x+x]=2x kmph so, 2x= 18, x=9 rate upstream =9kmph rate downstream =27 kmph rate of stream = [27-9] = 9kmph

3.A man can row 71/2kmph in still watre . if in a river running at 1.5 km an hour, if takes him 50 min to row to place and back. how far off is the place? Sol: speed down stream =7.5+1.5=9kmph speed upstream =7.5-1.5=6kmph let the required distence x km. then , x/9+x/6=50/60 = 2x+3x= 5/6*18 5x=15, x=3 Hence, the required distence is 3 km

4.A man can row 3 quarters of a km aganist the stream is 111/4 min. the speed of the man in still water is ? Sol: rate upstream = 750/625 m/sec =10/9 m/sec rate downstream =750/450 m/sec = 5/3 m/sec rate in still water =1/2[10/9+5/3] = 25/18 m/sec = 25/18*18/5=5 kmph 5.A boat can travel with a speed of 13 kmph in still water. if the speed of stream is 4 kmph,find the time taken by the boat to go 68 km downstream? Sol: Speed down stream = 13+4= 17 kmph time taken to travel 68km downstream =68/17 hrs = 4 hrs

Top
6.A boat takes 90 min less to travel 36 miles downstream then to travel the same distence upstream. if the speed of the boat in still water is 10 mph . The speed of the stream is : Sol: Let the speed of the stream be x mph . then, speed downstream = [10+x]mph speed upstream =[10-x] mph 36/[10+x] - 36/[10-x] = 90/60 =72x*60= 90[100-x2] (x+50)(x-2) =0 x=2 kmph

7.At his usual rowing rate, Rahul 12 miles down stream in a certain river in 6 hrs less than it takes him to travel the same distence upstream. but if he could double his usual rowing rate for his 24 miles roundthe down stream 12 miles would then take only one hour less than the up stream 12 miles. what is the speed of the current in miles per hours? Sol: Let the speed in still water be x mph and the speed of the curren be y mph. then, speed upstream = (x-y) speed downstream =(x+y) 12/(x-y) - 12/(x+y) = 6 6(x2 y2) m= 2xy => x2 y2 =4y -(1) and 12/(2x-y) - 12/(2x+y) =1 => 4x2 y2 = 24y x2= ( 24y + y2)/4 -->(2) from 1 and 2 we have 4y+ y2 =( 24y+y2)/4 y=8/3 mph y= 22/3 mph 8.There is a road beside a river. two friends started from a place A, moved to a temple situated at another place B and then returned to A again. one of them moves on a cycle at a speed of 12 kmph, while the other sails on a boat at a speed of 10 kmph . if the river flows at the speedof 4 kmph, which of the two friends will return to place A first ? Sol: Clearly, The cyclist moves both ways at a speed of 12 kmph so, average speed of the cyclist = 12 kmph the boat sailor moves downstream = (10+4) = 14 kmph upstream =(10-4) = 6 kmph So, average speed of the boat sailor =[ 2*14*6]/[14+6] kmph =42/5 kmph =8.4 kmph Since, the average speed of the cyclist is greater, he will return to A first. 9.A boat takes 19 hrs for travelling downstream from point A to point B. and coming back to a point C midway between A and B. if the velocity of the sream is 4 kmph. and the speed of the boat in still water is 14 kmph. what is the distence between A and B? Sol: speed downstream =14+4 =18 kmph speed upstream = 14 -4 = 10 kmph let the distence between A and B be x km. then, x/18 + (x/2)/10 = 19 x/18 + x/20 =19 19x/180 =19 =>x = 180km Hence, the distence between A and B bw 180 km

Alligation or Mixtures

Important Facts and Formulae: 1.Allegation:It is the rule that enables us to find the ratio in which two of more ingredients at the given price must be mixed to produce a mixture of a desired price. 2.Mean Price:The cost price of a unit quantity of the mixture is called the mean price. 3.Rule of Allegation:If two ingredients are mixed then Quantity of Cheaper / Quantity of Dearer = (C.P of Dearer Mean Price) /(Mean PriceC.P of Cheaper). C.P of a unit quantity of cheaper(c) C.P of unit quantity of dearer(d) Mean Price(m) (d-m) (m-c)

Cheaper quantity:Dearer quantity = (d-m):(m-c) 4.Suppose a container contains x units of liquid from which y units are taken out and replaced by water. After n operations the quantity of pure liquid = x (1 y/x)n units. Simple Problems 1.In what ratio must rice at Rs 9.30 per Kg be mixed with rice at Rs 10.80 per Kg so that the mixture be worth Rs 10 per Kg? Solution: C.P of 1 Kg rice of 1st kind 930 p C.P of 1 Kg rice of 2n d kind 1080p Mean Price 1000p 80 70 Required ratio=80:70 = 8:7 2.How much water must be added to 60 liters of milk at 11/2 liters for Rs 20 so as to have a mixture worth Rs 10 2/3 a liter? Solution: C.P of 1 lit of milk = 20*2/3 = 40/3 C.P of 1 lit of water 0 C.P of 1 lit of milk 40/3 Mean Price 32/3 8/3 32/3 Ratio of water and milk =8/3 : 32/3 = 1:4 Quantity of water to be added to 60 lit of milk =1/4*60=15 liters. 3.In what ratio must water to be mixed with milk to gain 20% by selling the mixture at cost price?

Solution:Let the C.P of milk be Re 1 per liter Then S.P of 1 liter of mixture = Re.1 Gain obtained =20%. Therefore C.P of 1 liter mixture = Rs(100/120*1) =5/6 C.P of 1 liter of water 0 C.P of 1 liter of milk1 Mean Price 5/6 1/6 5/6

Ratio of water and milk =1/6 : 5/6 = 1:5. 4.In what ratio must a grocer mix two varieties of pulses costing Rs 15 and Rs 20 per Kg respectively so as to get a mixture worth Rs 16.50 per Kg? Solution: Cost of 1 Kg pulses of 1 kind 15 Cost of 1 Kg pulses of 2nd kind 20 Mean Price Rs 16.50 3.50 Required ratio =3.50 : 1.50 = 35:15 = 7:3. 1.50

5. 4Kg s of rice at Rs 5 per Kg is mixed with 8 Kg of rice at Rs 6 per Kg .Find the average price of the mixture? Solution: rice of 5 Rs per Kg rice of 6 Rs per Kg Average price Aw 6-Aw Aw-5 (6-Aw)/(Aw-5) = 4/8 =1/2 12-2Aw = Aw-5 3Aw = 17 Aw = 5.66 per Kg.

Top
6.5Kg of rice at Rs 6 per Kg is mixed with 4 Kg of rice to get a mixture costing Rs 7 per Kg. Find the price of the costlier rice? Solution: Using the cross method:

rice at Rs 6 per Kg rice at Rs x per Kg Mean price Rs 7 per Kg 5 4 x-7:1=5:4 4x-28 = 5 4x=33=>x=Rs 8.25. Therefore price of costlier rice is Rs 8.25 per Kg Medium Problems 1.A butler stole wine from a butt of sherry which contained 40% of spirit and he replaced,what he had stolen by wine containing only 16% spirit. The butt was then of 24% strength only. How much of the butt did he steal?

Solution: Wine containing 40%spirit Wine containing 16% spirit Wine containing 24% spirit 8 16 They must be mixed in the ratio of =1:2. Thus 1/3 of the butt of sherry was left and hence the butler drew out 2/3 of the butt. 2.The average weekly salary per head of the entire staff of a factory consisting of supervisors and the laborers is Rs 60.The average salary per head of the supervisors is Rs 400 and that of the laborers is Rs 56.Given that the number of supervisors is 12.Find the number of laborers in the factory. Solution: Average salary of laborer Rs 56 Average salary of supervisors Rs 400 Average salary of entire staff Rs 60 340 4 Number of laborer / Number of Supervisors = 340 / 4=85/1 Thus,if the number of supervisors is 1,number of laborers =85. Therefore if the number of supervisors is 12 number of laborers 85*12=1020. 3.The cost of type 1 rice is Rs 15 per Kg and type 2 rice is Rs 20 per Kg. If both type1 and type 2 are mixed in the ratio of 2:3,then the price per Kg of the mixed variety of rice is? Solution:Let the price of the mixed variety be Rs x per Kg. Cost of 1 Kg of type 1 rice Rs 15 Cost of 1 Kg of type 2 rice Rs 20 Mean Price Rs x 20-x x-15 (20-x) /( x-15) = 2/3 => 60-3x = 2x-30 5x = 90=>x=18. 4.In what ratio must a grocer mix two varieties of tea worth Rs 60 a Kg and Rs 65 a Kg so that by selling the mixture at Rs 68.20 a Kg he may gain 10%? Solution:S.P of 1 Kg of the mixture = Rs 68.20,gain =10% S.P of 1 Kg of the mixture = Rs (100/110*68.20)=Rs 62. Cost of 1 Kg tea of 1st kind 60 Cost of 1 Kg tea of 2nd kind 65 Mean Price Rs 62 3 2 Required ratio =3:2. 5.A dishonest milkman professes to sell his milk at cost price but he mixes t with water and there by gains 25% .The percentage of water in the mixture is?

Solution:Let C. P of 1 liter milk be Re 1. Then S.P of 1 liter mixture=Re 1. Gain=25% C.P of 1 liter mixture =Re(100/125*1) = Re 4/5. C.P of 1 liter milk Re 1 C.P of 1 liter of water 0 Mean Price 4/5 4/5 1/5 Ratio of milk to water =4/5 : 1/5 = 4:1 Hence percentage of water n the mixture=1/5*100=20%. 12.A merchant has 1000Kg of sugar,part of which he sells at 8% profit and the rest at 18% profit. He gains 14% on the whole. The quantity sold at 18% profit is? Solution: Profit on 1st part 8% Profit on 2nd part 18% Mean Profit 14% 4 6 Ratio of 1st and 2nd parts =4:6 =2:3. Quantity of 2nd ind =3/5*1000Kg =600 Kg. 6.A jar full of whiskey contains 40% alcohol. A part of this whiskey is replaced by another containing 19% alcohol and now the percentage of alcohol was found to be 26%. The quantity of whiskey replaced is? Solution: Strength of first jar 40% Strength of 2nd jar 19% Mean Strength 26% 7 14 So,ratio of 1st and 2nd quantities =7:14 =1:2 Therefore required quantity replaced =2/3. 7.A container contains 40lit of milk. From this container 4 lit of milk was taken out and replaced by water. This process was repeated further two times. How much milk is now contained by the container? Solution:Amount of milk left after 3 operations = 40(1-4/40)3lit =(40*9/10*9/10*9/10) = 29.16 lit

Top
Complex Problems 1.Tea worth Rs 126 per Kg are mixed with a third variety in the ratio 1:1:2. If the mixture is worth Rs 153 per Kg , the price of the third variety per Kg will be? Solution: Since First and second varieties are mixed in equal proportions so their average price =Rs (126+135)/2 = 130.50. So the mixture is formed by mixing two varieties ,one at Rs 130.50 per Kg and the other at say Rs x per Kg in the ratio 2:2 i e,1:1 we have to find x. Costof 1Kg tea of 1st kind RS 130.50 Costof 1Kg tea of 2n d kind Rs x. Mean Price Rs 153

x-153 22.50 (x=153)/22.5 = 1 =>x-153 = 22.5 x = 175.50. Price of the third variety =Rs 175.50 per Kg. 2.The milk and water in two vessels A and B are in the ratio 4:3 and 2:3 respectively. In what ratio the liquids in both the vessels be mixed to obtain a new mixture in vessel c consisting half milk and half water? Solution:Let the C.P of milk be Re 1 per liter. Milk in 1 liter mixture of A = 4/7 liter. Milk in 1 liter mixture of B = 2/5 liter. Milk in 1 liter mixture of C = 1/2 liter. C.P of 1 liter mixture in A=Re 4/7 C.P of 1 liter mixture in B=Re 2/5. Mean Price = Re 1/2. By rule of allegation we have: C.P of 1 liter mixture in A C.P of 1 liter mixture in B 4/7 2/5 Mean Price 1/10 1/14 Required ratio = 1/10 : 1/14 = 7:5. 3.How many Kg s of wheat costing him Rs 1.20,Rs 1.44 and Rs 1.74 per Kg so that the mixture may be worth Rs 1.41 per Kg? Solution: Step1:Mix wheat of first and third kind to get a mixture worth Rs 1.41 per Kg. C.P of 1 Kg wheat of 1st kind 120p C.P of 1 Kg wheat of 3rd kind 174p Mean Price 141p 33 21 They must be mixed in the ratio =33:21 = 11:7 Step2:Mix wheats of 1st and 2n d kind to obtain a mixture worth of 1.41.per Kg. C.P of 1 Kg wheat of 1st kind 120p C.P of 1 Kg wheat of 2n d kind 144p Mean Price 141p 3 21 They must be mixed in the ratio = 3:21=1:7. Thus,Quantity of 2n d kind of wheat / Quantity of 3rd kind of wheat = 7/1*11/7= 11/1 Quantities of wheat of 1st :2n d:3rd = 11:77:7. 4.Two vessels A and B contain spirit and water mixed in the ratio 5:2 and 7:6 respectively. Find the ratio n which these mixture be mixed to obtain a new mixture in vessel c containing spirit and water in the ratio 8:5? Solution:Let the C.P of spirit be Re 1 per liter. Spirit in 1 liter mix of A = 5/7 liter. C.P of 1 liter mix in A =5/7. Spirit in 1 liter mix of B = 7/13 liter.

C.P of 1 liter mix in B =7/13. Spirit in 1 liter mix of C = 8/13 liter. C.P of 1 liter mix in C =8/13. C.P of 1 liter mixture in A 5/7 C.P of 1 liter mixture in B 7/13 Mean Price 8/13 1/13 9/91 Therefore required ratio = 1/13 : 9/91 = 7:9.

Top
5.A milk vendor has 2 cans of milk .The first contains 5% water and the rest milk. The second contains 50% water. How much milk should he mix from each of the container so as to get 12 liters of milk such that the ratio of water to milk is 3:5? Solution:Let cost of 1 liter milk be Re 1. Milk in 1 liter mixture in 1st can = 3/4 lit. C.P of 1 liter mixture in 1st can =Re 3/4 Milk in 1 liter mixture in 2n d can = 1/2 lit. C.P of 1 liter mixture in 2n d can =Re 1/2 Milk in 1 liter final mixture = 5/8 lit. Mean Price = Re 5/8. C.P of 1 lt mix in 1st Re3/4 C.P of 1 lt mix in 2nd Re1/2 Mean Price 5/8 1/8 1/8 There ratio of two mixtures =1/8 :1/8 = 1:1. So,quantity of mixture taken from each can=1/2*12 = 6 liters. 6.One quantity of wheat at Rs 9.30 p er Kg are mixed with another quality at a certain rate in the ratio 8:7. If the mixture so formed be worth Rs 10 per Kg ,what is the rate per Kg of the second quality of wheat? Solution:Let the rate of second quality be Rs x per Kg. C.P of 1Kg wheat of 1st 980p C.P of 1 Kg wheat of 2nd 100x p Mean Price 1000p 100x-1000p 70 p (100x-1000) / 70 = 8/7 700x -7000 = 560 700x = 7560 =>x = Rs 10.80. Therefore the rate of second quality is Rs10.80 7.8lit are drawn from a wine and is then filled with water. This operation is performed three more times.The ratio of the quantity of wine now left in cask to that of the water is 16:81. How much wine did the cask hold originally? Solution: Let the quantity of the wine in the cask originally be x liters. Then quantity of wine left in cask after 4 operations = x(1- 8/x)4lit. Therefore x((1-(8/x))4)/x = 16/81. (1- 8/x)4=(2/3) 4 (x- 8)/x=2/3 3x-24 =2x

x=24. 8.A can contains a mixture of two liquids A and B in the ratio 7:5 when 9 liters of mixture are drawn off and the can is filled with B,the ratio of A and B becomes 7:9. How many liters of liquid A was contained by the can initially? Solution: Suppose the can initially contains 7x and 5x liters of mixtures A and B respectively . Quantity of A in mixture left = (7x- (7/12)*9 )lit = 7x - (21/4) liters. Quantity of B in mixture left = 5x - 5/12*9 = 5x - (15/4) liters Therefore (7x 21/4)/ (5x 15/4+9)=7/9 (28x-21)/(20x +21)= 7/9 (252x -189)= 140x +147 112x = 336 => x=3. So the can contains 21 liters of A. 9.A vessel is filled with liquid,3 parts of which are water and 5 parts syrup. How much of the mixture must be drawn off and replaced with water so that the mixture may be half water and half syrup? Solution: Suppose the vessal initially contains 8 liters of liquid. Let x liters of this liquid be replaced with water then quantity of water in new mixture = 3-(3x/8)+x liters. Quantity of syrup in new mixture = 5 - 5x/8 liters. Therefore 3 - 3x/8 +x = 5 - 5x/8 5x+24 = 40-5x 10x = 16. x= 8/5. So part of the mixture replaced = 8/5*1/8 =1/5.

Simple Intrest
Important Facts and Formulae: Principal or Sum:- The money borrowed or lent out for a certain period is called Principal or the Sum. Interest:- Extra money paid for using others money is called Interest. Simple Interest:- If the interest on a sum borrowed for a certain period is reckoned uniformly,then it is called Simple Interest. Formulae:

Principal = P Rate = R% per annum Time = T years. Then, (i)Simple Interest(S.I)= (P*T*R)/100

(ii) Principal(P) = (100*S.I)/(R*T) Rate(R) = (100*S.I)/(P*T) Time(T) = (100*S.I)/(P*R) Simple Problems 1.Find S.I on Rs68000 at 16 2/3% per annum for 9months. Sol:P=68000 R=50/3% p.a T=9/12 years=4/3 years S.I=(P*R*T)/100 =(68000*(50/3)*(3/4)*(1/100)) =Rs 8500

Note:If months are given we have to converted into years by dividing 12 ie., no.of months/12=years 2.Find S.I on Rs3000 at 18% per annum for the period from 4th Feb to 18th April 1995 Sol:Time=(24+31+18)days =73 days =73/365=1/5 years P= Rs 3000 R= 18% p.a S.I = (P*R*T)/100 =(3000*18*1/5*1/100) =Rs 108 Remark:- The day on which money is deposited is not counted while the day on which money is withdrawn is counted. 3. In how many years will a sum of money becomes triple at 10% per annum. Sol:Let principal S.I S.I 2P T =P = 2P = (P*T*R)/100 = (P*T*10)/100 = 20 years

Note: (1) Total amount = Principal + S.I (2) If sum of money becomes double means Total amount or Sum = Principal + S.I = P + P = 2P

Top
Medium Problems 1.A sum at Simple interest at 13 1/2% per annum amounts

to Rs 2502.50 after 4 years.Find the sum. Sol:Let Sum be x. then, S.I = (P*T*R)/100 = ((x*4*27)/(100*2)) = 27x/100 Amount = (x+(27x)/100) = 77x/50 77x/50 = 2502.50 x = (2502.50*50)/77 = 1625 Sum = 1625

2. A some of money becomes double of itself in 4 years in 12 years it will become how many times at the same rate. Sol:4 yrs - - - - - - - - - P 12 yrs - - - - - - - - ? (12/4)* P =3P Amount or Sum = P+3P = 4 times

3. A Sum was put at S.I at a certain rate for 3 years. Had it been put at 2% higher rate ,it would have fetched Rs 360 more .Find the Sum. Sol:Let Sum original rate T If 2% is more than the fetched 360 more ie., (P*(R+2)*3/100) =P = R = 3 years original rate R+2 - (P*R*3)/100 3PR+ 6P-3PR 6P P Sum

,it would have = = = = = 360 36000 36000 6000 6000.

4.Rs 800 amounts to Rs 920 in 3yrs at S.I.If the interest rate is increased by 3%, it would amount to how much? Sol:S.I Rate New Rate Principal Time S.I New Amount = = = = = = = = 920 - 800 = 120 (100*120)/(800*3) = 5% 5 + 3 = 8% 800 3 yrs (800*8*3)/100 = 192 800 + 192 992

5. Prabhat took a certain amount as a loan from bank at the rate of 8% p.a S.I and gave the same amount to Ashish as a loan at the rate of 12% p.a . If at the end of 12 yrs, he made a profit of Rs. 320 in the deal,What was the original amount? Sol:Let the original amount be Rs x. T = 12

R1 = 8% R2 = 12% Profit = 320 P = x (P*T*R2)/100 - (P*T*R1)/100 =320 (x*12*12)/100 - (x*8*12)/100 = 320 x = 2000/3 x = Rs.666.67 6. Simple Interest on a certail sum at a certain rate is 9/16 of the sum . if the number representing rate percent and time in years be equal ,then the rate is. Sol:Let Sum = x .Then, S.I = 9x/16 Let time = n years & rate = n% n = 100 * 9x/16 * 1/x * 1/n n * n = 900/16 n = 30/4 = 7 1/2%

Complex Problems 1. A certain sum of money amounts t 1680 in 3yrs & it becomes 1920 in 7 yrs .What is the sum. Sol:- - - - - - - - - - - - 1680 - - - - - - - - - - - - 1920 then, - - - - - - - - - - - - 240 - - - - - - - - - - - ? (1/4) * 240 = 60 S.I in 3 yrs = 3*60 = 18012 Sum = Amount - S.I = 1680 - 180 = 1500 we get the same amount if we take S.I in 7 yrs I.e., 7*60 =420 Sum = Amount - S.I = 1920 - 420 = 1500 3 7 4 1 yrs yrs yrs yr -

2. A Person takes a loan of Rs 200 at 5% simple Interest. He returns Rs.100 at the end of 1 yr. In order to clear his dues at the end of 2yrs ,he would pay: Sol:Amount to be paid = Rs(100 + (200*5*1)/100 + (100*5*1)/100) = Rs 115

3. A Man borrowed Rs 24000 from two money lenders.For one loan, he paid 15% per annum and for other 18% per annum. At the end of one year,he paid Rs.4050.How much did he borrowed at each rate? Sol:Let & P1 = P2 = the Sum at 15% be Rs.x then at 18% be Rs (24000-x) x R1 = 15 (24000-x) R2 = 18

At the end of ine year T = 1 (P1*T*R1)/100 + (P2*T*R2)/100 = 4050 (x*1*15)/100 + ((24000-x)*1*18)/100 = 4050 15x + 432000 - 18x = 405000 x = 9000 Money borrowed at 15% = 9000 Money borrowed at 18% = (24000 - 9000) = 15000

Top
4.What annual instalment will discharge a debt of Rs. 1092 due in 3 years at 12% Simple Interest ? Sol:Let each instalment be Rs x (x + (x * 12 * 1)/100) + (x + (x * 12 * 2)/100) + x = 1092 28x/25 + 31x/25 + x =1092 (28x +31x + 25x) = (1092 * 25) 84x = 1092 * 25 x = (1092*25)/84 = 325 Each instalement = 325 5.If x,y,z are three sums of money such that y is the simple interest on x,z is the simple interest on y for the same time and at the same rate of interest ,then we have: Sol:y z is simple interest on x, means y = (x*R*T)/100 RT = 100y/x is simple interest on y, z = (y*R*T)/100 RT = 100z/y 100y/x = 100z/y y * y = xz

6.A Sum of Rs.1550 was lent partly at 5% and partly at 5% and partly at 8% p.a Simple interest .The total interest received after 3 years was Rs.300.The ratio of the money lent at 5% to that lent at 8% is: Sol:Let the Sum at 5% be Rs x at 8% be Rs(1550-x) (x*5*3)/100 + ((1500-x)*8*3)/100 = 300 15x + 1500 * 24 - 24x = 30000 x = 800 Money at 5%/ Money at 8% = 800/(1550 - 800) = 800/750 = 16/15

7. A Man invests a certain sum of money at 6% p.a Simple interest and another sum at 7% p.a Simple interest. His income from interest after 2 years was Rs 354 .one fourth of the first sum is equal to one fifth of the second sum.The total sum invested was: Sol:Let the sums be x & y R1 = 6 R2 = 7 T = 2 (P1*R1*T)/100 + (P2*R2*T)/100 = 354

(x * 6 * 2)/100 + (y * 7 * 2)/100 = 354 6x + 7y = 17700 (1) also one fourth of the first sum is equal to one fifth of the second sum x/4 = y/5 => 5x - 4y = 0 (2) By solving 1 & 2 we get, x = 1200 y = 1500 Total sum = 1200 +1500 = 2700 8. Rs 2189 are divided into three parts such that their amounts after 1,2& 3 years respectively may be equal, the rate of S.I being 4% p.a in all cases. The Smallest part is: Sol:Let these parts be x,y and[2189-(x+y)] then, (x*1*4)/100 = (y*2*4)/100 = (2189-(x+y))*3*4/100 4x/100 = 8y/100 x = 2y By substituting values (2y*1*4)/100 = (2189-3y)*3*4/100 44y = 2189 *12 y = 597 Smallest Part = 597 9. A man invested 3/3 of his capital at 7% , 1/4 at 8% and the remainder at 10%.If his annual income is Rs.561. The capital is: Sol:Let the capital be Rs.x Then, (x/3 * 7/100 * 1) + ( x/4 * 8/100 * 1) + (5x/12 * 10/100 * 1) = 561 7x/300 + x/50 + x/24 = 561 51x = 561 * 600 x = 6600

Compound Intrest
Important Facts and Formulae: Compound Interest: Sometimes it so happens that the borrower and the lender gree to fix up a certain unit of time ,say yearly or half-yearly or quarterly to settle the previous account. In such cases ,the amount after the first unit of time becomes the principal for the 2nd unit ,the amount after second unit becomes the principal for the 3rd unit and so on. After a specified period ,the difference between the amount and the money borrowed is called Compound Interest for that period. Formulae:

Let principal=p,Rate=R% per annum Time=nyears 1.When interest is compounded Annually, Amount=P[1+(R/100)]n 2.When interest is compounded Halfyearly, Amount=P[1+((R/2)100)]2n 3.When interest is compounded Quaterly, Amount=P[1+((R/4)100)]4n 4.When interest is compounded Annually,but time in fractions say 3 2/5 yrs Amount=P[1+(R/100)]3[1+((2R/5)/100)] 5.When rates are different for different years R1%,R2%,R3% for 1st ,2nd ,3rd yrs respectively Amount=P[1+(R1/100)][1+(R2/100)][1+(R3/100)] 6.Present Worth of Rs.X due n years hence is given by Present Worth=X/[1+(R/100)]n Simple Problems 1.Find CI on Rs.6250 at 16% per annum for 2yrs ,compounded annually. Sol: Rate R=16,n=2,Principle=Rs.6250 Method1: Amount=P[1+(R/100)]n =6250[1+(16/100)]2 =Rs.8410 C.I=Amount-P =8410-6250 =Rs.2160 Iyear------------------6250+1000 \\Interest for 1st yr on 6250 II yr---------------6250+1000+160 \\Interest for I1yr on 1000 C.I.=1000+1000+160 =Rs.2160 2.Find C.I on Rs.16000 at 20% per annum for 9 months compounded quaterly Sol: MethodI: R=20% 12months------------------------20% => 3 months------------------------5% For 9 months,there are '3' 3months --------16000+800 --------16000+800+40 --------16000+800+40+10+2 =>Rs.2522 Amount=P[1+(R/100)]n =16000[1+(5/100)]3 =Rs.18522

Method2:

MethodII:

C.I=18522-16000 =Rs.2522

Top
Complex Problems 1.The difference between C.I and S.I. on a certain sum at 10% per annum for 2 yrs is Rs.631.find the sum Sol: MethodI: NOTE: a) For 2 yrs -------->sum=(1002D/R2) b) For 3 yrs -------->sum=(1003D/R2(300+R)) Sum=1002*631/102 =Rs.63100 MethodII: Let the sum be Rs.X,Then C.I.=X[1+(10/100)]2-X S.I=(X*10*2)/100 =X/5 C.I-S.I.=21X/100-X/5 =X/100 X/100=631 X=Rs.63100 2.If C.I on a certain sum for 2 yrs at 12% per annum is Rs.1590. What would be S.I? sol: C.I.=Amount-Principle Let P be X C.I=X[1+(12/100)]2-X =>784X/625-X=1590 =>X=Rs.6250 S.I=(6250*12*2)/100=Rs.1500 3.A sum of money amounts to Rs.6690 after 3 yrs and to Rs.10035b after 6 yrs on C.I .find the sum sol: For 3 yrs, Amount=P[1+(R/100)]3=6690-----------------------(1) For 6 yrs, Amount=P[1+(R/100)]6=10035----------------------(2) (1)/(2)------------[1+(R/100)]3=10035/6690 =3/2 [1+(R/100)]3=3/2-----------------(3) substitue (3) in (1) p*(3/2)=6690 =>p=Rs.4460 sum=Rs.4460 4.A sum of money doubles itself at C.I in 15yrs.In how many yrs will it become 8 times?

sol:

Compound Interest for 15yrs p[1+(R/100)]15 p[1+(R/100)]15=2P =>p[1+(R/100)]n=8P =>[1+(R/100)]n=8 =>[1+(R/100)]n=23 =>[1+(R/100)]n=[1+(R/100)]15*3 since [1+(R/100)] =2 n=45yrs

5.The amount of Rs.7500 at C.I at 4% per annum for 2yrs is sol: Iyear------------------7500+300(300------Interest on 7500) IIyear ----------------7500+300+12(12------------4% interest on 300) Amount=7500+300+300+12 =Rs.8112 6.The difference between C.I and S.I on a sum of money for 2 yrs at 121/2% per annum is Rs.150.the sum is sol: Sum=1002D/R2=( 1002*150) /(25/2)2=Rs.9600 7.If the S.I on sum of money at 15% per annum for 3yrs is Rs.1200, the C.I on the same sum for the same period at same rate is-----S.I=1200 P*T*R/100=1200 P*3*5/100=1200 =>P=Rs.8000 C.I for Rs.8000 at 5% for 3 yrs is-------------8000+400 -----8000+400+20 -------------8000+400+20+20+1 C.I =400+400+20+400+20+20+1 =Rs.1261 sol:

Areas
Important Facts and Formulae: Results On Triangle 1.Sum of the angles of a triangle is 180 degrees. 2.The sum of any two sides of a triangle is greater than third side. 3.Pythagoras Theorem: In a right angled triangle (Hypotenuse)2 = (Base)2 +(Height)2

4.The line joining the mid point of a side of a triangle to the opposite vertex is called the MEDIAN. 5.The point where the three medians of a triangle meet, is called CENTROID. The centroid divides each of the medians in the ratio 2:1 6.In an isosceles triangle, the altitude from the vertex bisects the base 7.The median of a triangle divides it into two triangles of the same area. 8.The area of the triangle formed by joining the mid points of the sides of a given triangle is one-fourth of the area of the given triangle. Results On Quadrilaterals 1.The diagonals of a Parallelogram bisect each other. 2.Each diagonal of a Parallelogram divides it into two triangles of the same area. 3.The diagonals of a Rectangle are equal and bisect each other 4.The diagonals of a Square are equal and bisect each other at right angles. 5.The diagonals of a Rhombus are unequal and bisect each other at right angles. 6.A Parallelogram and a Rectangle on the same base and between the same parallels are equal in area. 7.Of all he parallelogram of given sides the parallelogram which is a rectangle has the greatest area.

Top
Formulae 1.Area of a RECTANGLE = length * breadth Length = (Area/Breadth) and Breadth = (Area/Length) 2.Perimeter of a RECTANGLE = 2(Length + Breadth) 3.Area of a SQUARE = (side)2 = ( Diagonal)2 4.Area of four walls of a room = 2(length + breadth) * height 5.Area of a TRIANGLE = * base * height 6.Area of a TRIANGLE = [s * (s-a) * (s-b) * (s-c)], where a,b,c are the sides of the triangle and s = 1/2(a+b+c)

7.Area of EQUILATERAL TRIANGLE = (3/4)* (side)2 8.Radius of in circle of an EQUILATERAL TRIANGLE of side a = r / 23 9.Radius of circumcircle of an EQUILATERAL TRIANGLE of side a = r / 3 10.Radius of incircle of a triangle of area and semi perimeter S = / s 11.Area of a PARALLELOGRAM = (base * height) 12.Area of RHOMBUS = 1/2 (product of diagonals) 13.Area of TRAPEZIUM = =1/2 * (sum of parallel sides)* (distance between them) 14.Area of a CIRCLE = r2 where r is the radius 15.Circumference of a CIRCLE = 2r 16.Length of an arc = 2 r / 360, where is central angle 17.Area of a SECTOR = (arc * r) = r2 / 360 18.Area of a SEMICIRCLE = r2 / 2 19.Circumference of a SEMICIRCLE = r

Top
Simple Problems 1.One side of a rectangular field is 15m and one of its diagonal is 17m. Find the area of field? Sol: Other side = [(17*17) (15*15)] = (289-225) = 8m Area = 15 * 8 =120 sq. m 2.A lawn is in the form of a rectangle having its sides in the ratio 2:3 The area of the lawn is 1/6 hectares. Find the length and breadth of the lawn. Sol: let length = 2x meters and breadth = 3x mt Now area = (1/6 * 1000)sq m = 5000/3 sq m 2x * 3x = 5000/3 =>x * x =2500 / 9 x = 50/3 length = 2x = 100/3 m and breadth = 3x = 3*(50/3) = 50m

3.Find the cost of carpeting a room 13m long and 9m broad with a carpet 75cm wide at the rate of Rs 12.40 per sq meter Sol: Area of the carpet = Area of the room = 13* 9 =117 sq m length of the carpet = (Area/width) = 117 * (4/3) = 156 m Cost of carpeting = Rs (156 * 12.40) = Rs 1934.40 4.The length of a rectangle is twice its breadth if its length

is decreased by 5cm and breadth is increased by 5cm, the area of the rectangle is increased by 75 sq cm. Find the length of the rectangle. Sol: let length = 2x and breadth = x then (2x-5) (x+5) (2x*x)=75 5x-25 = 75 => x=20 length of the rectangle = 40 cm

5.In measuring the sides of a rectangle, one side is taken 5% in excess and the other 4% in deficit. Find the error percent in the area, calculate from the those measurements. Sol: let x and y be the sides of the rectangle then correct area = (105/100 * x) * (96 / 100 *y) =(504/500 xy) xy = 4/500 xy Error% = 4/500 xy*(1/xy)*100 % = 4/5% = 0.8%

6.A room is half as long again as it is broad. The cost of carpeting the room at Rs 5 per sq m is Rs 2.70 and the cost of papering the four walls at Rs 10 per sq m is Rs 1720. If a door and 2 windows occupy 8 sq cm. Find the dimensions of the room? Sol: let breadth=x mt ,length= 3x/2 mt and height=h mt Area of the floor = (total cost of carpeting /rate) = 270/5 sq m = 54 sq m x * 3x/2=54 => x*x= 54*(2/3)=36 => x = 6m so breadth = 6m and length=3/2*6 = 9m now papered area = 1720 /10 = 172 sq m Area of one door and 2 windows =8 sq m total area of 4 walls = 172+8 = 180 sq m 2(9+6)*h = 180 => h=180/30 = 6m 7.The altitude drawn to the base of an isosceles triangle is 8cm and the perimeter is 32cm. Find the area of the triangle? Sol: let ABC be the isosceles triangle, the AD be the altitude let AB = AC=x then BC= 32-2x since in an isoceles triange the altitude bisects the base so BD=DC=16-x in ADC,(AC) 2 = (AD) 2 + (DC) 2 x*x=(8*8) + (16-x)*(16-x) 32x =320 => x = 10 BC = 32-2x = 32-20 = 12 cm Hence, required area = * BC * AD = * 12 * 10 = 60 sq cm 8.If each side of a square is increased by 25%, find the percentage change in its area? Sol: let each side of the square be a , then area = a * a New side = 125a / 100 = 5a / 4 New area =(5a * 5a)/(4*4) = (25a/16) a = 9a/16 Increase %= 9a/16 * 1/a * 100% = 56.25%

9.Find the area of a Rhombus one side of which measures 20cm and one diagonal 24cm. Sol: Let other diagonal = 2x cm since diagonals of a rhombus bisect each other at right angles, we have 20 = 12 + x => x = [20 -12]= 256 = 16cm so the diagonal = 32 cm Area of rhombus = * product of diagonals = * 24 * 32 = 384 sq cm 10. The area of a circular field is 13.86 hectares. Find the cost of fencing it at the rate of Rs. 4.40 per meter. Sol: Area = 13.86 * 10000 sq m = 138600 sq m r= 138600 => r = 138600 * 7/22 => 210 m circumference = 2r = 2 * 22/7 * 210m = 1320 m cost of fencing = Rs 1320 * 4.40 = Rs. 5808

Top
Medium Problems: 11.Find the ratio of the areas of the incircle and circumcircle of a square. Sol: let the side of the square be x, then its diagonal = 2 x radius of incircle = x/2 and radius of circmcircle =2 x /2 = x/2 required ratio = x/4 : x/2 = : = 1:2 12.If the radius of a circle is decreased by 50% , find the percentage decrease in its area. Sol: let original radius = r and new radius = 50/100 r = r/2 original area = r and new area = (r/2) decrease in area = 3 r/4 * 1/ r * 100 = 75% 13.Two concentric circles form a ring. The inner and outer circumference of the ring are 352/7 m and 528/7m respectively. Find the width of the ring. sol: let the inner and outer radii be r and R meters then, 2r = 352/7 => r = 352/7 * 7/22 * = 8m 2R = 528/7 => R= 528/7 * 7/22 * = 12m width of the ring = R-r = 12-8 = 4m 14.If the diagonal of a rectangle is 17cm long and its perimeter is 46 cm. Find the area of the rectangle. sol: let length = x and breadth = y then 2(x+y) = 46 => x+y = 23 x+y = 17 = 289 now (x+y) = 23 =>x+y+2xy= 529 289+ 2xy = 529 => xy = 120

area =xy=120 sq. cm 15.A rectangular grassy plot 110m by 65cm has a gravel path .5cm wide all round it on the inside. Find the cost of gravelling the path at 80 paise per sq.mt sol: area area cost area of theplot = 110 * 65 = 7150 sq m of the plot excluding the path = (110-5)* (65-5) = 6300 sq m of the path = 7150- 6300 =850 sq m of gravelling the path = 850 * 80/100 = 680 Rs

16. The perimeters of ttwo squares are 40cm and 32 cm. Find the perimeter of a third square whose area is equal to the difference of the areas of the two squares. sol: side of first square = 40/4 =10cm side of second square = 32/4 = 8cm area of third squre = 10 8 = 36 sq cm side of third square = 36 = 6 cm required perimeter = 6*4 = 24cm

Top
17. A room 5m 44cm long and 3m 74cm broad is to be paved with squre tiles. Find the least number of squre tiles required to cover the floor. sol: area of the room = 544 * 374 sq cm size of largest square tile = H.C.F of 544cm and 374cm= 34cm area of 1 tile = 34*34 sq cm no. of tiles required = (544*374) / (34 * 34) = 176 18. The diagonals of two squares are in the ratio of 2:5. Find the ratio of their areas. sol: let the diagonals of the squares be 2x and 5x respectively ratio of their areas = * (2x) : *(5x) = 4:25 19.If each side of a square is increased by 25%. Find the percentage change in its area. sol: let new side new area increase increase each side of the square be a then area = a = 125a/100 = 5a/4 = (5a/4) = 25/16 a in area = (25/16)a - a = (9/16)a % = (9/16)a * (1/a) * 100 = 56.25%

20.The base of triangular field os three times its altitude. If the cost of cultivating the field at Rs. 24.68 per hectare be Rs. 333.18. Find its base and height. sol: area of the field = total cost/ rate = 333.18 /24.68 = 13.5 hectares

=> = 13.5 * 10000 = 135000 sq m let the altitude = x mt and base = 3x mt then *3x * x = 135000 => x = 90000 => x = 300 base= 900m and altitude = 300m 21.In two triangles the ratio of the areas is 4:3 and the ratio of their heights is 3:4. Find the ratio of their bases? Sol: let the bases of the two triangles be x &y and their heights be 3h and 4h respectively. (1/2*x*3h)/(1/2*y*4h) =4/3 => x/y = 4/3 *4/3 = 16/9 22.Find the length of a rope by which a cow must be tethered in order that it may be able to graze an area of 9856 sq meters. Sol: clearly the cow will graze a circular field of area 9856 sq m and radius equal to the length of the rope. Let the length of the rope be r mts then r=9856 => r=9856*7/22 = 3136 => r=56m 23.The diameter of the driving wheel of a bus is 140cm. How many revolutions per minute must the wheel make inorder to keep a speed of 66 kmph? Sol: Distance to be covered in 1min = (66*1000)/60 m =1100m diameter = 140cm => radius = r =0.7m circumference of the wheel = 2*22/7*0.7 = 4.4m no of revolutions per minute = 1100/4.4 = 250 24.The inner circumference of a circular race track, 14m wide is 440m. Find the radius of the outer circle. Sol: let inner radius be r meters. Then 2r =440 => r=440*7/22*1/2 = 70m radius of outer circle = 70+4 =84m 25.A sector of 120 degrees, cut out from a circle, has an area of 66/7 sq cm. Find the radius of the circle. Sol: let the radius of the circle be r cm. Then r/360 =66/7=> 22/7*r*120/360 = 66/7 =>r = 66/7 *7/22*3 =9 radius = 3cm 26.The length of the room is 5.5m and width is 3.75m. Find the cost of paving the floor by slabs at the rate of Rs.800 per sq meter. Sol: l=5.5m w=3.75m area of the floor = 5.5 * 3.75 = 20.625 sq m cost of paving = 800 *20.625 =Rs. 16500

Top

27.A rectangular plot measuring 90 meters by 50 meters is to be enclosed by wire fencing. If the poles of the fence are kept 5 meters apart. How many poles will be needed? Sol: perimeter of the plot = 2(90+50) = 280m no of poles =280/5 =56m 28.The length of a rectangular plot is 20 meters more than its breadth. If the cost of fencing the plot @ 26.50 per meter is Rs. 5300. What is the length of the plot in meter? Sol: let breadth =x then length = x+20 perimeter = 5300/26.50 =200m 2(x+20+x) =200 => 4x+40 =200 x = 40 and length = 40+20 = 60m 29.A rectangular field is to be fenced on three sides leaving a side of 20 feet uncovered. If the area of the field is 680 sq feet, how many feet of fencing will be required? Sol: l=20feet and l*b=680 => b= 680/20 = 34feet length of fencing = l+2b = 20+68 =88 feet 30.A rectangular paper when folded into two congruent parts had a perimeter of 34cm foer each part folded along one set of sides and the same is 38cm. When folded along the other set of sides. What is the area of the paper? Sol: when folded along the breadth we have 2(l/2 +b) = 34 or l+2b = 34...........(1) when folded along the length, we have 2(l+b/2)=38 or 2l+b =38.....(2) from 1 &2 we get l=14 and b=10 Area of the paper = 14*10 = 140 sq cm 31.A took 15 seconds to cross a rectangular field diagonally walking at the rate of 52 m/min and B took the same time to cross the same field along its sides walking at the rate of 68m/min. The area of the field is? Sol: length of the diagonal = 52*15/60 =13m sum of length and breadth = 68*15/60 = 17m (l+b)=13 or l+b = 17 area =lb = (2lb) = [(l+b) (l+b)] = [17 -169] =1/2*120 = 60 sq meter 32 . A rectangular lawn 55m by 35m has two roads each 4m wide running in the middle of it. One parallel to the length and the other parallel to breadth. The cost of graveling the roads at 75 paise per sq meter is sol: area of cross roads = 55*4 +35*4-4*4 = 344sq m cost of graveling = 344 *75/100 =Rs. 258

33.The cost of fencing a square field @ Rs. 20 per metre is Rs.10.080. How much will it cost to lay a three meter wide pavement along the fencing inside the field @ Rs. 50 per sq m sol: perimeter = total cost / cost per m = 10080 /20 = 504m side of the square = 504/4 = 126m breadth of the pavement = 3m side of inner square = 126-6 = 120m area of the pavement = (126*126)-(120*120)=246*6 sq m cost of pavement = 246*6*50 = Rs. 73800 34.Amanwalked diagonally across a square plot. Approximately what was the percent saved by not walking along the edges? Sol: let the side of the square be x meters length of two sides = 2x meters diagonal = 2 x = 1.414x m saving on 2x meters = .59x m saving % = 0.59x /2x *100% = 30% (approx) 36.A man walking at the speed of 4 kmph crosses a square field diagonally in 3 meters.The area of the field is sol: speed of the man = 4*5/18 m/sec = 10/9 m/sec time taken = 3*60 sec = 180 sec length of diagonal = speed * time = 10/9 * 180 = 200m Area of the field = *(dioagonal) = * 200*200 sq m = 20000sq m 37.A square and rectangle have equal areas. If their perimeters are p and q respectively. Then sol: A square and a rectangle with equal areas will satisfy the relation p < q

Top
38.If the perimeters of a square and a rectangle are the same, then the area a & b enclosed by them would satisfy the condition: sol: Take a square of side 4cm and a rectangle having l=6cm and b=2cm then perimeter of square = perimeter of rectangle area of square = 16 sq cm area of rectangle = 12 sq cm Hence a >b 39.An error of 2% in excess is made while measuring the side of a square. The percentage of error in the calculated area of the square is sol: 100cm is read as 102 cm a = 100*100 sq cm and b = 102 *102 sq cm then a-b = 404 sq cm percentage error = 404/(100*100) = 4.04%

40.A tank is 25m long 12m wide and 6m deep. The cost of plastering its walls and bottom at 75 paise per sq m is sol: area to be plastered = [2(l+b)*h]+(l*b) = 2(25+12)*6 + (25*12)= 744 sq m cost of plastering = Rs . 744*75/100 = Rs. 5581 41.The dimensions of a room are 10m*7m*5m. There are 2 doors and 3 windows in the room. The dimensions of the doors are 1m*3m. One window is of size 2m*1.5m and the other 2 windows are of size 1m*1.5m. The cost of painting the walls at Rs. 3 per sq m is sol: Area of 4 walls = 2(l+b)*h =2(10+7)*5 = 170 sq m Area of 2 doors and 3 windows = 2(1*3)+(2*1.5)+2(1*1.5) = 12 sq m area to be planted = 170 -12 = 158 sq m cost of painting = Rs. 158 *3 = Rs. 474 42.The base of a triangle of 15cm and height is 12cm. The height of another triangle of double the area having the base 20cm is sol: a = *15*12 = 90 sq cm b = 2a = 2 * 90 = * 20 *h => h= 18cm 43.The sides of a triangle are in the ratio of :1/3:1/4. If the perimeter is 52cm, then the length of the smallest side is sol: ratio of sides = :1/3 :1/4 = 6:4:3 perimeter = 52 cm, so sides are 52*6/13 =24cm 52*4/13 = 16cm 52 *3/13 = 12cm length of smallest side = 12cm 44.The height of an equilateral triangle is 10cm. Its area is sol: a = (a/2) +(10) a a/4 = 100 =>3a = 100*4 area = 3/4 *a = 3/4*400/3 = 100/3 sq cm 45.From a point in the interior of an equilateral triangle, the perpendicular distance of the sides are 3 cm, 23cm and 53cm. The perimeter of the triangle is sol: let each side of the triangle be a cm then area(AOB) +area(BOC)+area(AOC) = area(ABC) * a *3 +1/2 *a *23 +1/2 * a*53 = 3/4 a a/23(1+2+5) = 3/4 a => a=16 perimeter = 3*16 = 48cm

Top
Complex Probems: 1.If the area of a square with side a s equal to the area of a triangle with base a, then the altitude of the triangle is

sol: area of a square with side a = a sq unts area of a triangle with base a = * a*h sq unts a =1/2 *a *h => h = 2a altitude of the triangle is 2a 2.An equilateral triangle is described on the diagonal of a square. What is the ratio of the area of the triangle to that of the square? Sol: area of a square = a sq cm length of the diagonal = 2a cm area of equilateral triangle with side 2a = 3/4 * (2a) required ratio = 3a : a = 3 : 2 3.The ratio of bases of two triangles is x:y and that of their areas is a:b. Then the ratio of their corresponding altitudes wll be sol: a/b =( * x*H) /(1/2 * y * h) bxH = ayh =>H/h =ay/bx Hence H:h = ay:bx 4 .A parallelogram has sides 30m and 14m and one of its diagonals is 40m long. Then its area is sol: let ABCD be the given parallelogram area of parallelogram ABCD = 2* (area of triangle ABC) now a = 30m, b = 14m and c = 40m s = (30+14+40) = 42m Area of triangle ABC = [ s(s-a)(s-b)(s-c) = (42*12*28*2 = 168sq m area of parallelogram ABCD = 2 *168 =336 sq m 5.If a parallelogram with area p, a triangle with area R and a triangle with area T are all constructed on the same base and all have the same altitude, then which of the following statements is false? Sol: let each have base = b and height = h then p = b*h, R = b*h and T = * b*h so P = R, P = 2T and T = R are all correct statements 6.If the diagonals of a rhombus are 24cm and 10cm the area and the perimeter of the rhombus are respectively. Sol: area = *diagonal 1 *diagonal 2= * 24 * 10= 120 sq cm * diagonal 1 = * 24 = 12cm * diagonal 2 = *10 =5 cm side of a rhombus = (12) + (5) = 169 => AB = 13cm

Top
7.If a square and a rhombus stand on the same base, then the ratio of the areas of the square and the rhombus is: sol: A square and a rhombus on the same base are equal in area

8.The area of a field in the shape of a trapezium measures 1440sq m. The perpendicular distance between its parallel sides is 24cm. If the ratio of the sides is 5:3, the length of the longer parallel side is: sol: area of field =1/2 *(5x+3x) *24 = 96x sq m 96x = 1440 => x = 1440 /96 = 15 hence, the length of longer parallel side = 5x = 75m 9.The area of a circle of radius 5 is numerically what percent its circumference? Sol: required percentage = (5)/(2*5) *100 = 250% 10.A man runs round a circular field of radius 50m at the speed of 12m/hr. What is the time taken by the man to take twenty rounds of the field? Sol: speed = 12 k/h = 12 * 5/18 = 10/3 m/s distance covered = 20 * 2*22/7*50 = 44000/7m time taken = distance /speed = 44000/7 * 3/10 = 220/7min 11.A cow s tethered in the middle of a field with a 14feet long rope.If the cow grazes 100 sq feet per day, then approximately what time will be taken by the cow to graze the whole field? Sol: area of the field grazed = 22/7 * 14 * 14 = 616 sq feet 12.A wire can be bent in the If it is bent in the form of sol: length of wire = 2 r side of the square = 352/4 = area of the square = 88*88 = form of a circle of radius 56cm. a square, then its area will be = 2 *22/7 *56 = 352 cm 88cm 7744sq cm

13.The no of revolutions a wheel of diameter 40cm makes in traveling a distance of 176m is sol: distance covered in 1 revolution = 2 r = 2 *22/7 *20 = 880/7 cm required no of revolutions = 17600 *7/880 = 140

Top
14.The wheel of a motorcycle 70cm in diameter makes 40 revolutions in every 10sec.What is the speed of motorcycle n km/hr? Sol: distance covered in 10sec = 2 *22/7 *35/100 *40 =88m distance covered in 1 sec =88/10m = 8.8m speed =8.8m/s = 8.8 * 18/5 *k/h = 31.68 k/h 15.Wheels of diameters 7cm and 14cm start rolling simultaneously

from x & y which are 1980 cm apart towards each other in opposite directions. Both of them make the same number of revolutions per second. If both of them meet after 10seconds.The speed of the smaller wheel is sol: let each wheel make x revolutions per sec. Then (2 *7/2 *x)+(2 * 7*x)*10 = 1980 (22/7 *7 * x) + (2 * 22/7 *7 *x) = 198 66x = 198 => x = 3 distance moved by smaller wheel in 3 revolutions = 2 *22/7 *7/2 *3 = 66cm speed of smaller wheel = 66/3 m/s = 22m/s 16.A circular swimming pool is surrounded by a concrete wall 4ft wide. If the area of the concrete wall surrounding the pool is 11/25 that of the pool, then the radius of the pool is? Sol: let the radius of the pool be R ft radius of the pool including the wall = (R+4)ft area of the concrete wall = [(R+4)2 - R2 ] => = [R+4+R][R+4-R] = 8(R+2) sq feet 8(R+2) = 11/25 R2 => 11 R2 = 200 (R+2) Radius of the pool R = 20ft 17.A semicircular shaped window has diameter of 63cm. Its perimeter equals sol: perimeter of window = r +2r = [22/7 * 63/2 +63] = 99+63 = 162 cm 18.Three circles of radius 3.5cm are placed in such a way that each circle touches the other two. The area of the portion enclosed by the circles is sol: required area - (3 * area of = ( * 7 = 493/4 = (area of an equilateral triangle of side 7 cm) sector with = 6o degrees and r = 3.5cm) * 7) (3* 22/7 *3.5 *3.5*60/360 ) sq cm 11*0.5*3.5 sq cm = 1.967 sq cm

19. Four circular cardboard pieces, each of radius 7cm are placed in such a way that each piece touches two other pieces. The area of the space encosed by the four pieces is sol: required area = 14*14 (4 * * 22/7 * 7 *7) sq cm = 196 154 = 42 sq cm

Races and Games of Skill

Important Facts and Formulae: Races: A contest of speed in running ,riding,driving,sailing or rowing is called a Race Race Course: The ground or path on which contests are made is called a race course Starting Point: The point from which a race begins is called starting point. Winning point or goal: The point set to bound a race is called a winning point. Dead Heat Race: If all the persons contesting a race reach the goal exactly at the same time,then the race is called a dead heat race. Start: Suppose A and B are two contestants in a race .If before the start of the race,A is at the satrtint point and B is ahead of A by 12 metres. Then we say that "A gives B a start 12 metres. ->To cover a race of 100metres in this case,A will have to cover 100m while B will have to cover 88m=(100-12) ->In a100m race 'A can give B 12m' or 'A can give B a start of 12m' or 'A beats B by 12m'means that while A runs 100m B runs 88m. Games: A game of 100m,means that the person among the contestants who scores 100 points first is the winner. If A scores 100 points while B scores only 80 points then we say that 'A can give B 20 points'.

Top
Problems: 1) In a 1 km race,A beats B by 28 m or 7sec.Find A's time over the course? Sol: B covers 28 m in 7sec so,B's time over the course = 7/28 *1000 =250 sec A's time over the course =250-7 =243 sec = 4min ,3 sec. 2) A runs 1 3/4 times as fast as B.If A gives B a start of 84 m,how far must be winning post be so that A and B might reach it at the same time ? Sol: Ratio of rates of A:B =7/4 :1 =7 :4 In a game of 7 m A gains 3m over B. 3m are gained by A in a race of 7m 84 m are gained by A in a race of 7*84/3 =196 m Winning post must be 196m away from the starting point. 3)A can run 1km in 3 min ,10sec and B can cover same distance in 3 min 20 sec. By what distance A beat B?

Sol: clearly A beats B by 10 sec. Distance covered by B in 10 sec =1000/200 *10 =50 m A beats B by 50 metres. 4) In a 100m race,A runs at 8km per hour.If A gives b a start of 4 m and still beats him by 15 sec,what is the speed of B? Sol: 8000 m -------60*60 sec 100m ------- 60*60*1000/8000 =45 sec. Time taken by A to cover 100m =45 sec. B covers 100-4 m =96 min 45 sec =60 sec B's speed =96 *60*60/60*1000 =5.76 km/hr 5) A and B take part in 100m race .A runs at 5km per hour. A gives B a start of 8 m and still beats him by 8 sec. What is the speed of B? Sol : A'speed = 5km/hr =5*5/18 =25/18 m/s Time taken by A to cover 100m =100*18/25 =7.2 sec Time taken by A to cover 92m = 72+8 =80 sec B's speed =92*18/80*5 = 4.14 kmph. 6) A runs 1 2/3 times as fast as B.If A gives B a start of 80 m, how far must the winning post be so that A and B might reach if at the same time? Sol: Ratio of the speed of A and B =5/3 :1 Thus in a race of 5m ,A gains 2m over B 2m are gained by in a race of 5m 80 m will be gained by A in a race of 5/2* 80 =200 m 7) A,B and C are three contestans in a kmrace .If A can give B a start of 40 m and A can give C a start of 64 m,how amny metres start can b give C? Sol: A covers 100m,B covers (1000-40) =960 m C covers 1000-64 m or 936m when B covers 960 m,C covers 936 m when B covers 1000 m, C covers 936*1000/960 m =975 m B can give C a start of 1000-975 or 25 m. 8) In a 100m race,A covers the distance in 36 sec and B in 45 sec.In this race A beats B by? Sol: Distance covered by B in 9secs =100*9/45 =20 m A beats B by 20m 9) In a 200 m race A beats B by 35m or 7 sec.What is the A's time over the course? Sol: B runs 35 m in 7sec. B covers 200m in =7*200/35 = 40 sec. B's time over the course =40 sec A's time over the course =40-7 =33 sec. 10) In a 300 m race A beats B by 22.5 m or 6 sec.What is the B's time over the course? Sol: B runs 22.5 m in 6sec. B runs 300m in =6*300*2/45 =80 sec.

B's time over the course =80 sec.

Top
11) A can run 22.5 m while B runs 25 m.In a kilometre race B beats A by? Sol: B runs 25 m ,A runs 45/2 m B runs 1000 A runs = 1000*45/2*25 =900m B beats A by 100m 12)In a 500 m race, the ratio of the speeds of two contestants A and B is 3:4.A has a start of 140 m.Then ,A win by B? Sol: The speeds of A and B =3:4 To reach the winning post A will have to cover a distance of 500-140 m i.e 360 m while A covers 3m, b covers 4m A covers 360m B covers 4/3*360=480m Thus when A reaches the winning post, b covers 480m and therefore remains 20m behind. A wins by 20m. 13) In a 100m race,A can beat B by 25 m and B can beat c by 4m. In the same race A can beat C by/ Sol: If A:B =100 :75 B :C=100 :96 then A :C =A/B*B/C=100/75* 100/96 = 100/72 A beats C by 100 -72 m=28 m 14) In a 100 race,A can give B 10 mand C 28 m.In the same race B can give C? Sol: A:B =100 :90 A :C=100 :72 B:C =B/A *A/C =90/100*100/72 =90/72 When B runs 90 C runs 72 when B runs 100 C runs =72*100/90 B beats C by 20m 15) In a 100m race ,A beats B by 10 m and C by 13 m.In the race of 180m. B will beat c by? Sol :A : B =100 :90 A/B =100/90 A/C =100/87 B/C =B/A *A/C =90 /87 When B runs 90m C runs 87 When B runs 180 m then C runs =87 *180/90 B beats C by 180-174= 6m 16) In a race of 200 m, A can beat B by 31 m and C by 18m.In arace of 350 m, C will beat B by? Sol : In a race of 200 m A :B =200:169 A :C =200 :182 C/B =C/A*A/B =182/200*200/169 When C runs 182 m B runs 169 when C runs 350 m B runs =350*169/182 =325m 17) In agame of 100 points A can give B 20 points and C 28 points then B can give C? Sol: In a game of 100 points.A :B =100 :80 A :C =100 :72 B/C=B/A*A/C =80/100*100/72 = 80/72 when B runs 80m C runs 72 when B runs 100m C runs =100*72/80 =90 B can give C 10 points in agame of 100. 18)At a game of billiards,A can give B 15 points in 60 and A can give C 20 points in60.How amny points can B give C in a game of 90? Sol: A:B =60:45 A:C =60:40 B/C =B/A*A/C =45/60*60/40 =90/80

B can give C 10 points in agame of 90. 19) in agame of 80 points,A can give B 5 points and C 15 points. Then how many points B can give C in agame of 60? Sol: A :B =80 :75 A :C =80:65 B/C=B/A*A/C = 75/80*80/65 =15/13 B:C =60:52

Calenders
Important Facts and Formulae: a) Odd Days : The number of days more than the complete number of weeks in a given period is number of odd days during that period. b) Leap year : Every year which is divisible by 4 is called a leap year. Thus each one of he year 1992,1996,2004,2008,..etc, is a eap year. Every 4th century is a leap year but no other century is a leap year thus each one of 400,800,1200,1600,2000,etc is a leap year. None of the 1900,2010,2020,2100,etc is a leap year. An year which is not a leap year is called Ordinary year. c)An ordinary year has 365 days. d) A leap year has 366 days. e)Counting of odd days : i)1 ordinary year = 365 days =52 weeks+1 day,Therefore An ordinary year has 1 Odd day. ii)One leap year = 366 days =52 weeks+2 days, Therefore a leap year has 2 Odd days. iii) 100 years = 76 ordinary years+ 24 leap years = [(76*52) weeks+76 days]+[(24*52)weeks+48 days] = 5200 weeks+124days=[5217 weeks+5 days] therefore 100 years contain 5 odd days iv)200 years contain 10(1week+3days), i.e 3 odd days v)300 years contain 15(2 weeks+1 day), i.e 1 odd day vi)400 years contain (20+1), i.e 3 weeks,so 0 Odd days similarly each one of 800,1200,1600,etc contains 0 odd days. Note:(7n+m) odd days , where m less than or equal to 7 is equivalent to m odd days ,thus ,8 odd days = 1 odd day etc. f) Some codes o remember the months and weeks: a) Week Sunday - 1 Monday - 2 Tuesday - 3

Wednesday - 4 Thursday - 5 Friday - 6 Saturday - 0 b) Month jan - 1 feb - 4 Mar - 4 Apr - 0 May - 2 june - 5 Simple problems: Shortcuts : This shortcut must be applied only starting with 19 series. Example: What day of the week on 17th june , 1998? Solution : 5 -> the given month code(august) 17 -> the given date 98->(19 th century after years) 24-> ((47/4) = 11 i.e how many leap years -------total = 144 ((144/7) = 20 and the remainder is 4) therefore in the above week table the no 4 code represents wednesday so the required day is wednesday. july - 0 Aug - 3 Sep - 6 Oct - 1 Nov - 4 Dec - 6

Top

Problem 1: The first republic day of the India was celebrated on 26th January,1950. It was Solution : 01 26 50 12 ---------total = 89 ((89/7) = 12 and the remainder is 5) therefore in the above week table represents the number 5 as thursday, so the required day was Thursday.

Problem 2: Find on which day 15th august1947 ? Solution : 03 15 47 11 ---------total = 76 Then (76)/7 = 6 odd days 6 indicates friday in the above week table.

Therefore required day is friday. Problem 3: Find on which day jan 26th 1956 ? Solution : 01 26 56 14 -1 (-1 indicates leapyear(i.e 1956),so 1 reduce from the total) --------total = 96 Then (96)/7 = 5 odd days 5 indicates thursday in the above week table Therefore our required day is Thursday. Problem 4: Today is friday after 62 days,it will be : Solution : Each day of the week is repeated after 7 days. so, after 63 days,it will be friday. Hence ,after 62 days, it will be thursday. Therefore the required day is thursday. Problem 5: Find the day of the week on 25th december,1995? Solution : 06 25 95 23 --------total = 149 Then (149)/7=(23)=2 odd days Therefore the required day is "Monday".

Top
Medium Problems Problem 1: jan 1, 1995 was a sunday.what day of the week lies on jan 1,1996? Solution : 01 01 96 24 -1(since 1996 was leap year) --------total = 121 Then (121)/7 = (17) = 2 odd days Therefore our required day wasMonday.

Problem 2: On 8th feb,1995 it wednesday. The day of the week on

8th feb,1994 was? Solution : 04 08 94 23 --------total = 129 Then (129)/7 = (18) = 3 odd days Therefore the required day is Tuesday.

Problem 3: may 6,1993 was thursday.what day of the week was on may 6,1992 ? Solution : 02 06 92 23 -1 ---------total = 122 Then (122)/7 = (17) = 3 odd days Therefore the required day is Tuesday Problem 4: jan 1, 1992 was wednesday. What day of the week was on jan 1,1993 ? Solution : 01 01 93 23 ---------total = 118 Then (118)/7 = (16) = 6 odd days Therefore the required day is Friday. Problem 5: January 1,2004 was a thursday,what day of the week lies on jan ,2005? solution : The year 2004 being a leap year, it has 2 odd days. so, first day of the 2005 will be 2 days beyond thursday and so it will be saturday therefore the required day is Thursday. Problem 6: On 8th march,2005,wednesday falls what day of the week was it on 8th march,2004? Solution : the year 2004 being a leap year,it has 2 odd days. so, the day on8th march,2005 will be two days beyond the day

on 8th march,2004.but 8th march,2005 is wednesday. so, 8th march,2004 is monday. Therefore the required day is Monday. Problem 7: what was the day of the week on 19th september ,1986 ? Solution : 06 19 86 21 --------total = 132 Then ((132/7 = 18 and the remainder is 6) In the above week table represents the number 6 is friday. Therefore the required day is Friday.

Top
Typical problems Problem 1: On what dates of october,1994 did monday fall ? Solution : 01 01 94 23 ------total = 119 Then (119)/7 = (17) = 0 odd days so the day is saturday Therefore in october first the day is saturday.so, the monday fell on 3rd october 1994.During october 1994, monday fell on 3rd ,10th,17th and 24th. Problem 2: How many days are there from 2nd january 1995 to 15 th march,1995 ? Solution : Jan + Feb + March 30 + 28 + 15 = 73 days

Problem 3: The year next to 1996 having the same calendar as that of 1996 is ? Solution : Starting with 1996 , we go on countig the number of odd days till the sum is divisible by 7. Year 1996 1997 1998 1999 2000 odd days 2 1 1 1 2 2 + 1 + 1 + 1 + 2 = 7 odd days i.e odd day. Therefore calendar for 2001 will be the same as that of 1995. Problem 4: The calendar for 1990 is same as for :

Solution: count the number of days 1990 onwards to get 0 odd day. Year 1990 1991 1992 1993 1994 1995 oddd days 1 1 2 1 1 1 1 + 1 + 2 + 1 + 1 + 1 = 7 or 0 odd days Therefore calendar for 1990 is the same as for the year 1996. Problem 5: The day on 5th march of year is the same day on what date of the same year? Solution: In the given monthly code table represents the march code and november code both are same.that means any date in march is the same day of week as the corresponding date in november of that year, so the same day falls on 5th november.

Clocks
General Concepts: The face or dial of a watch is a circle whose circumference is divided into 60 equal parts,called minute spaces. A clock has two hands, the Smaller one is called the hour hand or short hand while the larger one is called the minute hand or long hand. Important points: a) In every 60 minutes, the minute hand gains 55 minutes on the hour hand b)In every hour, both the hands coincide once ,i.e 0 degrees. c)the hands are in the same straight line when they are coincident or opposite to each other. i.e 0 degrees or 180 degrees. d)when the two hands are at right angles, they are 15 minute spaces apart,i.e 90 degrees. e)when the hands are in the opposite directions,they are 30 minute spaces apart,i.e 180 degrees. f)Angle traced by hour hand in 12hrs = 360 degrees. g)Angle traced by minute hand in 60 min = 360 degrees. If a watch or a clock indicated 8.15,when the correct time is 8, it is said to be 15 minutes too fast. On the other hand, if it indicates 7.45,

when the correct time is 8,it is said to be 15 minutes slow. h)60 min --> 360 degrees 1 min --> 60 i)the hands of a clock coincide in a day or 24 hours is 22 times, in 12hours 11minutes. j)the hands of clock are straight in a day is 44 times . k)the hands of a clock at right angle in a day is 44 times . l)the hands of a clock in straight line but opposite in direction is 22 times per day

Top
Simple Problems: Type1: Find the angle between the hour hand and the minute hand of a clock when the time is 3.25 solution : In this type of problems the formulae is as follows 30*[hrs-(min/5)]+(min/2) In the above problem the given data is time is 3.25. that is applied in the formulae 30*[3-(25/5)]+(25/2)30*(15-25)/5+25/2 = 30*(-10/5)+25/2 = -300/5+25/2 = -600+(25/2)=-475/10=-47.5 i.e 47 1/20 therefore the required angle is 47 1/20. Note:The -sign must be neglected. Another shortcut for type1 is : The formulae is 6*x-(hrs*60+X)/2 Here x is the given minutes, so in the given problem the minutes is 25 minutes, that is applied in the given formulae 6*25-(3*60+25)/2 150-205/2 (300-205)/2=95/2 =47 1/20. therefore the required angle is 47 1/20. Type2: At what time between 2 and 3 o' clock will be the hands of a clock be together? Solution : In this type of problems the formulae is 5*x*(12/11) Here x is replaced by the first interval of given time. here i.e 2. In the above problem the given data is between 2 and 3 o' clock 5*2*12/11 =10*12/11=120/11=10 10/11min. Therefore the hands will coincide at 10 10/11 min.past2.

Another shortcut for type2 is: Here the clocks be together but not opposite to each other so the angle is 0 degrees. so the formulae is 6*x-(2*60+x)/2=06*x-(120+x)/2=012x-120-x=0 11x=120 x=120/11=10 10/11 therefore the hands will be coincide at 10 10/11 min.past2.

Top
Medium Problems Type3: At what time between 4 and 5 o'clock will the hands of a clock be at rightangle? Solution : In this type of problems the formulae is (5*x + or -15)*(12/11) Here x is replaced by the first interval of given time here i.e 4 Case 1 : (5*x + 15)*(12/11) (5*4 +15)*(12/11) (20+15)*(12/11) 35*12/11=420/11=38 2/11 min. Therefore they are right angles at 38 2/11 min .past4 Case 2 : (5*x-15)*(12/11) (5*4-15)*(12/11) (20-15)*(12/11) 5*12/11=60/11 min=5 5/11min Therefore they are right angles at 5 5/11 min.past4. Another shortcut for type 3 is: Here the given angle is right angle i.e 900. Case 1 : The formulae is 6*x-(hrs*60+x)/2=Given angle 6*x-(4*60+x)/2=90 6*x-(240+x)/2=90 12x-240-x=180 11x=180+240 11x=420 x=420/11= 38 2/11 min Therefore they are at right angles at 38 2/11 min. past4. Case 2 : The formulae is (hrs*60+x)/2-(6*x)=Given angle (4*60+x)/2-(6*x)=90 (240+x)/2-(6*x)=90 240+x-12x=180 -11x+240=180 240-180=11x x=60/11= 5 5/11 min Therefore they art right angles at 5 5/11 min past4. Type 4: Find at what time between 8 and 9 o'clock will the hands of a

clock be in the same straight line but not together ? Solution : In this type of problems the formulae is (5*x-30)*12/11 x is replaced by the first interval of given time Here i.e 8 (5*8-30)*12/11 (40-30)*12/11 10*12/11=120/11 min=10 10/11 min. Therefore the hands will be in the same straight line but not together at 10 10/11 min.past 8. Another shortcut for type 4 is: Here the hands of a clock be in the same straight line but not together the angle is 180 degrees. The formulae is (hrs*60+x)/2-(6*x)=Given angle (8*60+x)/2-6*x=180 (480+x)/2-(6*x)=180 480+x-12*x=360 11x=480-360 x=120/11=10 10/11 min. therefore the hands will be in the same straight line but not together at 10 10/11 min. past8.

Top
Type 5: At what time between 5 and 6 o clock are the hands of a 3 minutes apart ? Solution : In this type of problems the formuae is (5*x+ or - t)*12/11 Here x is replaced by the first interval of given time here xis 5. t is spaces apart Case 1 : (5*x+t)*12/11 (5*5+3)*12/11 28*12/11 = 336/11=31 5/11 min therefore the hands will be 3 min .apart at 31 5/11 min.past5. Case 2 : (5*x-t)*12/11 (5*5-3)*12/11 (25-3)*12/11=24 min therefore the hands wi be 3 in apart at 24 min past 5. Typicalproblems problems: A watch which gains uniformly ,is 5 min,slow at 8 o'clock in the morning on sunday and it is 5 min.48 sec.fast at 8 p.m on following sunday. when was it correct? Solution : Time from 8 am on sunday to 8 p.m on following sunday = 7 days 12 hours = 180 hours the watch gains (5+(5 4/5))min .or 54/5 min. in 180 hours Now 54/5 minare gained in 180 hours. Therefore 5 minutes are gained in(180*5/54*5)hours=83 hours20 min. =3 days11hrs20min.

therefore watch is correct at 3 days 11 hours 20 minutes after 8 a.m of sunday therefore it wil be correct at 20 min.past 7 p.m on wednesday

True Discount
Formulae: Let rate=R%per annum, Time= T years 1.Present worth (PW) = (100*Amount)/(100+(R*T)) = (100* TrueDiscount)/(R*T) 2.TrueDiscount (TD) = (P.W*R*T)/100 = (Amount*R*T)/(100+(R*T)) 3.Sum =(SimpeInterest*TrueDiscount)/(SimpleInterest-TrueDiscount) 4.SimpleInterest-TrueDiscount=SimpeInterest on TrueDiscount 5.When the sum is put at CompoundInterest,then PresentWorth=Amount/(1+(R/100))^T GeneralConcept: Suppose a man has to pay Rs.156 after 4 years and the rate of interest is 14%per annum Clearly ,Rs.100 at 14% will amount to Rs156 in 4 years So,the payment of Rs.100 now wil cear off the debt of Rs156 due 4 years hence We say that Sum due = Rs156 due 4 years hence Present Worth =Rs100 True Discount=Rs.156-Rs100=Rs56 =Sumdue-PW We define TrueDiscount= Interest on Present Worth(PW) Amount = PresentWorth+TrueDiscount 1.Find the present worth of Rs.930 due 3 years hence at 8% per annum.Aso find the discount? Sol: Amount=RS.930,Time=3years,Rate=8% TrueDiscount = (Presentworth*Time*Rate)/100 Presentworth = (Amount*100) /(100+(R*T)) Presentworth = (930*100)/(100+(8*3) =Rs.750 TrueDiscount = (930*3*8)/(100+(8*3)) =Rs.180 (or) TrueDiscount = Amount-Presentworth =Rs.930-Rs.750

=Rs.180 2.The truediscount on a bill due 9 months hence at 12% per annum is Rs540.Find the amount of the bill and its presentworth? Sol: Time=9months=9/12years=3/4years Rate=12% TrueDiscount=Rs540 TrueDiscount=(Amount*100)/(100+(R*T)) =>Amount=(TrueDiscount*(100+(R*T))) /100 =(540*(100+12*(3/4))/100 =Rs.6540 Presentworth=Amount-TrueDiscount =Rs.6540-Rs540 =Rs.6000 3.The TrueDiscount on a certain sum of money due 3 years hence is Rs.250 and SimpeInterest on the same sum for same time and same rate is Rs375 find sum and rate%? Sol: Time=3 years Truediscount=Rs.250 SimpeInterest=Rs375 Sum = (SimpeInterest*TrueDiscount)/(SimpeInterest-TrueDiscount) = (375*250)/(375-250) =Rs.750 SimpeInterest=(Principle*Time*Rate)/100 375 = ( 750*3R)/100 R=50/3% => Rate=162/3%

Top
4.The difference between SimpeInterest and TrueDiscount on a certain sum of money for 6 months at 121/2% per annum is Rs25. Find the sum. Sol: Let amount be Rs.x SimpleInterest=(Amount*T*R)/100 TrueDiscount=(Amount*T*R)/(100+(R*T)) SI-T.D=Rs25 =>((x*6/12*25/2)/100)-((x*6/12*25/2)/(100+(6/12*25/2))=25 =>x=Rs.6800 5.The Present worth of Rs.2310 due 21/2yrs henceThe interest being 15% per annum is sol: Amount=Rs2310,Time=21/2yrs,Rate=15% Presentworth = (Amount*100) /(100+(R*T)) =2310*100/(100+15*5/2) =Rs1680. Medium Problems 1.A bill falls due in 1 year.The creditor agrees to accept immediate payment of the half and to defer the payment of the other half for 2 years .By this arrangement he gains Rs.40.what is the amount of bill,if the money be worth 121/2%?

sol: Let the amount be Rs.x If the bill falls due for 1 yr, Truediscount=(Amount*100)/(100+R*T) =(x*100)/(100+(25/2*1) If Accepting immediate payment of the half and to defer the payment of the other half for 2 years, Truediscount=(Amount*100)/(100+R*T) =[x/2+((x/2*100)/(100+(25/2*2))] x/2 for immediate payment, ((x/2*100)/(100+(25/2*2)) for paying after 2 yrs He gains Rs40 =>[x/2+((x/2*100)/(100+(25/2*2))] (x*100)/(100+(25/2*1) = Rs40 => x/2+2x/5-8x/9=40 =>x=Rs.3600 Amount of the bill=Rs.3600 2.If the truediscount on a sum due 2yrs hence at 14% per annum be Rs168.The sum due is? Sol: Time=2yrs, Rate=14% Truediscount=Rs168,Amount=x TrueDiscount=(Amount*R*T)/(100+R*T) 168 =(x*14*2)/(100+(14*2)) =>x=Rs.768 3.The truediscount on Rs.2562 due 4 months hence is Rs.122.The rate % is? Sol: Amount=Rs.2562 Time=4/12yrs TrueDiscount=Rs122 Rate=X% TrueDiscount=(Amount*R*T)/(100+R*T) =>122=(2562*x*(4/12))/(100+(x*(4/12)) =>36600+122x=2562x =>Rate=15% 4.The Truediscount on Rs1760 due after a certain time at 12% per annum is Rs160The time after which it is due is: Sol: Amount=Rs.1760 Rate=12% Truediscount=Rs160 Time=x TrueDiscount=(Amount*R*T)/(100+R*T) =>x*11*12=100+12x =>x=5/6yr Time=10months 5.The interest on Rs.760 for 2yrs is the same as the Truediscount on Rs960 due 2yrs hence .If the rate of interest is same in both cases,it is

sol: Principal=Rs.760 Time=2yrs amount=Rs960 P*T*R/100=(Amount*R*T)/(100+R*T) =>(750*2*r)/100=(960*r*2)/(100+2r) =>150r=2100 rate=14% 6.The SimpleInterest & TrueDiscount on a certain sum of money for a given time & at a given rate are Rs85 & Rs.80.The sum is............. sol: S.I= Rs.85 TrueDiscount=Rs80 Sum=(S.I.*TD)/(SI-T.D) =Rs.1360

Top
7.A trader owes a maerchant Rs10028 due 1yr hence The trader wants to settle the account after 3 months .If the rate of interest is 12%per annum How much cash should he pay? Sol: Time=1yr but he settles account after 3months so time = 9months Cash to pay=(Amount*R*T)/(100+R*T) =(10028*100)/(100+12*(9/12)) =Rs.9200 8.A man buys a watch for Rs1950 in cash and sells it for Rs2200 at a credit of 1yrThe rate of interest is 10% per annum Then he gains / loose---------------amount? Sol: If he sells it for Rs2200 at a credit of 1yr then the present worth of that amount is Presentworth = (Amount*100) /(100+(R*T)) =(2200*100)/(100+10*1) =2000/So he gains 2000-1950=Rs.50 9.A owes Rs.1573 payable 11/2yrs hence ,Aso B owes A Rs.144450 payabe 6months hence If they want to settle the accunt forth with ,keeping 14% as the rate of interest ,then who should pay & how much? Sol: B->A-----------Amount=Rs.1573 Rate=14% Time=3/2 Presentworth = (Amount*100) /(100+(R*T)) =(1573*100)/(100+(3/2)*14) =Rs1300 A->B------------Amount=Rs.1444.50

Rate=14% Time=1/2 Presentworth = (Amount*100) /(100+(R*T)) =(1444.50*100)/(100+(1/2)*14) =Rs1350 so B should pay Rs.1350 10.If Rs20 is the TrueDiscount on Rs260due after a certain time. What wil be trueDiscount on same sum due after of former time, the rate of interest beng the same? Sol: Simple Interest on (260-20) for a gven time=Rs20 Simple Interest on (260-20) for a half time=Rs20*(1/2) =Rs10 True Discount on Rs.250=Rs10 True Discount on Rs.260=Rs10*260/250 =Rs10.40 11.A has to pay Rs.220 to B after 1yr.B asks A to pay Rs.110 in cash and defer the payment of Rs,.110 for 2 yrs.A agrees to it.If the rate of interest be 10% per annum in this mode of payment sol: A has to pay =Present worth of Rs220 due 1yr hence =Rs.(220*100)/(100+(10*1)) =Rs.200 A actually pays=Rs.110+Presentworth of Rs110 due 2 yrs hence =[110+ (Amount*100) /(100+(R*T))] =[110+((110*100)/(100+(10*2)))] =Rs192.66 So A gains Rs(200-192.66)=Rs.7.34

Top
Complex Problems 1.If Rs.10 be allowed as truedscount on a bill of Rs.110 at the end of a certaimn time ,then discount allowed on the same sum due at the end of double the time.. sol: Amount=Rs110 TrueDiscount=Rs10 Present worth=Amount-TrueDiscount =Rs110-10 =Rs.100 SI on Rs.100 for a certain time =Rs.10 SI on Rs.100 for doube the time =Rs.20 TrueDiscount on (100+20)=120-100 =Rs20 TrueDiscount on Rs.110 =(110*20)/120 =Rs18.33 2.A man wants to se hs scooter .There are two offers one at Rs12000 cash and other at acredit of Rs12880 to be paid

after 8 months ,money being at 18% per annum which is better offer? Sol: offer1=Rs12000 offer2 Present worth= (Amount*100) /(100+(R*T)) =Rs.12880*100/(100+(18*(8/12)) =Rs11,500 The first offer is better as if he gains 500/if he sells at Rs.12000 is better 3.Goods were bought for Rs.600 and sold the same day for Rs.688.80 at a credit of 9 months and thus gaining 2% rate of interest per annum is sol: MethodI: Amount=Rs.688.50 Time=9.12 Gaining 2%----------->Presentworth=102%of 600=(102*600)/100 =Rs.612 Presentworth=(Amount*100)/(100+(T*R)) 612=(688.80*100)/(100+((9/2)*R)) =>R=162/3% MethodII: TrueDiscount=688.50-612 =Rs.76.50 Rate=TrueDiscount*100/(P.W*T) =(76.50*100)/(612*(9/12)) =162/3% 4.The present worth of Rs.1404 due in 2 equal halfyearly instalments at 8% per annu8m S.I is SOl: Presentworth=(Amount*100)/(100+(T*R)) PresentWorth=Presentworth of Rs.702 6 months hence + Presentworth of Rs.702 1yr hence = (702*100)/(100+(1/2*8)) + (702t*100)/(100+(1*8)) =Rs.1325

Bankers Discount
Formulae: i. Suppose a merchant A buys goods worth Rs.10000 from another merchant B at a credit of say 5 months ii.Then,B prepares a bill , called the bill of exchange iii. A signs this bill & allows B to withdraw the amount from his bank account after exactly 5 months,the date exactly after

5 months is called Nominally due date iv. Three days (grace days) are added to it get a date known as legally due date v.Suppose B wants to have money before legally due date then he can have the money from banker or a broker who deducts S.I on the face value (i.e., 10000) for the period from the date on which the bill was discounted (i.e paied by the banker) & the legally due date this amount is known as Bankers Discount vi.Thus , B.D is the S.I on the face for the period from the date on which the bill was discounted and the legally due date vii.Bankers Gain (B.G) = (B.D) (T.D) for the unexpired time Note: When the date of the bill is not given,grace days are not to be added Formulae: (1)B.D = S.I on bill for unexpired time (2)B.G = (B.D) (T.D) = S.I on T.D = (T.D)^2 /P.W (3)T.D = sqrt(P.W * B.G) (4)B.D = (Amount * Rate * Time)/100 (5)T.D = (Amount * Rate * Time)/(100+(Rate * time) (6)Amount = (B.D * T.D)/(B.D T.D) (7)T.D = (B.G * 100)/(Rate * Time)

Top
Simple Problems 1.If the true discount on a certain sum due 6 months hence at 15% is Rs 120.What is the bankers discount on the same for same time and the same rate. Sol:B.G = S.I on T.D = RS (120 * 15 * = 9 (B.D) (T.D) = 9 B.D = 120 + 9 =129 * 1/100)

2.The bankers discount on Rs 1800 at 12 % per annum is equal to the true discount on Rs 1872 for the same time at the same rate .Find the time. Sol:S.I on Rs 1800 = T.D on Rs 1872 P.W of Rs 1872 is Rs 1800 Rs 72 is S.I on Rs 1800 at 12% Time = (100 * 72)/(12 * 1800) = 1/3 years = 4 months

3.The bankers discount and true discount on a sum of money due 8 months hence are Rs.120 & Rs.110 resp. Find the sum & the rate per cent Sol:Sum = (B.D * T.D) / (B.D) (T.D) = (120 * 110) / (120 110) = 1320

Since B.D is S.I on sum due, so S.I on Rs 1320 for 8 months is Rs 120 Rate = (100 * 120) / (1320 * 2/3) = 13 7/11% Medium Problems 1.The Bankers discount on Rs 1650 due a certain time hence is Rs 165. find the true discount and the bankers gain. Sol :Sum = (B.D * T.D) / (B.D T.D) = (B.D * T.D) / B.G T.D/B.G = Sum/B.D =650/165 =10/1 Thus if B.G is Rs 1 ,T.D = Rs 10 if B.D is Rs 11 ,T.D = Rs 10 if B.D is Rs 165,T.D = Rs (10/11 * 165) = 150 B.G =Rs(165 150) = Rs 15 2.The Present worth of a bill due something hence is Rs 1110 and the true discount on the bill is Rs.110 . Find the bankes discount & the bankers gain. Sol:T.D = sqrt (P.W * B.G) B.G = (T.D)^2 /P.W = (110 * 110) / 1110 = 11 B.D = (T.D + B.G) = (110 + 11) = Rs 121

3.What rate percent does a man get for his money when in discounting Sol:Let the amount of the bill =100 Money deducted = 10 Money received by the holder of the bill = (100 10) = 90 S.I on Rs 90 for 10 months = 10 Rate = (100 * 10) / (90 * 10/12) = 13 1/3%

Top
Complex Problems 1.A bill for Rs.6000 is drawn on July 14 at 5 months . It is discounted on 5th October at 10%.Find the bankers discount true discount, bankers gain and the money that the holder of the bill receives. Sol:Face value of the bill = Rs.6000 date on which the bill was drawn = July 14 at 5 months nominally due date = December 14 legally due date = December 17 Date on which the bill was discounted = October 5 Unexpired time : Oct Nov Dec 26 + 30 + 17 = 73days =1/5 years B.D = S.I on Rs 6000 for 1/5 year = Rs (6000 * 10 * 1/5 * 1/100) = Rs 120 T.D = Rs(6000 * 10 *1/5)/(100 + (10 * 1/5)) = Rs. 117.64

B.G = (B.D) (T.D) = Rs(120 -117.64) = Rs 2.36 Money received by the holder of the bill = Rs(6000 120) = 5880 2. The bankers gain on a certain sum due 1 year hence is 3/25 of the bankers discount .The rate percent is Sol:Let B.D = 1 then B.G = 3/25 T.D = (B.D B.G) = (1 3/25) = 22/25 sum = (1 * 22/25) / (1 22/25) = 22/3 S.I on Rs 22/3 for 1 year is 1. Rate = (100 * 1) / (22/3 * 3/2) = 9 1/9%

3. The bankers gain of a certain sum due 2 years hence at 10% per annum is Rs 24 .The percent worth is Sol:T.D = (B.G * 100) / (Rate * Time) 00) / (10 * 2) = 120. P.W = (100 *T.D) / (Rate * Time) = (100 * 120) /(10 * 2) = 600

Oddman Out and Series


Introduction: In any type of problems,a set of numbers is given in such a way that each one except one satiesfies a particular definite property.The one which does not satisfy that characteristic is to be taken out. Some important properties of numbers are given below : 1.Prime Number Series Example: 2.Even Number Series Example: 3.Odd Number Series: Example: 4.Perfect Squares: Example: 2,3,5,7,11,.............. 2,4,6,8,10,12,........... 1,3,5,7,9,11,........... 1,4,9,16,25,............

5.Perfect Cubes: Example: 1,8,27,64,125,................. 6.Multiples of Number Series: Example: 3,6,9,12,15,..............are multiples of 3 7.Numbers in Arthimetic Progression(A.P): Example: 13,11,9,7................ 8.Numbers in G.P: Example: 48,12,3,..... Some More Properties: 1. If any series starts with 0,3,.....,generally the relation will be (n2-1). 2. If any series starts with 0,2,.....,generally the relation will be (n2-n). 3. If any series starts with 0,6,.....,generally the relation will be (n3-n). 4. If 36 is found in the series then the series will be in n2 relation. 5. If 35 is found in the series then the series will be in n2-1 relation. 6. If 37 is found in the series then the series will be in n2+1 relation. 7. If 125 is found in the series then the series will be in n3 relation. 8. If 124 is found in the series then the series will be in n3-1 relation. 9. If 126 is found in the series then the series will be in n3+1 relation. 10. If 20,30 found in the series then the series will be in n2-n relation. 11. If 60,120,210,........... is found as series then the series will be in n3-n relation. 12. If 222,............ is found then relation is n3+n 13. If 21,31,.......... is series then the relation is n2-n+1. 14. If 19,29,.......... is series then the relation is n2-n-1. 15. If series starts with 0,3,............ the series will be on n2-1 relation.

To p
Problems 1.Find the odd one out.3,5,7,12,17,19 SOLUTION: The above series except 12 all elements are odd numbers.so 12 is the odd one. 2.Find the odd one out.1,4,9,16,23,25,36 SOLUTION: In the above series all elements except 23 are perfect sqares. so 23 is odd one.

3.Find the odd one out.41,43,47,53,61,71,73,81 SOLUTION: In the above series all elements except 81 are prime numbers. so 81 is odd one. 4.Find the odd one out.1,4,9,16,20,36,49 SOLUTION: In the above series all elements except 20 are perfect squares. So 20 is odd one. 5.Find the odd one out.8,27,64,100,125,216,343 SOLUTION: In the above series all elements except 100 are perfect cubes. so 100 is odd one. 6. Find the odd one out.1,5,14,30,50,55,99 SOLUTION: In the above series all elements in the pattern like 12, 12+22,12+22+32,................. But 50 is not in this pattern,so odd one. 7.Find the odd one out.835,734,642,751,853,981,532 SOLUTION: In the above series,the difference between third and first digit of each element is equal to its middle digit.But 751 is not in this pattern,so odd one. 8.Find the odd one out.385,4462,572,396,427,672,264 SOLUTION: In the above series,the sum of first and third digit of each element is equal to its middle digit.But 427is not in this pattern,so odd one. 9.Find the odd one out.331,482,551,263,383,242,111 SOLUTION: In the above series,the product of first and third digit of each element is equal to its middle digit. But 383 is not in this pattern,so odd one. 10. Find the odd one out.2,5,10,17,26,37,50,64 SOLUTION: In the above series,the elements are in the pattern of x2+1, Where x is 1,2,3,4,5,6,7.but 82+1 is not equal to 64.It is 65.64 is odd one. 11.Find the odd one out. 19,28,39,52,67,84,102 SOLUTION:

In the above series,the elements are in the pattern of x2+3, Where x is 4,5,6,7,8,9,10.but 102+3 is not equal to 102. It is 103.so 102 is odd one.

To p
12.Find the odd one out.253,136,352,460,324,613,244 SOLUTION: In the above series,the elements are in the pattern of x2+3, Where x is 4,5,6,7,8,9,10.but 102+3 is not equal to 102.It is 103.so 102 is odd one. 13.Find the odd one out. 2,5,10,50,500,5000 SOLUTION: In the above series,the pattern as follows: 1st term * 2nd term = 3rd term 2nd term * 3rd term = 4th term 3rd term * 4th term = 5th term But 50*500=25000 which is not equal to 5000. so 5000 is odd one. 14.Find the odd one out. 582,605,588,611,634,617,600 SOLUTION: In the above series, alternatively 23 is added and 17 is subtracted from the terms. So 634 is odd one. 15.Find the odd one out.46080,3840,384,48,24,2,1 SOLUTION: In the above series,the terms are successively divided by 12,10,8,6,..... so 24 is not in this pattern. so 24 is odd one. 16.Find the odd one out.5,16,6,16,7,16,9 SOLUTION: In the above series,the terms at odd places are 5,6,7,8....... and at even places is 16. So 9 is odd one. 17.Find the odd one out.6,13,18,25,30,37,40 SOLUTION: In the above series,the difference between two successive terms from the beginning are 7,5,7,5......... so 40 is odd one. 18.Find the odd one out.56,72,90,110,132,150 SOLUTION: The above series as follows: 7*8,8*9,9*10,10*11,11*12,12*13. So it will be 56,72,90,110,132,156 so 150 is wrong. 19.Find the odd one out. 1,2,6,15,31,56,91

SOLUTION: Add 1square ,2square ,....,6square so 91 is wrong.

to the terms.

20.Find the odd one out.105,85,60,30,0,-45,-90 SOLUTION: Subtract 20,25,30,35,40,45 So 0 is odd one. from the terms.

21.Find out the odd one out.3,10,21,36,55,70,105 SOLUTION: The pattern in the series is 1*3, 2*5, 3*7, 4*9, 5*11, 6*13, 7*15. So the series will be 3,10,21,36,55,78,105. So 70 is wrong term in the series.

To p
22.Find out the odd one out. 4,9,19,39,79,160,319 SOLUTION: Double the number and add 1 to it. So the series will be 4,9,39,79,159,319. So 160 is wrong. 23.Find out the odd one out.10,14,28,32,64,68,132. SOLUTION: Alternatively add 4 and double the next term. So 132 is wrong. COmplex Problems 1.Find the missing term in the series: 4,-8,16,-32,64,( ) SOLUTION: The terms are doubled and change the sign. So the next term is -128 2.16,33,65,131,261,( SOUTION: )

The terms are doubled and 1 is added. So 261*1+1=522+1=523 So the missing term is 523. )

3.2,6,12,20,30,42,56,(

SOLUTION: The pattern is 1 * 2 , 2 * 3 , 3 * 4 , 4 * 5 , 5 * 6 , 6 * 7 , 7 * 8 , 8 * 9 . So the series is 2,6,12,20,30,42,56,72. So 72 is the missing term.

4.

8,24,12,36,18,54,(

SOLUTION: Numbers are alternatively multiplied by 3 and divided by 2. So the next term is 54 / 2 = 27. 5. 165,195,255,285,345,( )

SOLUTION: Each number is 15 multiplied by a prime number. i.e the series is 15*11,15*13,15*17,15*19,15*23,15*29. So series is 165,195,255,285,345,435. So 435 is the missing term.

To p
6. 7,16,63,124,215,342,( ). SOLUTION: Numbers are 23 -1,33-1,43-1,....................so 83-1=511. So 511 is the missing term. 7.2,4,12,48,240,( SOLUTION: )

Go on multiplying by 2,3,4,5,6. So the last term in the series is 240*6=1440. )

8.8,7,11,12,14,17,17,22,( SOLUTION:

There are two series 8,11,14,17,20 and 7,12,17,22 So increasing by 3 and 5.So 20 the missing term. 9.71,76,69,74,67,72,( SOLUTION: )

Alternately add 5 and subtract 7. so the series is 71+5=76

10.10.2,5,9,19,37 SOLUTION: Second number is one more than twice the first,Third number is one less than twice the second,Forth is one more than twice the third and so on. So the next number is 2 * 37 + 1 = 74+1 = 75. 11. Find the wrong number in the given series. 3,8,15,24,34,48,63 SOLUTION: The difference between consecutive terms are respectively 5,7,9,11,13. So 34 is the wrong number in the series.

12.

125,106,88,76,65,58,53

SOLUTION: Subtract 24,21,18,15,12,9 from the numbers to get the next number. So 128 is wrong. 13. 1,1,2,6,24,96,720 SOLUTION: Multiply with 1,2,3,4,5,6 to get the next number. So 96 is wrong. 14 . 32,36,41,61,86,122,171,235 SOLUTION: Second term = First term + 22 Third term = Second term + 32 Fourth term = Third term + 42 Fifth term = Forth term + 52 Sixth term = Fifth term + 62 Seventh term = Sixth term + 72 So the third term should be 45 instead of 41.

15 . 15,16,34,105,424,2124,12576 SOLUTION: Second term = First term * 1 + 1 = 16 Third term = Second term * 2 + 2 = 34 Forth term = Third Term * 3 + 3 = 105 Fifth term = Forth term * 4 + 4 = 424 Sixth term = Fifth term * 5 + 5 =2125 Seventh term = Sixth term * 6 + 6 = 12576. So 2124 is wrong.

16 . 40960,10240,2560,640,200,40,10 SOLUTION: Go on dividing by 4 ,the series will be 40960,10240,2560,640,160,40,10. So 200 is wrong. 17.7,8,18,57,228,1165,6996 SOLUTION: Let the numbers be A,B,C,D,E,F,G then A,A*1+1,B*2+2,C*3+3,............ so 288 is wrong. 18. 19,26,33,46,59,74,91 SOLUTION: Go on adding 7,9,11,13,15,17. So 33 is wrong.

19 . 10,26,74,218,654,1946,5834. SOLUTION:

Second term = first term * 3 4 = 26. Third term = Second term * 3 4 =74 Forth term = Third term * 3 4 =218 Fifth term = Forth term * 3 4 =650 So 654 is wrong .

Probability
Introduction: Experiment: An operation which can produce some well-defined outcome is called an experiment. Random Experiment: An experiment in which all possible out comes are known and the exact output cannot be predicted in advance is called a random experiment. EX: 1) Rolling an unbiased dice. 2) Tossing a fair coin. 3) Drawing a card from a pack of well-shuffled cards . 4)Picking up a ball of certain colour from a bag containing balls of different colours. Details: 1) When we thrown a coin ,then either a Head(H) or a Tail(T) appears. 2)A dice is a solid cube ,having 6 faces,marked 1,2,3,4,5,6 respectively. When we throw a die ,the outcome is the number that appears on its upper face. 3)A pack of cards has 52 cards. It has 13 cards of each suit,namely spades,clubs,hearts and diamonds. Cards of spades and clubs are balck cards. Cards of hearts and diamonds are red cards. There are four honours of each suit. These are Aces,Kings,queens and Jacks. These are called Face cards. Sample Space: When we perform an experiment ,then the set of S of all possible outcomes is called the Sample space . EX: 1)In tossing a coin S= {H,T}. 2)If two coins are tossed then S= {HH,HT,TH,TT}. 3)In rolling a dice ,we have S={1,2,3,4,5,6}. Event:Any subset of a sample space is called an Event. Probability of occurrence of an Event:

Let S be the sample space. Let E be the Event. Then E cS i.e E is subset of S then probability of E p(E) =n(E)/n(S). Reults on Probability: 1)P(S) =1. 2)0 < P(E) < 1 probability of an event lies between 0 and 1. Max value of probability of an event is one. 3)P()=0. 4)For any events A and B we have . P(AUB) =P(A) +P(B) -P(AnB). 5)If A denotes (not -A) then P(A) =1-P(A) P(A)+P(A) =1.

Top
Problems: 1)An biased die is tossed.Find the probability of getting a multiple of 3? Sol: Here we have sample space S={1,2,3,4,5,6}. Let E be the event of getting a multiple of 3. Then E={3,6}. P(E) =n(E)/n(S). n(E) =2, n(S) =6. P(E) =2/6 P(E) =1/3. 2)In a simultaneous throw of a pair of dice,find the probability of getting a total more than 7? Sol: Here we have sample space n(S) =6*6 =36. Let E be the event of getting a total more than 7. ={(1,6),(2,5),(3,4),(4,3)(5,2),(6,1)(2,6),(3,5),(4,4), (5,3),(6,2),(4,5),(5,4), (5,5),(4,6),(6,4)} n(E) =15 P(E) = n(E)/n(S) = 15/36. P(E) = 5/12. 3)A bag contains 6 white and 4 black balls .Two balls are drawn at random .Find the probability that they are of the same colour? Sol: Let S be the sample space. Number of ways for drawing two balls out of 6 white and 4 red balls = 10C2 =10!/(8!*2!) = 45. n(S) =45. Let E =event of getting both balls of the same colour. Then n(E) =number of ways of drawing ( 2balls out of 6) or

(2 balls out of 4). = 6C2 +4C2 = 6!/(4!*2!) + 4!/(2! *2!) = 6*5/2 +4 *3/2 =15+6 =21. P(E) =n(E)/n(S) =21/45 =7/45. 4)Two dice are thrown together .What is the probability that the sum of the number on the two faces is divisible by 4 or 6? Sol: n(S) = 6*6 =36. E be the event for getting the sum of the number on the two faces is divisible by 4 or 6. E={(1,3)(1,5)(2,4?)(2,2)(3,5)(3,3)(2,6)(3,1)(4,2)(4,4) (5,1)(5,3)(6,2)(6,6)} n(E) =14. Hence P(E) =n(E)/n(S) = 14/36. P(E) = 7/18 5)Two cards are drawn at random from a pack of 52 cards What is the probability that either both are black or both are queens? Sol: total number of ways for choosing 2 cards from 52 cards is =52C2 =52 !/(50!*2!) = 1326. Let A= event of getting bothe black cards. Let B= event of getting bothe queens AnB=Event of getting queens of black cards n(A) =26C2. We have 26 black cards from that we have to choose 2 cards. n(A) =26C2=26!/(24!*2!) = 26*25/2=325 from 52 cards we have 4 queens. n(B) = 4C2 = 4!/(2!* 2!) =6 n(AnB) =2C2. =1 P(A) = n(A) /n(S) =325/1326 P(B) = n(B)/n(S) = 6/1326 P(A n B) = n(A n B)/n(S) = 1/1326 P(A u B) = P(A) +P(B) -P(AnB) = 325/1326 + 6/1326 -1/1326 = 330/1326 P(AuB) = 55/221 6)Two diced are tossed the probability that the total score is a prime number? Number of total ways n(S) =6 * 6 =36 E =event that the sum is a prime number. Then E={(1,1)(1,2)(1,4)(1,6)(2,1)(2,3)(2,5)(3,2)(3,4)(4,1) (4,3)(5,2)(5,6)(6,1)(6,5)} n(E) =15 P(E) =n(E)/n(S) = 15/36 P(E) = 5/12

Top

7)Two dice are thrown simultaneously .what is the probability of getting two numbers whose product is even? Sol : In a simultaneous throw of two dice ,we have n(S) = 6*6 = 36 E=Event of getting two numbers whose product is even E={(1,2)(1,4)(1,6)(2,1)(2,2)(2,3)(2,4)(2,5)(2,6)(3,2) (3,4)(3,6)(4,1)(4,2)(4,3)(4,4)(4,5)(4,6)(5,2)(5,4)(5,6)(6,1) (6,2)(6,3)(6,4)(6,5)(6,6)} n(E) = 27 P(E) = n(E)/n(S) = 27 /36 P(E) =3/4 probability of getting two numbers whose product is even is equals to 3/4. 8)In a lottery ,there are 10 prozes and 25 blanks.A lottery is drawn at random. what is the probability of getting a prize ? Sol: By drawing lottery at random ,we have n(S) =10C1+25C1 = 10+25 = 35. E =event of getting a prize. n(E) =10C1 =10 out of 10 prozes we have to get into one prize .The number of ways 10C1. n(E) =10 n(S) =35 P(E) =n(E)/n(S) =10/35 = 2/7 Probability is 2/7. 9)In a class ,30 % of the students offered English,20 % offered Hindi and 10 %offered Both.If a student is offered at random, what is the probability that he has offered English or Hindi? Sol:English offered students =30 %. Hindi offered students =20% Both offered students =10 % Then only english offered students E =30 -10 =20 % only Hindi offered students S =20 -10 % = 10 % All the students =100% =E +S +E or S 100 =20 +10 + E or S +E and S Hindi or English offered students =100 -20-10-10 =60 % Probability that he has offered English or Hindi =60/100= 2/5 10) A box contains 20 electricbulbs ,out of which 4 are defective, two bulbs are chosen at random from this box.What is the probability that at least one of these is defective ? Sol: out of 20 bulbs ,4 bulbs are defective. 16 bulbs are favourable bulbs. E = event for getting no bulb is defective.

n(E) =16 C 2 out of 16 bulbs we have to choose 2 bulbs randomly .so the number of ways =16 C 2 n(E) =16 C2 n(S) =20 C 2 P(E) =16 C2/20C2 = 12/19 probability of at least one is defective + probability of one is non defective =1 P(E) + P(E) =1 12/19 +P(E) =1 P(E) =7/19 11)A box contains 10 block and 10 white balls.What is the probability of drawing two balls of the same colour? Sol: Total number of balls =10 +10 =20 balls Let S be the sample space. n(S) =number of ways drawing 2 balls out of 20 = 20 C2 = 20 !/(18! *2!) = 190. Let E =event of drawing 2 balls of the same colour. n(E) =10C2+ 10C2 = 2(10 C2) = 90 P(E) =n(E)/n(S) P(E) =90/190 = 9/19 12) A bag contains 4 white balls ,5 red and 6 blue balls .Three balls are drawn at random from the bag.What is the probability that all of them are red ? Sol: Let S be the sample space. Then n(S) =number of ways drawing 3 balls out of 15. =15 C3. =455 Let E =event of getting all the 3 red balls. n(E) = 5 C3 =5C2 = 10 P(E) =n(E) /n(S) =10/455 =2/91.

Top
13)From a pack of 52 cards,one card is drawn at random.What is the probability that the card is a 10 or a spade? Sol: Total no of cards are 52. These are 13 spades including tne and there are 3 more tens. n(E) =13+3 = 16 P(E) =n(E)/n(S). =16/52 P(E) =4/13. 14) A man and his wife appear in an interview for two vacancies in the same post.The probability of husband's selection is 1/7 and the

probabililty of wife's selection is 1/5.What is the probabililty that only one of them is selected? Sol: let A =event that the husband is selected. B = event that the wife is selected. E = Event for only one of them is selected. P(A) =1/7 and p(B) =1/5. P(A') =Probability of husband is not selected is =1-1/7=6/7 P(B') =Probaility of wife is not selected =1-1/5=4/7 P(E) =P[(A and B') or (B and A')] = P(A and B') +P(B and A') = P(A)P(B') + P(B)P(A') = 1/7*4/5 + 1/5 *6/7 P(E) =4/35 +6/35=10/35 =2/7 15)one card is drawn at random from a pack of 52 cards.What is the probability that the card drawn is a face card? Sol: There are 52 cards,out of which there 16 face cards. P(getting a face card) =16/52 = 4/13 16) The probability that a card drawn from a pack of 52 cards will be a diamond or a king? Sol: In 52 cards 13 cards are diamond including one king there are 3 more kings. E event of getting a diamond or a king. n(E) =13 +3 = 16 P(E) =n(E) /n(S) =16/52 =4/13 17) Two cards are drawn together from apack of 52 cards.What is the probability that one is a spade and one is a heart ? Sol: S be the sample space the n (S) =52C2 =52*51/2 =1326 let E =event of getting 2 kings out of 4 kings n(E) =4C2 = 6 P(E) =n(E)/n(S) =6/1326 =1/221 18) Two cards are drawn together from a pack of 52 cards.What is the probability that one is a spade and one is a heart? Sol: Let S be the sample space then n(S) =52C2 =1326 E = Event of getting 1 spade and 1 heart. n(E) =number of ways of choosing 1 spade out of 13 and 1 heart out of 13. = 13C1*13C1 =169 P(E)= n(E)/n(S)

=169/1326 =13/102. 19) Two cards are drawn from a pack of 52 cards .What is the probability that either both are Red or both are Kings? Sol: S be the sample space. n(S) =The number of ways for drawing 2 cards from 52 cards. n(S) =52C2 =1326 E1 be the event of getting bothe red cards. E2 be the event of getting both are kings. E1nE2 =Event of getting 2 kings of red cards. We have 26 red balls.From 26 balls we have to choose 2 balls. n(E1) =26C2 = 26*25/2 =325 We have 4 kings .out of 4 kings,we have to choosed 2 balls. n(E2) =4C2 =6 n(E1nE2) =2C2 =1 P(E1) = n(E1)/n(S) =325/1326 P(E2) =n(E2)/n(S) =6/1326 P(E1nE2) =n(E1nE2)/n(S) =1/1326 P(both red or both kings) = P(E1UE2) = P(E1) +P(E2)-P(E1nE2) =325/1326 +6/1326 -1/1326 =330/1326 =55/221

Permutations and Combinations


Formulae: Factorial Notation: Let n be positive integer.Then ,factorial n dentoed by n! is defined as n! = n(n-1)(n-2). . . . . . . .3.2.1 eg:- 5! = (5 * 4* 3 * 2 * 1) = 120 0! = 1 Permutations: The different arrangements of a given number of things by taking some or all at a time,are called permutations. eg:- All permutations( or arrangements)made with the letters a,b,c by taking two at a time are (ab,ba,ac,ca,bc,cb) Numbers of permutations: Number of all permutations of n things, taken r at a time is given by nPr = n(n-1)(n-2). . .. . . (n-r+1) = n! / (n-r)! An Important Result: If there are n objects of which p1 are alike of one kind;

p2 are alike of another kind ; p3 are alike of third kind and so on and pr are alike of rth kind, such that (p1+p2+. . . . . . . . pr) = n Then,number of permutations of these n objects is: n! / (p1!).(p2!). . . . .(pr!) Combinations: Each of different groups or selections which can be formed by taking some or all of a number of objects,is called a combination. eg:- Suppose we want to select two out of three boys A,B,C . then ,possible selection are AB,BC & CA. Note that AB and BA represent the same selection. Number of Combination: The number of all combination of n things taken r at atime is: nCr = n! / (r!)(n-r)! = n(n-1)(n-2). . . . . . . tor factors / r! Note: nCn = 1 and nC0 =1 An Important Result: nCr = nC(n-r)

Top
Problems 1.Evaluate 30!/28! Sol:30!/28! = 30 * 29 * (28!) = 30 * 29 =870 / (28!)

2.Find the value of 60P3 Sol:- 60P3 = = = = 60! / (60 3)! = 60! / 57! (60 * 59 *58 * (57!) )/ 57! 60 * 59 *58 205320

3. Find the value of 100C98,50C 50 Sol:100C98 = 100C100-98) = 100 * 99 / 2 *1 = 4950 50C50 = 1

4.How many words can be formed by using all the letters of the word DAUGHTR so that vowels always come together & vowels are never together? Sol:(i) Given word contains 8 different letters When the vowels AUE are always together we may suppose them to form an entity ,treated as one letter then the letter to be arranged are DAHTR(AUE) these 6 letters can be arranged in 6p6 = 6! = 720 ways The vowels in the group (AUE) may be arranged in 3! = 6 ways Required number of words = 760 * 6 =4320

(ii)Total number of words formed by using all the letters of the given words 8! = 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 = 40320 Number of words each having vowels together = 760 * 6 = 4320 Number of words each having vowels never together = 40320 4320 = 36000 5.In how many ways can a cricket eleven be chosen out of a batch of 15 players. Sol:- Required number of ways = 15C 11 = 15C (15-11) = 15 C 4 15C4 = 15 * 14 * 13 * 12 / 4 * 3 * 2 *1 = 1365 6.In how many a committee of 5 members can be selected from 6men 5 ladies consisting of 3 men and 2 ladies Sol:(3 men out of 6) and (2 ladies out of 5) are to be chosen Required number of ways =(6C3 * 5C2) = 200

7.How many 4-letter word with or without meaning can be formed out of the letters of the word 'LOGARITHMS' if repetition of letters is not allowed Sol:'LOGARITHMS' contains 10 different letters Required number of words = Number of arrangements of 100 letters taking 4 at a time = 10P4 = 10 * 9 * 8 * 7 = 5040

8.In how many ways can the letter of word 'LEADER' be arranged Sol:The word 'LEADER' contains 6 letters namely 1L,2E,1A,1D and 1R Required number of ways = 6! / (1!)(2!)(1!)(1!)(1!) = 6 * 5 * 4 * 3 * 2 *1 / 2 * 1 =360

Top
9.How many arrangements can be made out of the letters of the word 'MATHEMATICS' be arranged so that the vowels always come together Sol:In the word ' MATHEMATICS' we treat vowels AEAI as one letter thus we have MTHMTCS(AEAI)

now we have to arrange 8 letters out of which M occurs twice ,T occurs twice & the rest are different Number of ways of arranging these letters = 8! / (2!)(2!) = 10080 now AEAI has 4 letters in which A occurs 2 times and the rest are different Number of ways of arranging these letters = 4! / 2! = 12 Required number of words = (10080 * 12) = 120960 10.In how many different ways can the letter of the word 'DETAIL' be arranged in such a way that the vowels occupy only the odd positions Sol:These are 6 letters in the given word , out of which there are 3 vowels and 3 consonants Let us mark these positions as under

(1)(2) (3) (4)(5)(6) now 3 vowels can be placed at any of the three places out of 4 marked 1,3,5 Number of ways of arranging the vowels = 3P3 = 3! =6 Also,the 3 consonants can be arranged at the remaining 3 positions Number of arrangements = 3P3 = 6 Total number of ways = (6 * 6) =36 11.How many 3 digit numbers can be formed from the digits 2,3,5,6,7 and 9 which are divisible by 5 and none of the digits is repeated? Sol:- Since each desired number is divisible by so we much have 5 at the unit place. can now be filled by any of the remaining 4 4 ways of filling it. Required number of numbers = (1 * 5 * = 20 12.In how many ways can 21 books on English and be placed in a row on a self so that two books be together? Sol:5, The hundreds place digits .so, there 4) 19 books on Hindi on Hindi may not

In order that two books on Hindi are never together, we must place all these books as under: X E X E X . . . . . . . . . . X E X Where E denotes the position of an English and X that of a Hindi book. Since there are 21 books on English,the number of places marked X are therefore 22. Now, 19 places out of 22 can be chosen in 22 C 19 = 22 C 3 =22 * 21 * 20 / 3 * 2 *1 Hence the required number of ways = 1540

13.Out of 7 constants and 4 vowels how many words of 3 consonants and 2 vowels can be formed? Sol:Number of ways of selecting (3 consonants out of 7) and (2 vowels out of 4) = 7C3 * 4C2

= 210 Number of groups each having 3 consonants and 2 vowels = 210 Each group contains 5 letters Number of ways of arranging 5 letters among themselves = 5! = (5 * 4 * 3 * 2 * 1) = 210 Required number of words = (210 * 210) = 25200

Puzzles
Introduction: Puzzles are dealt in a detailed manner with certain solutions. Different puzzles are gathered from ShakuntalaDevis puzzle books. Keeping in mind certain puzzles for Infosys some reasoning problems are also dealt. Puzzle name at the top of each problem will give a brief idea regarding the mode of application. SELECTING A CANDIDATE For an advertisement of six local posts,twelve persons applied for the job.Can you tell in how many different ways the selection can be made? Solution: 6^12 SET OF BAT AND BALL When I wanted to buy a bat and ball, the shopkeeper said they would together cost Rs.3.75.But I did not want to buy a ball. The shopkeeper said that bat would cost 75paise more than the ball.What was the cost of bat and the ball? Soluton: Given that bat and ball together cost Rs.3.75 = 375paise Let cost of the ball alone be x. Given cost of the bat is 75p greater than cost of the ball. So cost of the bat = x+75 x+x+75 = 375 2x = 375 75 2x = 300 x = 150p Hence cost of the ball = Rs.1.50 =>Cost of the bat = 1.50 + 75 = Rs.2.25 PLAYING CHILDREN A group of boys and girls are playing.15 boys leave.There remain 2 girls for each boy.Then 45 girls leave.There remain 5 boys for

each girl.How many boys were in the orginal group? Solution: Let B and G represent no.of boys and girls in the original group respectively. G ---------> 2 B-15 ----------> 1 G/B-15 = 2/1 i.e., 2 girls are left for 15 boys who are alone. G-45 -------------------->1 B-15 ------------------------->5 5 boys are left out when 15 girls are alone. =>G/B-15=2/1 --------------------------------(1) =>G-45/B-15 =1/5 ----------------------------(2) (1) & (2) => G = 2B-30 5G 225 = B - 15 5 ( 2B 30 ) = B 15 + 225 10B = B 15 + 225 + 150 9B = 360 B = 40 (1)=> G/40-15 = 2 G=50 girls.

Top
Problems 1.Reshma appeared for a maths exam.She was given 100 problems to solve.She tried to solve all of them correctly but some went wrong.But she scored 85. Her score was calculated by subtracting two times th no.of wrong answers from the no.of correct answers. How many problems did Reshma do correctly? Soluton: Assume W as wrong answers and R as correct answers Given total no.of questions as 100 R+W=100 ---------------------------(1) Score is calculated by subtracting 2 times wrong answers(2W) from right answers(R) and given as 85 R-2W=85 -------------------------------(2) (2)-(1) R-2W=85 R+W=100 --------------------W=5 Hence,100-5=95 is the no.of correct answers of Reshma. 2.A RUNNNG RACE Sneha,Shilpa,Sushma join a running race.The distance is 1500 metres. Sneha beats Shilpa by 30 metres and Sushma by 100 metres.By how much could Shilpa beat Sushma over the full distance if they both ran as before? Solution: Total distance covered by Sneha=1500m Shilpa=1500-30=1470 Sneha =1500-100=1400

Distance covered by Shilpa=1500*1400/1470=1428.6 Distance to be covered by Shilpa to beat Sushma over full distance 1500-1428.6=71.4m 3.FILLING A CISTERN Pipe S1 can fill a cistern in 2 hours and pipe S2 in 3 hours.Pipe S3 can empty it in 5 hours.Supposing all the pipes are turned on when the cistern is competely empty,how long will it take to fill? Solution: S1 fills cistern in 1/2 hours S2 fills cistern in 1/3 hours S3 empties it in 1/5 hours A the pipes S1,S2,S3 working i.e.,filling the cistern 1/2+1/3-1/5=15+10-6/30=25-6/30=19/30 No.of hours to fill=30/19=1 11\19hours. 4.SEQUENCE PROBLEMS What are the next two terms in the sequence?1,1,5,17,61,217......... Solution: The order in this cases is Tn=3*Tn-1 +2*Tn-2 = 3(217)+2(61) = 773 Tn+1=3(773)+2(271) =2319+542 =2753 5.SEQUENCES What are the next two terms in the sequence? 1,1,5,17,61,217................. Solution: Tn=3Tn-1+2Tn-2 =3(217)+2(61) =773 Tn+1=3(773)+2(217)=2753 6.What are the next three terms to the series? 1+3+7+15+31+63........... Solution: Actual term is 2exp n-1. The next three terms are: 2exp7-1=127 2exp8-1=255 2exp9-1=511 7.A PROBLEM OF SHOPPING Samsrita went out for shopping by taking with her Rs.15/- in one rupee notes and 20p coins.On return she had as many one rupee notes as she originally had and as many 20p coins as she had one rupee notes.She came back with 1/3rd with what she had.How much did

Samsrita spend and how much did she take? Solution: Let x be no.of rupee notes y be no.of 20pcoins. So,when going for shopping 100x+20y paise were there with Samsrita. On return she had 100y+20x paise. Also it is given that she had 1/3 rd of the orginal amount. 1/3(10x+20y)=100y+20x =>4x=280y =>x=7y y=1 => x=7 total =7.20 <15 y=2 =>x=14 total=14.40~=15 y=3 =>x=21 total=21.60 >>15 Hence the suitable value nearer to the amunt is 14.40 and so is the amount Samsrita carried with her. 1/3(1440)=480paise. Rs.4.80/- is amount spent by Samsrita. 8.A PUZZLE OF CULTURAL GROUPS Literary,Dramatic,Musical,Dancing and Painting are the 5 groups of a club.Literary group meets every other day,dramatic every third day,musical every fourth day,dancing every fifth day,painting every sixth day.Five groups meet on NewYears day of 1975 and starting from that day they met regularly on schedule. How many times did all the 5 groups meet on same day in first quarter excluding Jan1,1975.How many days did none of them met? Solution: LCM of 2,3,4,5,6 is 60. Hence excluding Jan1,1975 they met on every 61st day. 60/2=30 60/3=20 60/4=15 60/5=12 60/6=10 Literary meet for 30 2 day intervals. Dramatic meet for 20 3 day intervals. Musical meet for 15 4 day intervals. Dancing meet for 12 5 day intervals. Paintng meet for 10 6 day intervals. First quartr implies 3 months with 90 days. so inorder to a nswer that how many days do they don/t meet atleast once in first quarter is got by rounding all other categories. By counting all the intervals for other groups no.of days in Jan 8,Feb 7,Mar 9. Total is 24. 9.STOLEN MANGOES Three naughty boys stole some mangoes from a garden.Among them one counted and ate one.From the remainder he took precise third and went back to sleep. After sometime second boy woke up,counted the mangoes,ate one,took an exact third of the remaining and went back to sleep. After sometime third boy also did the same.In the morning they found one which was rotten and hence threw it away from the remainder,they made an exact division.How many mangoes did they steal? Solution: Let the noof mangoes be x After the first boy had eaten noof mangoes =x-1 After taking 1/3 rd of remaining it is 2x-2/3

Second boy ate one and tok 1/3 then it is 2(2x-2/3 -1)=4x-10/9 Third boy ate and tok 1/3 as 2(4x-19)/27=8x-38/27 Deducting the rotten one from remaining noogf mangoes left =8x-38/27=8x-765/27 This is divided among the three equally 8x-65/27=3n 8x=81n+65 Let n be equal to odd number 2b+1 8x=81(2b+1)+65 4x=81b+73 Let b=2c+1 4x=81(2c+1)+73 2x=81c+77 Let c=2d+1 x=81d+79 Least value of x for d=0 is 79 for d=1 is 160 for d=3 is 241 On verfication,79-1=78/3=26 Hence 79 is the correct answer.

Top
10.AN ELECTION PROBLEM My club had a problem recently.They had to appoint a Ssecretary from among the men and a joint secretary from among the women. We have a membership of 12 men and 10 women.In how many ways can the selection be made? Solution: As per the permutations and combinatins concept of mathematics, out of 12 men one selected as secretary can be done in 12c1 ways out of 10 women one selected as joint secretary can be done in 10c1 ways Hence one secrtary and one joint secretary is 12*10=120 11.SNAPPING A PLANE A plane has a span of 12 metres.It was photographed as it was flying directly overhead with a camera with a depth of 12cm.In the photo the span of the plane was same.Can you tell how higher was the plane when it was snapped? Solution: Actual span of the plane was 12m Span of the plane n photograph was 800m Depth of the plane is 12000m=12cm Hence,height of the plane when photographed be x 12000:800 = x:12 x=180m 12.A THRST PROBLEM Pramatha and Pranathi went camping.They took their own water in bg plastic bottles. Pramatha got thirsty and drank half the water in her bottle.A little later on she drank 1/3 f what was left.Sometime afterwards she drank 1/4 of what remained and so on Pranathi also had a bottle of the same size.She drank half the bottle at the first instance ,half of what remained when she drank next and so on. Aftr each took 10 drins ,the water Pramatha left was how many times greatr than the water Pranathi had left?

Soltuion: Pramatha for the first drink 1/2 for the second drink 1/3 for the third drink 1/4 She drank 10 times and hence by the end of the 10th drink 1/11 of water she had in the bottle was over. Pranathi for the first drink 1/2 for the second drin 1/4 for the third drink 1/8 So Pranathi as per the given information has drunk 1/1024 of water she had in the bottle. Water left for Pramatha/Water left for Pranathi=1/11 / 1/1024 =1024/11 13.NAME OF THE EXCHANGE In GreatBritain some years ago the first threeletters of a telephone number usd to indicate the name of the exchangeHow many such arrangements of 3 letters is it possible to devise from the 26 letters of the alphabet? Solution: For permutations the no.of ways to select is npr=n!/(n-r)! Hence out of 26 letters the possible outcomes are 26p3=26!/23!=15600 14.VALUE OF THE SERIES Take a good look at the following series. 1-1/3+1/5-1/7+1/9-1/11+1/13.................... Find the value of the series and multiply the answer by 4.You will notce that a well-known vale approximates this product.Even more interestng is that as you add more terms the approximation becomes closer. Solution: Ths is an Arithmetic progresson with value .76 when two terms added becomes .77 and multiplidd by 4 it becomes 3.04 and 3.08 repeatition it is 3.14 which pi value adjusted to 2 decimals. 15.PLANTING TREES If you wished to plant some trees so that each was equidistant from every pther tree,what is the largest number you would plant? Solution: From the above informatin,as per equidstant formula of triangle,it is an equilateral triangle. Planting at all the three corners only 3 can be planted. The centroid is the middle point placed exactly equidistant from all the corners. Hence 4 plants can be planted at euqidistant. 16.LENGTH OF A TRAIN A train is travelling at the speed of 96 kmph.It takes 3 seconds to enter a tunnel and 30 seconds more to pass thorugh it completely. What is the length of the train and the tunnel?

Solution: Speed of the train=95*5/18 m/sec Time taken=3ssec Length of the train=96*5/18*3=80m Length of the tunnel=96*5/18*30=800m 17.A GAME OF BILLIARDS Rajv,Sanjiv,Vinay were playing a game of Billiards.Rajiv can give Sanjiv 10 points in 50 and Sanjiv can give 10 points in 50.How many points in 50 must Rajiv gve Sanjiv to make an even game? Solution: Rajiv 50 Sanjiv 50 Sanjiv 40 Rajiv 50 Rajiv gains 18 Sanjiv 40 Vinay 40 Vinay 40*40/50=32 Sanjiv 40 Vinay 32 points than Vinay (50-32=18)

18.WOMEN AT CLUB SOCIALS Women outnumbered men by 16 at a club social.Seventimes the no.of women exceeds nine times the no.of men by 32.What was the number of men and women at club? Solution: Let W and M be the no.of women and men respectively. Given W=M+16.................(1) 7W=9M+32................(2) 7*(1)=>7W=7M+112........(3) (3)-(2) =>M=40 W=56

Top
19.FILLING WINE IN BARRELS A friend of mine in London has a very nice cellar.He has two large barrels in the cellar.The larger barrel is mostly empty.But the smaller barrel is only 5/6 th full f wine while it can hold 536 litres.Supposing he empties the smaller barrel and fills the bigger barrel to find that the wine fills only 4/9 of it.How much wine would the larger barrel hold when full? Solution: 5/6-------------------536 4/9-------------------? 5/6*536=4/9*x =>x=1005 litrs 20.WEIGHT OF A BRICK We have a brick of regular size.It weighs 4 kilograms.How much do you think asmaller brick four times small, but made of the same material weigh? Solution: The weight of the given brick = 4 Kilograms = 4000 grams It is given that the smaller brick's volume is 4 times smaller than the given one.

The volume of smaller brick = 4 * 4 * 4 = 64 times smaller The smaller brick's weight = 4000/64 = 62.5 grams 21.A JUMPING FROG A frog starts climbing a 30 ft wall. Each hour it climbs 3 ft and slips back 2. How many days does it take him to reach the top and get out? Solution: Hours Feets 1 3ft - 2ft = 2 3ft - 2ft = 3 3ft - 2ft = : : : : 27 3ft - 2ft = At the end of 27th hour the frog climbs 27fts climbs the remaining 3fts and comes out.

1ft 1ft 1ft 1 ft and on 28th hour it

22.QUESTION OF PROBABILITY My friend Parveen teaches at a school. One day she conducted a test for 3 of her students and when they handed back the test papers, they had forgotten to write their names. Parveen returned the papers to the students at random.What is the probability that none of the 3 students will get the right paper? Solution: The possible combinations for the given condition are: 1 2 3 condition met 1 2 3 No 1 3 2 Yes 2 1 3 No 2 3 1 Yes 3 1 2 Yes 3 2 1 No The required probability = 2/6 = 1/3 23.MATHEMATICAL ODDITY In the 20th century there are only seven years whose numbers are a mathematical oddity because their numbers signify a prime number. The first one of its kind was the year 1951.Can you name the other sin? Solution: 1973,1979,1987,1993,1997,1999. 24.DOWN THE ESCALATOR Recently,while in London,I decided to walk down the escalator of a tube station.I did some quick calculation in my mind.I found that if I wa down 26 steps, I require 30 seconds to reach the bottom. However ,if I am able to step down 34 stairs I would only require 18 secionds to get to the bottom. If the time is measured from the moment the top step begins to descend to the time I step off the last step at the bottom , can you yel the height of the stairway

in steps? Solution: Given that after walking 26 steps time needed to reach the bottom is 30 seconds ---(1) Similarly after walking 34 steps, it needs 18 seconds more to reach the bottom ---(2) from (1) & (2) it is clear that for (34-26) steps it took (30-18) seconds. i.e; 12 seconds for 8 steps in 1 second --------? (1*8)/12=2/3 steps/sec. i.e; 2 steps in 3 seconds for 30 seconds -----------how many steps? => (30*2)/3=20 steps. Finally Total number of steps = 26 + (steps covered in 30 seconds) =26+20=46 steps. 25.A COMPUTING PROBLEM Compute (100-1)(100-2)(100-3).................(100+1)(100+2)(100+3)=? Solution: =>(100-1)(100-2)(100-3).........(100-100)(100+1)(100+2)(100+3) =>(100-1)(100-2)(100-3).........(0)(100+1)(100+2)(100+3) =0 26.A CIRCLE AND A TRIANGLE What do you call a circle which passes through the vertices of of a triangle? Solution: Circumscribed.The meaning to circumscribe is to describe a figure round another so as to touch it at points without cutting.This is exactly what takes place with the circumscribed circle. To find the center of such a circle,we have to bisect the sides of a triangle and errect perpendiculars which are concurrent at the circumcentre. The radius r of the circumscribed circle of the triangle ABC is given by R=a/2SinA=b/2SinB=c/2Sinc 27.MISSING TERMS 48,60,58,72,68,104....... Here is a sequenc.Can you find the two missing terms? Solution: The odd terms are in the decimal system and differ by 10.And each even term is the preceeding odd term expressed in the octonamy system.78-8=70,remainder 6:9:8=1,remainder 1.Therefore the next two terms are: 78,116

Top
28.PACKETS OF CANDY If 6 men can pack 6 packets of candy in 6 minutes.How many are required to pack 60 packets in 60 minutes? Solution:

Given that for 6 men to pack 6packets of candy it takes 6 miutes i.e., for 1 man to pack 1 packet it takes 1 miute. Hence,for 60 packets to be packed in 60 miutes we need 60 men. 29.A PROBLEM OF WEIGHT In my neighbourhood lives a man who weighs 200 pounds.He has two sons.They both weigh 100 pounds each.On a festival day they decide to go across the river on a boat to vissit some relations. But the boat could carry a maximum load at only 200 pounds.Yes they managed to come across the river by boat.How did they? Solution: Let us assume that c1 ----------------->first son c2 ---------------->second son f ------------------>father First the two sons c1,c2rowed across the river and c1 stayed behind while c2 returned in the boat to his father.The son remained behind while the father crossed the river.Then the other son brought back and the two brothers c1,c2 rowed over together. 30.A PROBLEM OF CANDY BARS Recently I attended a birthday party.All the children in the party were given candy bars.All the children got 3 candy bars each except the child sitting in the end.She got only 2 candy bars.If only child had been given 2 candy bars there would have been 8 candy bars remaining.How many candy bars were there altogether to begin with? Solution: Suppose that there were x children at the party. If we distribute the candies in the above mentioned ways,then the resulting expressions 3(x-1)+2---------------------(1) 2x+8-------------------------(2) 3(x-1)+2=2x+8 3x-3+2=2x+8 3x-1=2x+8 x=9 Therefore the no.of candies for distribution 2x+8=2*9+8=18+8=26 31.FIND OUT THE SUM What is the sum of all numbers between 100 and 1000 which are divisible by 14? Solution: Let us assume that the sum is S s=112+126+........+994 s=14(8+9+10+.....................+71) s=14(8+71)(71-8+1)/2=7(79)(64)=35392 32.WALKING ALL THE WAY One day I decided to walk all the way from Banglore to

Tumkur.

I started exactly at noon and some one I know in Tumkur decided to walk all the way from Tumkur to Banglore and she started exactly at 2 PM on the same day. We met on the Banglore - Tumkur road at 5 past four and we both reached our destination at exactly the same time.At what time did we both arrive? Solution: There fore Total time = 2:00 PM + 3:55 PM + 1:55 PM = 7:50PM 33.THE TRAINS AND THE FALCON Two trains start from two opposite directions towards each other. The stations from which they start are 50 miles apart.Both the trains start at the same time towards the other train. As soon as it reaches the second one, it fies back to the first train and so on and so forth. It continues to do so, flying bacwards and forwards from one train to other until the trains meet. Both the trains travel at a speed of 25 miles per hour,and the bird flies at 100 miles per hour. How many miles will the falcon have flown before the trains meet? Solution: The trains travel at 25 miles per hour. Hence they will meet after travelling for one hour and the falcon also must have been flyingfor one hour. Since it travels at 100 miles per hour the bird must have flown 100 miles 34.VALUE OF 'S' S434S0, what number must be substituted with to make it divisible by 36? Solution: To be divisible by 36, the number has to be divided by 4 and 9 To be divisible by 4 , the number 'S' must be an even number and to be divisible by 9, the sum of all the digits of the number must be either equal to 9 or a multiple of 9 i.e; S + 4 + 3 + 4 + S + 0 = 9n The only digit that meets these two condition is 8 35.HEIGHT OF A ROOM Given the floor area of a room as 24 feet by 48 feet,and the space diagonal of the room as 56 feet,Can you find the height of the room? Solution: We know that, Volume of a cube =l pow(2) + b pow(2) + h Here the values of l & b are given. We also know that (diagonal)pow(2) = (length)pow(2) + => (x)pow(2) = 24 pow(2) + 48 => x = 24squareroot(5); Therefore,volume= h pow(2) + x pow(2) =56 => h=16 Therefore,height of the room=16 ft. pow(2). (breadth)pow(2). pow(2) pow(2)

36.A QUESTION OF DISTANCE It was a beautiful sunny morning. The air was fresh and a mild wind

was blowing against my wind screen I was driving from Banglore to Brindavan Gardens. It took me 1 hour and 30 miutes to complete the journey. After lunch I returned to Banglore. I drove for 90 minutes.How do you explain it? Solution: 90 minutes = 1 hour 30 minutes. Hence,the driving time there and back is absolutely the same because 90 minutes and 1 hour and 30 minutes are one and the samething. 37.ARRANGE THE DIGITS: Arrange the digits 1,2,3,4,5,6,7,8,9 in order from left to right and use only + or _ signs so as to produce a result of 100? Sol: 123-45-67+89

Top
38.DIVISION OF 45: Can you divide the number 45 into four parts such that when 2 is added to the first part, 2 is subtracted from the second part, 2 is multiplied by the third part, and the fourth part is divided by 2. All the four results to be the same number. Sol: Let us take A,B,C,D are the four equal parts and their sum is equal to 45. A+B+C+D = 45 Given that, A+2 = B-2 = C*2 = D/2 ----------------(1) =>A = B-4 ; C = (B-2)/2 ; D = 2(B-2) =>B-4 + [(B-2)/2] + 2(B-2) = 45 =>B=12 :. A=8 , C=5 , D=20 And condition (1) is satisfied. i .e; 8+2 = 12-2 = 5*2 = 20/2 39.SPECIAL NUMBER: What is the special about the number 1729? Sol: This is popularly known as Ramanujan's number. This is the known number that is a sum of two cubes in two different ways. i .e; (10*10*10) + (9*9*9) = 1729 ( 12*12*12) + (1*1*1) = 1729 40.PRICE OF A BOTTLE: A bottle and its cork together cost Rs 1.10, and the bottle costs Rs 1.00 more than its cork. What is the price of the bottle? Sol: Let us assume that, B = Price of the bottle C = Price of the cork It is given that, B + C = Rs 1.10 -------------------(1) and B C = Rs 1.00 -------------------(2)

From the equations (1) and (2) it is clear that B = Rs 1.05 C = Rs 0.05 41.A QUESTION OF DISTANCE: It was a beautiful sunny morning. The air was fresh and a mild wind was blowing against my wind screen. I was driving from Banglore to Brindavan Gardens. It took me one hour and 30 minutes to complete the journey. After lunch I returned to banglore. I drove for 90 minutes. How do you explain it? Sol: 90 minutes = 1 hour 30 minutes. Hence, the driving time there and back is absolutely same because 90 minutes and 1 hour 30 minutes are one and the same. 42.FOR THE CHARITIES: One day when I was walking on the road in New Delhi, a group of boys approached me for donation for their poor boys' fund. I gave them a Rupee more than half the money I had in my purse. I must have walked a few more yards when a group of women approached me for donation, for an orphanage. I gave them 2 Rupees more than half the money I had in my purse. Then after a few yards I was approached by a religious group for a donation to the temple they were building. I gave them 3 Rupees more than half of what I had in my purse. At last I returned to my hotel room, I found that I had only one Rupee remaining in my purse. How much money did I have in my purse when I started? Sol: Suppose that the money in his purse when he started = x --------(1) For poor boys fund he gave x/2 + 1 Rs/- -----------------(2) i .e; 1 Rupee more than half the amount he had. Now he left with [x - (x/2 + 1)] =(x-2)/2 Rs/For Orphanage he gave [(x/2 1)/2] +2 = (x+6)/4 Rs/- -----(3) Now he left with [(x-2)/2] [(x+6)/4] = (x-10)/4 Rs/For temple building he gave [(x-10)/4]/2 + 3 = (x+14)/8 Rs/- ---(4) Now he left with [(x-10)/4] [(x+14)/8] = (x-34)/8 Rs/Finally he had 1 Rupee in his purse. i .e; Actual amount Expended amount = 1 :. from (1),(2),(3) and (4) we have x-{ [ (x+2)/2 ] + [ (x+6)/4 ] + [ (x+14)/8 ] } = 1 =>x-34=8 => x=42 :. The original amount in his purse at the beginning = Rs 42/43.A PAIR OF PALLINDROMES Multiply 21978 by 4.Comment about the result? Solution: 21978*4=87912. If we clearly observe the two numbers 21978 and 87912, the resultant number ie; 87912 is the reverse number of the number 219780. There fore these two numbers are a pair of paindromes.

44.A COMPUTING PROBLEM Compute: [5-2/(4-5)]pow(2). Solution: [5-2/(4-5)]pow(2) =[5-2/(-1)]pow(2) =[5+2]pow(2)=49. 45.CONTINUE THE SERIES 1,3,6,10.Name the next three numbers in the series. Solution: The series is +2,+3,+4,----------------There fore next three numbers are: 10+5,10+5+6,10+5+6+7 = 15,21,28.

46.NAME FIVE TERMS OF ANOTHER SERIES These are the numbers that are the first five terms of a series that add upto 150.Can you name five terms of another series without fractons that add upto 153? [ex: 10,20,30,40,50. sum=150.] Solution: Each term in this series is a factorial, in other words,the product of a the numbers from 1 to that particular term considered. The first five terms of the series are,there fore 1,2,6,24,120. Their sum is 153 and are factorials of 1,2,3,4,5 respectively. 47.FIND OUT THE TIME What does 1408 hours mean? Solution: 1408 hours is actually 8 minutes past 2 PM. This is the system of twenty-four-hour cock.Writing the hours and minutes this way is a sensible means of avoiding confusion between AM and PM. 48.FIND OUT TTHE PATTERN What do you think the pattern is?6,24,60,120,210,336, Solution: The series is 1.2.3, 2.3.4, 3.4.5, 4.5.6, 5.6.7, 6.7.8,---------The next numbers would be 7.8.9, 8.9.10,------(or) 504, 720,-----------------------

Top
49.THE TRAIN AND THE CYCLIST A railway track runs parallel to a road until a bend brings the road to a level crossing. A cyclist rides along to work along the road every day at a constant speed of 12 miles per hour. He normally meets a train that travels in the same direction at the crossing One day he was late by 25 minutes and met the train 6 miles ahead of the level crossing. Can you figure out the speed of the train?

Solution: Suppose that the train and the cyclist meet everyday at the crossing at 8:00A.M. i. e; starts at 7:00A.M Since the cyclist is late by 25 minutes, he starts at 7:25A.M As his speed is 12 miles per hour, he reaches the crossing at 7:25A.M + 1 Hour = 8:25A.M By 8:30A.M the train is 6 miles ahead of the cyclist The difference between their timings = 8:30A.M 8:25A.M = 5 Minutes The difference between their distances = 6 Miles Therefore,the train travels 6 miles in 5 minutes In 1 minute it travels ---------------------? = [(1 * 6) /5] * 60 = 72 Miles/hour 50.HEIGHT OF THE PALM TREE A palm tree was 90 cm high, when it was planted. It grows by an equal number of cm each year, and at the end of the seventh year it was one ninth taller than at the end of the sixth year. Can you tell how tall was the tree at the end of the twelfth year? Solution: Suppose that the tree grows x cm each year Height of the tree at the end of the sixth year = (90 + 6x) cm Growth in seventh year is, X = 1/9(90 + 6x) cm x = 10 + 2x/3 x = 30 Therefore the height of the tree at the end of the twelfth year=(90+12*30)=450cm 51.PROBLEM OF AGE Recently I attended a cocktail party. There was a beautiful young lady, who seemed very vitty and intelligent. She was posed a question, how old are you? . She answered , my age 3 years hence munltiply by 3 and from that subtracted 3 times my age 3 years ago will give you my exact age? How od is the lady? Solution: Let the age be x Age after 3 years wi be (x + 3) Age before 3 years = (x 3) Hence 3(x + 3) 3(x 3) = x x = 3x + 9 3x + 9 x = 18 Therefore the age of the lady = 18 years

52.CONSECUTIVE NATURASL NUMBERS There are two consecutive natural numbers whose product is equal to the product of three consecutive natural numbers,for example x(x+1) = y(y+1)(y+2).What are the two numbers? Solution: 14 * 15 = 5 * 6 * 7

53.SOME GLUTTON A man sitting beside me at a hotel ate idlis ordering plate by plate. He said to me after last one I ate was my hundredth idli in last I ate 6 more than the previous day. Can you ate yesterday? Soluton:

one after the other by drinking some water the five days. Each day tell me how many he

First day the number of idlis he ate be x Second day the count is (x+6) Third day ------------------------- (x+12) Fourth day ------------------------(x+18) Fifth day ---------------------------(x+24) Total is 5x + 6(1+2+3+4) =100 5x + 60 =100 x = 8 Day Idlis 1 8 2 14 3 20 4 26 5 32 So, on fourth day the number of idlis the man ate were 26.

Reasoning
Reasoning CLASSIFICATION TYPE Read the following information carefully and answer the questions that follow: 1) There are six cities A,B,C,D,E and F A is not a hill station. B and E are not historical places. D is not an industrial city. A and D are not historical craj_konkepudiities. A and B are not alike. 1.Which two cities are industrial centres? a)A,B b)E,F* c)C,D d)B,F 2.Which two cities are historical places? a)A,C b)B,F c)C,F* d)B,E 3.Which two cities are hill stations? a)A,B b)C,A c)B,D* d)A,F e)A,D e)A,D e)none

4.Which city is a hill station and an industrial centre but not

ahistorical place? a)E* b)F

c)A

d)B

e)C

5.Which two cities are neither historical places nor industrial centres? a)A,B b)D,E c)F,C d)B,D* e)none Solution: A x y x B x x y C y y y D x x y E x y y F y y y

Historical Industrial Hillstation 2)

Five friends Indu,Pinki,Sai,Srujan,Pavan travelled to five different cities of Chennai,Calcutta,Delhi,Bangalore and Hyderabad by five differnet modes of transport of Bus,Train,Aeroplane,Car and Boat from Mumbai. The person who travelled to Delhi did not travel by Boat. Sai went to Banalore by Car and Pinki went to Calcutta by Aeroplane. Srujan travelled by Boat whereas Pavan travelled by Train. Mumbai is not connected by bBus to Delhi and Chennai. 1.Which of the following combinations of person and mode is not correct? a)Indu-Bus b)Pinki-Aeroplane c)Sai-Car d)Srujan-Boat e)PavanAeroplane* 2.Which of the following combinations is true for Srujan? a)Delhi-Bus b)Chennai-Bus c)Chennai-Boat* d)Data inadequate 3.Which of the following combinations of place and mode is not correct? a)Delhi-Bus* b)Calcutta-Aeroplane c)Bangalore-Car d)Chennai-Boat 4.Person travelling to Delhi went by which of the following modes? a)Bus b)Train* c)Aeroplane d)Car e)Boat 5.Who among the following traj_konkepudiravelled to Delhi? a)Sai b)Srujan c)Pavan* d)Data inadequate e)none

Solution: Sai travels by Car. Pinki travels by Aeropraj_konkepudilane. Srujan travels by Boat. Pavan travels by Train. Indu travels by Bus. Sai goes to Bangalore. Pinki goes to Calcutta. Bus facility is not there for Delhi or Chennai. Indu goes to Hyderabad by Bus. From given information it is clear that Srujan goes by Boat but not to Delhi. Hence Srujan goes to Chennai.

Pavan

goes to Delhi. PLACE MODE Bus Aeroplane Car Boat Train

Indu Pinki Sai Srujan Pavan

Hyderabad Calcutta Bangalore Chennai Delhi

3) Four youngmen Thirbhuvan,Thrishanth,trinath,Trived are friendly with four girls Indira,Madhuri,Swetha and Dimple.Indira and Swetha are friends.Trinath's girlfriend does not like Indira and Swetha. Madhuri does not care for Trinath.Trishanth's girlfriend is friendly with Indira.Indira does not like Thribhu. 1.Who is Thribhu's girlfriend? a)Indira b)Madhuri* c)Swetha 2.With whom is Indira friendly? a)Thribhuvan b)Thrishanth c)Trinath 3.who is Dimple's boyfriend? a)Trived b)Trinath* c)Thrishanth d)Dimple d)Trived* d)Thribhuvan d)Trinath

4.Who does not like Indira and Swetha? a)Dimple* b)Thribhuvan c)Trived

Solution: Given Indira and Swetha are friends. Thrishanth's girlfriend is friendly with Indira. Hence,Thrishanth's girlfriend is Swetha. Given,Trinath's girlfriend does not like Indira and Swetha. =>She might be Madhuri or Dimple. But Madhuri does not care for Trinath. =>Trinath's girlfriend is Dimple. Given,Indira does not like Thrinbhuvan. =>Thribhuvan's girlfriend is Madhuri. Clearly,Trived's girlfriend is Indira. BOY Thribhuvan Thrishanth Trinath Trived COMPARISION TYPE QUESTIONS GIRL Madhuri Swetha Dimple Indira

Top

1) Clues will be given regarding comparisions among a ssset of persons or things with respest to one or more qualities.After analysing a proper ascending ,descending sequence is formed and then are supposed to answer. There are five friends-Sachin,Sourav,Rahul,Zaheer and Yuvi.Sachin is shorter than Sourav but taller than Yuvi.Rahul is the tallest. Zaheer is little shorter than Sourav and little taller than Sachin. 1.Who is the shortest? a)Yuvi* b)Sachin c)Zaheer d)Sourav e)none

2.If they stand inorder of their heights,who will be in the middle? a)Sourav b)Yuvi c)Sachin d)Zaheer* e)none 3.If they stand inorder of their increasing heights,who will be the second? a)Zaheer b)Sachin* c)Yuvi d)Sourav e)none 4.Who is the second tallest? a)Sachin b)Sourav* c)Zaheer d)Yuvi e)none e)none

5.Who is taller than Zaheer but shorter than Rahul? a)Sourav* b)Yuvi c)Sachin d)datainadequate Solution: Sachin < Sourav Rahul is tallest Zaheer < Sourav Yuvi < Sachin < Sourav < Rahul Yuvi < Sachin < Zaheer Sourav > Yuvi

Zaheer > Sachin and Sachin < Zaheer < Sourav < Sourav < Rahul

2) Among five boys Vineeth is taller than Manick,but not as tall as Ravi,Jacob is taller than Dilip but shorter than Manick.Who is the tallest in their group? a)Ravi* b)Manick c)Vineeth d)can't say e)none

Solution: Manick < Vineeth ; Vineeth < Ravi ; Dilip < Jacob ; Jacob < Mainck =>Dilip < Jacob < Manick < Vineeth < Ravi 3) Sudhanshu is as much older than Kokila as he is younger than Praveen. Nitin is as old as Kokila.Which of the following is wrong? a)Kokila is younger than Praveen. b)Nitin is younger than Praveen. c)Sudhanshu is older than Nitin. d)Praveen is not the oldest.* e)Kokila is younger than Sudhanshu. Solution: =>Kokila < Sudhanshu; Praveen > Sudhanshu; Nitin = Kokila

=>Nitin = Kokila < Sudhanshu < Praveen =>Praveen is the oldest.

Top
SELECTION BASED ON GIVEN CONDITIONS 1) A few essential criteria for selection of group of items are given: From amongst five doctors A,B,C,D and E;four engineers G,H,K and L; six teachers M,N,O,P,Q and R some teams are to be selected.A,B,G,H,O,P and Q are females and the rest are males. Where ever there is a male doctor ,no female teacher. Where ever there is a male engineer, no female doctor. There shall not be more than two male teachers in any team. 1.If the team consists of 2 doctors,3 female teachers and 2 engineers, the members of the team are: a)A B O P Q G H* b)C D O P Q G H c)C D K L O P Q d)D E G H O P Q 2.If the team following are a)A B G M N O d)A B K N R P consists of 2 doctors,1 engineer and 4 teachers all the possible except P b)A B H M O P Q c)A B H M R P Q Q*

3.If the team consists of2 doctors,2 female teachers and two engineers all the following teams are possible except: a)A B G H O Q b)A B G H P Q c)A B K L P Q d)O P G H A B 4.If the team consists of 3 doctors,2 male engineers and 2 teachers, the members of the team could be: a)A B C K L M R b)B C D K L N R c)C D E K L M N d)C D E K L P R 5.if the team consists of two doctors,two engineers and two teachers, all the following teams are possible except: a)A B G H O P b)A B G H M N c)C E K L N R d)C D K L O P Explanation:Doctors A B C D E Engineers G H K L Teachers M N O P Q R Given Females A B G H O P Q Males C D E K L M N R Male doctor and female teacher male engineer and female doctor More than two teachers/team combination are not allowed. 1Q) Explanation: Doctors are A B C D E Female teachers are O P Q Engineers are G H K L Male doctor and no female teacher => A,B are Doctors. So the Team consists of A B O P Q G H.

2Q) Explanation: Teachers are M N O P Q R Four are needed Three are male teachers. Female teachers are also to be selected.Hence no male doctors C D E are selected. So Doctors => A B Both doctors are Females =>no male Engineer to be selected. Ans:Team =>A B K N R P Q. 3Q) Explanation: The doctors are A B C D E, Female Teachers are O P Q, Engineers are G H K L, Since 2 Female Teachers are to be selected.So male doctors i.e;C D E cannot be selected. So, 2 Doctors selected will be A,B. Both Doctors are Females. So, male Engineer K L cannot be selected. G H are chosen. =>A B K L P Q are selected. 4Q)Explanation: Doctors A,B,C,D,E Male Engineers K,L Teachers M,N,O,P,Q,R Male Engineers =>no female Doctors=>no A,B 3 Doctors to be selected are C,D,E who are all males.

Top
FAMILY BASED PROBLEMS 1) There is a group of six persons A,B,C,D,E and F from a family. They are psychologist,manager,lawyer,jeweler,doctor and engineer. The doctor is the grandfather of F who is a psychologist. The manager D is married to A. C,the jeweler is married to the lawyer. B is the mother of F and E. There are two married couples in the family. 1.What is the profession of E? a)Doctor b)Jeweler c)Manager 2.How is A related to E? a)Brother b)Uncle c)Father d)Psychologist e)None*

d)Grandfather*

3.How many male members are there in the family? a)One b)Three c)Four d)Data insufficient* 4.What is the profession of A? a)Doctor* b)Lawyer c)Jeweler d)Manager

5.Which of the following is one of the pairs of couples in the family? a)AB b)AC c)AD* d)cant say Solution: F is a Psychologist. B is the mother of F and E. =>E is brother or sister of F. There are two married couples in the family. Since D is married to A,C the jeweler is married to lawyer B. Manager D is married to A means A is doctor,grandfather of E and F. So no one else is engineer till this point.=>E is engineer. AD--->CB------>EF 2) Prashanth Arora has three children-Sangeeta,Vimal and Ashish.Ashish married Monika,the eldest daughter of Mr.andMrs.Roy.The Roys married their youngest daughter to the eldest son of Mr.and Mrs.Sharma,and they had two children named Amit and Shashi.The Roys have two more children, Roshan and Vandana,both elder to Veena.Sameer and Ajay are sons of Ashish and Monika.Rashmi is the daughter of Amit. Prashanth Arora-------> 1.Sangeeta 2.Vimal 3.Ashish(Monika)--------------------> 1.Sameer 2.Ajay Mr & Mrs.Sharma----------------> 1.Amit(Veena)---------------->1.Rashmi 2.Shashi Mr & Mrs.Roy---------------------> 1.Monika 2.Roshan 3.Vandana 4.Veena 1.What is the surname of Rashmi? a)Sharma* b)Roy c)Arora

d)cant say

e)none e)none e)none

2.How is Sameer related to father of Monika? a)Grandson* b)Son c)Cousin 3.What is the surname of Sameer? a)Roy b)Sharma c)Arora* 4.How is Mrs.Roy related to Ashish? a)aunt b)Mother-in-law* 3)

d)Son-in-law d)cant say

c)mother

d)sister-in-law

In a family of six persons,there are three generations.Each person has seperate profession and also they like different colours.There are two couples in the family.Rohan is a CA and his wife neither is a doctor nor likes green colour. Engineer likes red colour and his wife is a teacher.Mohini is mother-in-law of Sunita and she likes orange colour. Vinod is grandfather of Tanmay,Tanmay is principal likes black colour. Nanu is granddaughter of Mohini and she likes blue colour.Nanus

mother likes white colour. 1.Who is an Engineer? a)Nanu b)Mohini c)Sunita d)cant say d)cant say e)none* e)none

2.What is the profession of Sunita? a)engineer b)doctor c)teacher* 3.Which of the a)Mohini-Vinod b)Vinod-Mohini c)Rohan-Sunita d)cant say following is the correct pair? and Rohan-Sunita* and Rohan-Nanu and Tanmay-Nanu e)none

4.How many ladies are there in the family? a)2 b)3* c)4 d)cant say e)none 5.Which colour is liked by CA? a)green* b)white c)white/green d)cant say e)none

Solution: (Engineer) Vinod- Mohini(Teacher)------------->(CA)Rohan-Sunita--------->Nanu&Tanmay(principal) Vinod------------Red Mohini-----------Orange Rohan-------------Green Sunita--------------White Nanu---------------Black Tanmay-----------Black Mohini is mother-in-law of Sunita and grandmother of Nanu. Vinod is grandfather of Tanmay. So,Nanu and Tanmay represent third generation. Mohini and vinod form a couple and represent first generation. Rohan and Sunita form the other couple and represdent second generation. Rohan is a CA. Since,engineer is married,Vinod is engineer. Given Vinod loves red colour. Mohini is ateacher and likes Orange colour. Nanu likes blue colour. Tanmay is principal and likes black colour. Sunita Nanus mother likes white colour.=>Rohan likes green colour.

First Job. Dream Job. Freshersworld.com

Aptitude Questions
1.If 2x-y=4 then 6x-3y=? (a)15 (b)12 (c)18 (d)10 Ans. (b) 2.If x=y=2z and xyz=256 then what is the value of x? (a)12 (b)8 (c)16 (d)6 Ans. (b) 3. (1/10)18 - (1/10)20 = ? (a) 99/1020 (b) 99/10 (c) 0.9 (d) none of these Ans. (a) 4.Pipe A can fill in 20 minutes and Pipe B in 30 mins and Pipe C can empty the same in 40 mins.If all of them work together, find the time taken to fill the tank (a) 17 1/7 mins (b) 20 mins (c) 8 mins (d) none of these Ans. (a) 5. Thirty men take 20 days to complete a job working 9 hours a day.How many hour a day should 40 men work to complete the job? (a) 8 hrs (b) 7 1/2 hrs (c) 7 hrs (d) 9 hrs Ans. (b) 6. Find the smallest number in a GP whose sum is 38 and product 1728
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com


(a) 12 (b) 20 (c) 8 (d) none of these Ans. (c) 7. A boat travels 20 kms upstream in 6 hrs and 18 kms downstream in 4 hrs.Find the speed of the boat in still water and the speed of the water current? (a) 1/2 kmph (b) 7/12 kmph (c) 5 kmph (d) none of these Ans. (b) 8. A goat is tied to one corner of a square plot of side 12m by a rope 7m long.Find the area it can graze? (a) 38.5 sq.m (b) 155 sq.m (c) 144 sq.m (d) 19.25 sq.m Ans. (a) 9. Mr. Shah decided to walk down the escalator of a tube station. He found that if he walks down 26 steps, he requires 30 seconds to reach the bottom. However, if he steps down 34 stairs he would only require 18 seconds to get to the bottom. If the time is measured from the moment the top step begins to descend to the time he steps off the last step at the bottom, find out the height of the stair way in steps? Ans.46 steps. 10. The average age of 10 members of a committee is the same as it was 4 years ago, because an old member has been replaced by a young member. Find how much younger is the new member ? Ans.40 years. 11. Three containers A, B and C have volumes a, b, and c respectively; and container A is full of water while the other two are empty. If from container A water is poured into container B which becomes 1/3 full, and into container C which becomes 1/2 full, how much water is left in container A? 12. ABCE is an isosceles trapezoid and ACDE is a rectangle. AB = 10 and EC = 20. What is the length of AE? Ans. AE = 10.
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com


13. In the given figure, PA and PB are tangents to the circle at A and B respectively and the chord BC is parallel to tangent PA. If AC = 6 cm, and length of the tangent AP is 9 cm, then what is the length of the chord BC? Ans. BC = 4 cm. 15 Three cards are drawn at random from an ordinary pack of cards. Find the probability that they will consist of a king, a queen and an ace. Ans. 64/2210. 16. A number of cats got together and decided to kill between them 999919 mice. Every cat killed an equal number of mice. Each cat killed more mice than there were cats. How many cats do you think there were ? Ans. 991. 17. If Log2 x - 5 Log x + 6 = 0, then what would the value / values of x be? Ans. x = e2 or e3. 18. The square of a two digit number is divided by half the number. After 36 is added to the quotient, this sum is then divided by 2. The digits of the resulting number are the same as those in the original number, but they are in reverse order. The ten's place of the original number is equal to twice the difference between its digits. What is the number? Ans. 46 19.Can you tender a one rupee note in such a manner that there shall be 50 coins but none of them would be 2 paise coins.? total

Ans. 45 one paisa coins, 2 five paise coins, 2 ten paise coins, and 1 twenty-five paise coins. 20.A monkey starts climbing up a tree 20ft. tall. Each hour, it hops 3ft. and slips back 2ft. How much time would it take the monkey to reach the top? Ans.18 hours. 21. What is the missing number in this series? Ans. 9 22. A certain type of mixture is prepared by mixing brand A at Rs.9 a kg. with brand B at Rs.4 a kg. If the mixture is worth Rs.7 a kg., how many kgs. of brand A are needed to make 40kgs. of the mixture? Ans. Brand A needed is 24kgs. 8 2 14 6 11 ? 14 6 18 12

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com


23. A wizard named Nepo says "I am only three times my son's age. My father is 40 years more than twice my age. Together the three of us are a mere 1240 years old." How old is Nepo? Ans. 360 years old. 24. One dog tells the other that there are two dogs in front of me. The other one also shouts that he too had two behind him. How many are they? Ans. Three. 25. A man ate 100 bananas in five days, each day eating 6 more than the previous day. How many bananas did he eat on the first day? Ans. Eight. 26. If it takes five minutes to boil one egg, how long will it take to boil four eggs? Ans. Five minutes. 27. The minute hand of a clock overtakes the hour hand at intervals of 64 minutes of correct time. How much a day does the clock gain or lose? Ans. 32 8/11 minutes. 28. Solve for x and y: 1/x - 1/y = 1/3, 1/x2 + 1/y2 = 5/9.

Ans. x = 3/2 or -3 and y = 3 or -3/2. 29. Daal is now being sold at Rs. 20 a kg. During last month its rate was Rs. 16 per kg. By how much percent should a family reduce its consumption so as to keep the expenditure fixed? Ans. 20 %. 30. Find the least value of 3x + 4y if x2y3 = 6. Ans. 10. 31. Can you find out what day of the week was January 12, 1979? Ans. Friday. 32. A garrison of 3300 men has provisions for 32 days, when given at a rate of 850 grams per head. At the end of 7 days a reinforcement arrives and it was found that now the provisions will last 8 days less, when given at the rate of 825 grams per head. How, many more men can it feed? Ans. 1700 men.

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com


33. From 5 different green balls, four different blue balls and three different red balls, how many combinations of balls can be chosen taking at least one green and one blue ball? Ans. 3720. 34. Three pipes, A, B, & C are attached to a tank. A & B can fill it in 20 & 30 minutes respectively while C can empty it in 15 minutes. If A, B & C are kept open successively for 1 minute each, how soon will the tank be filled? Ans. 167 minutes. 35. A person walking 5/6 of his usual rate is 40 minutes late. What is his usual time? Ans. 3 hours 20 minutes.

36.For a motorist there are three ways going from City A to City C. By way of bridge the distance is 20 miles and toll is $0.75. A tunnel between the two cities is a distance of 10 miles and toll is $1.00 for the vehicle and driver and $0.10 for each passenger. A two-lane highway without toll goes east for 30 miles to city B and then 20 miles in a northwest direction to City C. 1. Which is the shortest route from B to C (a) Directly on toll free highway to City C (b) The bridge (c) The Tunnel (d) The bridge or the tunnel (e) The bridge only if traffic is heavy on the toll free highway Ans. (a) 2. The most economical way of going from City A to City B, in terms of toll and distance is to use the (a) tunnel (b) bridge (c) bridge or tunnel (d) toll free highway (e) bridge and highway Ans. (a) 3. Jim usually drives alone from City C to City A every working day. His firm deducts a percentage of employee pay for lateness. Which factor would most influence his choice of the bridge or the tunnel ? (a) Whether his wife goes with him (b) scenic beauty on the route
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com


(c) Traffic conditions on the road, bridge and tunnel (d) saving $0.25 in tolls (e) price of gasoline consumed in covering additional 10 miles on the bridge Ans. (a) 4. In choosing between the use of the bridge and the tunnel the chief factor(s) would be: I. Traffic and road conditions II. Number of passengers in the car III. Location of one's homes in the center or outskirts of one of the cities IV. Desire to save $0.25 (a) I only (b) II only (c) II and III only (d) III and IV only (e) I and II only Ans. (a) 37.The letters A, B, C, D, E, F and G, not necessarily in that order, stand for seven consecutive integers from 1 to 10 D is 3 less than A B is the middle term F is as much less than B as C is greater than D G is greater than F 1. The fifth integer is (a) A (b) C (c) D (d) E (e) F Ans. (a) 2. A is as much greater than F as which integer is less than G (a) A (b) B (c) C (d) D (e) E Ans. (a) 3. If A = 7, the sum of E and G is (a) 8 (b) 10
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com


(c) 12 (d) 14 (e) 16 Ans. (a) 4. A - F = ? (a) 1 (b) 2 (c) 3 (d) 4 (e) Cannot be determined Ans. (a) 5. An integer T is as much greater than C as C is greater than E. T can be written as A + E. What is D? (a) 2 (b) 3 (c) 4 (d) 5 (e) Cannot be determined Ans. (a) 6. The greatest possible value of C is how much greater than the smallest possible value of D? (a) 2 (b) 3 (c) 4 (d) 5 (e) 6 Ans. (a)

38. 1. All G's are H's 2. All G's are J's or K's 3. All J's and K's are G's 4. All L's are K's 5. All N's are M's 6. No M's are G's 1. If no P's are K's, which of the following must be true? (a) All P's are J's (b) No P is a G (c) No P is an H
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com


(d) If any P is an H it is a G (e) If any P is a G it is a J Ans. (a) 2. Which of the following can be logically deduced from the conditions stated? (a) No M's are H's (b) No M's that are not N's are H's (c) No H's are M's (d) Some M's are H's (e) All M's are H's Ans. (a) 3. Which of the following is inconsistent with one or more of the conditions? (a) All H's are G's (b) All H's that are not G's are M's (c) Some H's are both M's and G's (d) No M's are H's (e) All M's are H's Ans. (a) 4. The statement "No L's are J's" is I. Logically deducible from the conditions stated II. Consistent with but not deducible from the conditions stated III. Deducible from the stated conditions together with the additional statement "No J's are K's" (a) I only (b) II only (c) III only (d) II and III only (e) Neither I, II nor III Ans. (a)

39.In country X, democratic, conservative and justice parties have fought three civil wars in twenty years. TO restore stability an agreement is reached to rotate the top offices President, Prime Minister and Army Chief among the parties so that each party controls one and only one office at all times. The three top office holders must each have two deputies, one from each of the other parties. Each deputy must choose a staff composed of equally members of his or her chiefs party and member of the third party. 1. When Justice party holds one of the top offices, which of the following cannot
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com


be true (a) Some of the staff members within that office are justice party members (b) Some of the staff members within that office are democratic party members (c) Two of the deputies within the other offices are justice party members (d) Two of the deputies within the other offices are conservative party members (e) Some of the staff members within the other offices are justice party members. Ans. (a) 2. When the democratic party holds presidency, the staff of the prime minister's deputies are composed I. One-fourth of democratic party members II. One-half of justice party members and one-fourth of conservative party members III. One-half of conservative party members and one-fourth of justice party members. (a) I only (b) I and II only (c) II or III but not both (d) I and II or I and III (e) None of these Ans. (a) 3. Which of the following is allowable under the rules as stated: (a) More than half of the staff within a given office belonging to a single party (b) Half of the staff within a given office belonging to a single party (c) Any person having a member of the same party as his or her immediate superior (d) Half the total number of staff members in all three offices belonging to a single party (e) Half the staff members in a given office belonging to parties different from the party of the top office holder in that office. Ans. (a) 4. The office of the Army Chief passes from Conservative to Justice party. Which of the following must be fired. (a) The democratic deputy and all staff members belonging to Justice party (b) Justice party deputy and all his or hers staff members (c) Justice party deputy and half of his Conservative staff members in the chief of staff office (d) The Conservative deputy and all of his or her staff members belonging to Conservative party (e) No deputies and all staff members belonging to conservative parties.
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com

Ans. (a)

40.In recommendations to the board of trustees a tuition increase of $500 per year, the president of the university said "There were no student demonstrations over the previous increases of $300 last year and $200 the year before". If the president's statement is accurate then which of the following can be validly inferred from the information given: I. Most students in previous years felt that the increases were justified because of increased operating costs. II. Student apathy was responsible for the failure of students to protest the previous tuition increases. III. Students are not likely to demonstrate over new tuition increases. (a) I only (b) II only (c) I or II but not both (d) I, II and III (e) None Ans. (a)

41. The office staff of XYZ corporation presently consists of three bookeepers--A, B, C and 5 secretaries D, E, F, G, H. The management is planning to open a new office in another city using 2 bookeepers and 3 secretaries of the present staff . To do so they plan to seperate certain individuals who don't function well together. The following guidelines were established to set up the new office I. Bookeepers A and C are constantly finding fault with one another and should not be sent together to the new office as a team II. C and E function well alone but not as a team , they should be seperated III. D and G have not been on speaking terms and shouldn't go together IV Since D and F have been competing for promotion they shouldn't be a team 1.If A is to be moved as one of the bookeepers,which of the following cannot be a possible working unit. A.ABDEH B.ABDGH C.ABEFH D.ABEGH Ans.B 2.If C and F are moved to the new office,how many combinations are possible A.1 B.2
Freshersworld.com Resource Center

10

First Job. Dream Job. Freshersworld.com


C.3 D.4 Ans.A 3.If C is sent to the new office,which member of the staff cannot go with C A.B B.D C.F D.G Ans.B 4.Under the guidelines developed,which of the following must go to the new office A.B B.D C.E D.G Ans.A 5.If D goes to the new office,which of the following is/are true I.C cannot go II.A cannot go III.H must also go A.I only B.II only C.I and II only D.I and III only Ans.D 42.After months of talent searching for an administrative assistant to the president of the college the field of applicants has been narrowed down to 5--A, B, C, D, E .It was announced that the finalist would be chosen after a series of all-day group personal interviews were held.The examining committee agreed upon the following procedure I.The interviews will be held once a week II.3 candidates will appear at any all-day interview session III.Each candidate will appear at least once IV.If it becomes necessary to call applicants for additonal interviews, no more 1 such applicant should be asked to appear the next week V.Because of a detail in the written applications,it was agreed that whenever candidate B appears, A should also be present.
Freshersworld.com Resource Center

11

First Job. Dream Job. Freshersworld.com


VI.Because of travel difficulties it was agreed that C will appear for only 1 interview. 1.At the first interview the following candidates appear A,B,D.Which of the follwing combinations can be called for the interview to be held next week. A.BCD B.CDE C.ABE D.ABC Ans.B 2.Which of the following is a possible sequence of combinations for interviews in 2 successive weeks A.ABC;BDE B.ABD;ABE C.ADE;ABC D.BDE;ACD Ans.C 3.If A ,B and D appear for the interview and D is called for additional interview the following week,which 2 candidates may be asked to appear with D? I. A II B III.C IV.E A.I and II B.I and III only C.II and III only D.III and IV only Ans.D 4.Which of the following correctly state(s) the procedure followed by the search committee I.After the second interview all applicants have appeared at least once II.The committee sees each applicant a second time III.If a third session,it is possible for all applicants to appear at least twice A.I only B.II only C.III only D.Both I and II
Freshersworld.com Resource Center

12

First Job. Dream Job. Freshersworld.com


Ans.A 43. A certain city is served by subway lines A,B and C and numbers 1 2 and 3 When it snows , morning service on B is delayed When it rains or snows , service on A, 2 and 3 are delayed both in the morning and afternoon When temp. falls below 30 degrees farenheit afternoon service is cancelled in either the A line or the 3 line, but not both. When the temperature rises over 90 degrees farenheit, the afternoon service is cancelled in either the line C or the 3 line but not both. When the service on the A line is delayed or cancelled, service on the C line which connects the A line, is delayed. When service on the 3 line is cancelled, service on the B line which connects the 3 line is delayed. Q1. On Jan 10th, with the temperature at 15 degree farenheit, it snows all day. On how many lines will service be affected, including both morning and afternoon. (A) 2 (B) 3 (C) 4 (D) 5 Ans. D

Q2. On Aug 15th with the temperature at 97 degrees farenheit it begins to rain at 1 PM. What is the minimum number of lines on which service will be affected? (A) 2 (B) 3 (C) 4 (D) 5 Ans. C

Q3. On which of the following occasions would service be on the greatest number of lines disrupted. (A) A snowy afternoon with the temperature at 45 degree farenheit (B) A snowy morning with the temperature at 45 degree farenheit (C) A rainy afternoon with the temperature at 45 degree farenheit (D) A rainy afternoon with the temperature at 95 degree farenheit Ans. B
Freshersworld.com Resource Center

13

First Job. Dream Job. Freshersworld.com

44. In a certain society, there are two marriage groups, red and brown. No marriage is permitted within a group. On marriage, males become part of their wives groups; women remain in their own group. Children belong to the same group as their parents. Widowers and divorced males revert to the group of their birth. Marriage to more than one person at the same time and marriage to a direct descendant are forbidden Q1. A brown female could have had I. A grandfather born Red II. A grandmother born Red III Two grandfathers born Brown (A) I only (B) III only (C) I, II and III (D) I and II only Ans. D

Q2. A male born into the brown group may have (A) An uncle in either group (B) A brown daughter (C) A brown son (D) A son-in-law born into red group Ans. A

Q3. Which of the following is not permitted under the rules as stated. (A) A brown male marrying his father's sister (B) A red female marrying her mother's brother (C) A widower marrying his wife's sister (D) A widow marrying her divorced daughter's ex-husband Ans. B

Q4. If widowers and divorced males retained their group they had upon marrying which of the following would be permissible ( Assume that no previous marriage occurred) (A) A woman marrying her dead sister's husband (B) A woman marrying her divorced daughter's ex-husband (C) A widower marrying his brother's daughter (D) A woman marrying her mother's brother who is a widower.

Freshersworld.com Resource Center

14

First Job. Dream Job. Freshersworld.com


Ans. D

Q5. I. All G's are H's II. All G's are J's or K's III All J's and K's are G's IV All L's are K's V All N's are M's VI No M's are G's 45. There are six steps that lead from the first to the second floor. No two people can be on the same step Mr. A is two steps below Mr. C Mr. B is a step next to Mr. D Only one step is vacant ( No one standing on that step ) Denote the first step by step 1 and second step by step 2 etc. 1. If Mr. A is on the first step, Which of the following is true? (a) Mr. B is on the second step (b) Mr. C is on the fourth step. (c) A person Mr. E, could be on the third step (d) Mr. D is on higher step than Mr. C. Ans: (d) 2. If Mr. E was on the third step & Mr. B was on a higher step than Mr. E which step must be vacant (a) step 1 (b) step 2 (c) step 4 (d) step 5 (e) step 6 Ans: (a) 3. If Mr. B was on step 1, which step could A be on? (a) 2&e only (b) 3&5 only (c) 3&4 only (d) 4&5 only (e) 2&4 only Ans: (c) 4. If there were two steps between the step that A was standing and the step that B was standing on, and A was on a higher step than D , A must be on step (a) 2 (b) 3 (c) 4

Freshersworld.com Resource Center

15

First Job. Dream Job. Freshersworld.com


(d) 5 (e) 6 Ans: (c)

5. Which of the following is false i. B&D can be both on odd-numbered steps in one configuration ii. In a particular configuration A and C must either both an odd numbered steps or both an even-numbered steps iii. A person E can be on a step next to the vacant step. (a) i only (b) ii only (c) iii only (d) both i and iii Ans: (c)

46. Six swimmers A, B, C, D, E, F compete in a race. The outcome is as follows. i. B does not win. ii. Only two swimmers separate E & D iii. A is behind D & E iv. B is ahead of E , with one swimmer intervening v. F is a head of D 1. Who stood fifth in the race ? (a) A (b) B (c) C (d) D (e) E Ans: (e) 2. How many swimmers seperate A and F ? (a) 1 (b) 2 (c) 3 (d) 4 (e) cannot be determined Ans: (d) 3. The swimmer between C & E is (a) none (b) F (c) D
Freshersworld.com Resource Center

16

First Job. Dream Job. Freshersworld.com


(d) B (e) A Ans: (a) 4. If the end of the race, swimmer D is disqualified by the Judges then swimmer B finishes in which place (a) 1 (b) 2 (c) 3 (d) 4 (e) 5 Ans: (b) 47. Five houses lettered A,B,C,D, & E are built in a row next to each other. The houses are lined up in the order A,B,C,D, & E. Each of the five houses has a colored chimney. The roof and chimney of each housemust be painted as follows. i. The roof must be painted either green,red ,or yellow. ii. The chimney must be painted either white, black, or red. iii. No house may have the same color chimney as the color of roof. iv. No house may use any of the same colors that the every next house uses. v. House E has a green roof. vi. House B has a red roof and a black chimney 1. Which of the following is true ? (a) At least two houses have black chimney. (b) At least two houses have red roofs. (c) At least two houses have white chimneys (d) At least two houses have green roofs (e) At least two houses have yellow roofs Ans: (c) 2. Which must be false ? (a) House A has a yellow roof (b) House A & C have different color chimney (c) House D has a black chimney (d) House E has a white chimney (e) House B&D have the same color roof. Ans: (b) 3. If house C has a yellow roof. Which must be true. (a) House E has a white chimney (b) House E has a black chimney (c) House E has a red chimney (d) House D has a red chimney (e) House C has a black chimney

Freshersworld.com Resource Center

17

First Job. Dream Job. Freshersworld.com


Ans: (a) 4. Which possible combinations of roof & chimney can house I. A red roof 7 a black chimney II. A yellow roof & a red chimney III. A yellow roof & a black chimney (a) I only (b) II only (c) III only (d) I & II only (e) I&II&III Ans: (e)

48. Find x+2y (i). x+y=10 (ii). 2x+4y=20 Ans: (b) 49. Is angle BAC is a right angle (i) AB=2BC (2) BC=1.5AC Ans: (e) 50. Is x greater than y (i) x=2k (ii) k=2y Ans: (e)

Freshersworld.com Resource Center

18

First Job. Dream Job. Freshersworld.com

C,C++ Questions
1. Base class has some virtual method and derived class has a method with the same name. If we initialize the base class pointer with derived object,. calling of that virtual method will result in which method being called? a. Base method b. Derived method.. Ans. b 2. For the following C program #define AREA(x)(3.14*x*x) main() {float r1=6.25,r2=2.5,a; a=AREA(r1); printf("\n Area of the circle is %f", a); a=AREA(r2); printf("\n Area of the circle is %f", a); } What is the output? Ans. Area of the circle is 122.656250 Area of the circle is 19.625000 3. What do the following statements indicate. Explain. int(*p)[10] int*f() int(*pf)() int*p[10]

Refer to: -- Kernighan & Ritchie page no. 122 -- Schaum series page no. 323 4. void main() { int d=5; printf("%f",d); } Ans: Undefined

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com

5. void main() { int i; for(i=1;i<4,i++) switch(i) case 1: printf("%d",i);break; { case 2:printf("%d",i);break; case 3:printf("%d",i);break; } switch(i) case 4:printf("%d",i); } Ans: 1,2,3,4

6. void main() { char *s="\12345s\n"; printf("%d",sizeof(s)); } Ans: 6

7. void main() { unsigned i=1; /* unsigned char k= -1 => k=255; */ signed j=-1; /* char k= -1 => k=65535 */ /* unsigned or signed int k= -1 =>k=65535 */ if(i<j) printf("less"); else if(i>j) printf("greater"); else if(i==j) printf("equal"); } Ans: less

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com

8. void main() { float j; j=1000*1000; printf("%f",j); } 1. 2. 3. 4. 1000000 Overflow Error None

Ans: 4

9. How do you declare an array of N pointers to functions returning pointers to functions returning pointers to characters? Ans: The first part of this question can be answered in at least three ways: 1. char *(*(*a[N])())(); 2. Build the declaration up incrementally, using typedefs: typedef char *pc; /* pointer to char */ typedef pc fpc(); /* function returning pointer to char */ typedef fpc *pfpc; /* pointer to above */ typedef pfpc fpfpc(); /* function returning... */ typedef fpfpc *pfpfpc; /* pointer to... */ pfpfpc a[N]; /* array of... */ 3. Use the cdecl program, which turns English into C and vice versa: cdecl> declare a as array of pointer to function returning pointer to function returning pointer to char char *(*(*a[])())() cdecl can also explain complicated declarations, help with casts, and indicate which set of parentheses the arguments go in (for complicated function definitions, like the one above). Any good book on C should explain how to read these complicated C declarations "inside out" to understand them ("declaration mimics use"). The pointer-to-function declarations in the examples above have not included parameter type information. When the parameters
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com


have complicated types, declarations can *really* get messy. (Modern versions of cdecl can help here, too.) 10. A structure pointer is defined of the type time . With 3 fields min,sec hours having pointers to intergers. Write the way to initialize the 2nd element to 10.

11. In the above question an array of pointers is declared. Write the statement to initialize the 3rd element of the 2 element to 10;

12. int f() void main() { f(1); f(1,2); f(1,2,3); } f(int i,int j,int k) { printf("%d %d %d",i,j,k); } What are the number of syntax errors in the above? Ans: None.

13. void main() { int i=7; printf("%d",i++*i++); } Ans: 56

14. #define one 0 #ifdef one printf("one is defined "); #ifndef one printf("one is not defined "); Ans: "one is defined"

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com

15. void main() { int count=10,*temp,sum=0; temp=&count; *temp=20; temp=&sum; *temp=count; printf("%d %d %d ",count,*temp,sum); } Ans: 20 20 20 16. There was question in c working only on unix machine with pattern matching. 14. what is alloca() Ans : It allocates and frees memory after use/after getting out of scope

17. main() { static i=3; printf("%d",i--); return i>0 ? main():0; } Ans: 321

18. char *foo() { char result[100]); strcpy(result,"anything is good"); return(result); } void main() { char *j; j=foo() printf("%s",j); } Ans: anything is good.

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com


19. void main() { char *s[]={ "dharma","hewlett-packard","siemens","ibm"}; char **p; p=s; printf("%s",++*p); printf("%s",*p++); printf("%s",++*p); } Ans: "harma" (p->add(dharma) && (*p)->harma) "harma" (after printing, p->add(hewlett-packard) &&(*p)->harma) "ewlett-packard" 20. Output of the following program is main() {int i=0; for(i=0;i<20;i++) {switch(i) case 0:i+=5; case 1:i+=2; case 5:i+=5; default i+=4; break;} printf("%d,",i); } } a) 0,5,9,13,17 b) 5,9,13,17 c) 12,17,22 d) 16,21 e) Syntax error Ans. (d) 21. What is the ouptut in the following program main() {char c=-64; int i=-32 unsigned int u =-16; if(c>i) {printf("pass1,"); if(c<u) printf("pass2"); else printf("Fail2"); } else
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com


printf("Fail1); if(i<u) printf("pass2"); else printf("Fail2") } a) Pass1,Pass2 b) Pass1,Fail2 c) Fail1,Pass2 d) Fail1,Fail2 e) None of these Ans. (c) 22. What will the following program do? void main() { int i; char a[]="String"; char *p="New Sring"; char *Temp; Temp=a; a=malloc(strlen(p) + 1); strcpy(a,p); //Line number:9// p = malloc(strlen(Temp) + 1); strcpy(p,Temp); printf("(%s, %s)",a,p); free(p); free(a); } //Line number 15// a) Swap contents of p & a and print:(New string, string) b) Generate compilation error in line number 8 c) Generate compilation error in line number 5 d) Generate compilation error in line number 7 e) Generate compilation error in line number 1 Ans. (b) 23. In the following code segment what will be the result of the function, value of x , value of y {unsigned int x=-1; int y; y = ~0; if(x == y) printf("same"); else printf("not same"); }
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com


a) same, MAXINT, -1 b) not same, MAXINT, -MAXINT c) same , MAXUNIT, -1 d) same, MAXUNIT, MAXUNIT e) not same, MAXINT, MAXUNIT Ans. (a) 24. What will be the result of the following program ? char *gxxx() {static char xxx[1024]; return xxx; } main() {char *g="string"; strcpy(gxxx(),g); g = gxxx(); strcpy(g,"oldstring"); printf("The string is : %s",gxxx()); } a) The string is : string b) The string is :Oldstring c) Run time error/Core dump d) Syntax error during compilation e) None of these Ans. (b) 25. Find the output for the following C program main() { char *p1="Name"; char *p2; p2=(char *)malloc(20); while(*p2++=*p1++); printf("%s\n",p2); } Ans. An empty string 26. Find the output for the following C program main() { int x=20,y=35; x = y++ + x++; y = ++y + ++x;
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com


printf("%d %d\n",x,y); } Ans. 57 94 27. Find the output for the following C program main() { int x=5; printf("%d %d %d\n",x,x<<2,x>>2); } Ans. 5 20 1 28 Find the output for the following C program #define swap1(a,b) a=a+b;b=a-b;a=a-b; main() { int x=5,y=10; swap1(x,y); printf("%d %d\n",x,y); swap2(x,y); printf("%d %d\n",x,y); } int swap2(int a,int b) { int temp; temp=a; b=a; a=temp; return; } Ans. 10 5

29 Find the output for the following C program main() { char *ptr = "Ramco Systems"; (*ptr)++; printf("%s\n",ptr); ptr++; printf("%s\n",ptr); } Ans. Samco Systems

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com


Amco Systems 30 Find the output for the following C program #include<stdio.h> main() { char s1[]="Ramco"; char s2[]="Systems"; s1=s2; printf("%s",s1); } Ans. Compilation error giving it cannot be an modifiable 'lvalue'

31 Find the output for the following C program #include<stdio.h> main() { char *p1; char *p2; p1=(char *) malloc(25); p2=(char *) malloc(25); strcpy(p1,"Ramco"); strcpy(p2,"Systems"); strcat(p1,p2); printf("%s",p1); } Ans. RamcoSystems

32. Find the output for the following C program given that [1]. The following variable is available in file1.c static int average_float; Ans. All the functions in the file1.c can access the variable

33. Find the output for the following C program # define TRUE 0 some code while(TRUE) { some code } Ans. This won't go into the loop as TRUE is defined as 0

Freshersworld.com Resource Center

10

First Job. Dream Job. Freshersworld.com


34. struct list{ int x; struct list *next; }*head; the struct head.x =100 Is the above assignment to pointer is correct or wrong ? Ans. Wrong 35.What is the output of the following ? int i; i=1; i=i+2*i++; printf(%d,i); Ans. 4 36. FILE *fp1,*fp2; fp1=fopen("one","w") fp2=fopen("one","w") fputc('A',fp1) fputc('B',fp2) fclose(fp1) fclose(fp2) } Find the Error, If Any? Ans. no error. But It will over writes on same file. 37. What are the output(s) for the following ? 38. #include<malloc.h> char *f() {char *s=malloc(8); strcpy(s,"goodbye"); } main() { char *f(); printf("%c",*f()='A');

Freshersworld.com Resource Center

11

First Job. Dream Job. Freshersworld.com


39. #define MAN(x,y) (x)>(y)?(x):(y) {int i=10; j=5; k=0; k=MAX(i++,++j); printf(%d %d %d %d,i,j,k); } Ans. 12 6 11 40. void main() { int i=7; printf("%d",i++*i++); } Ans: 56

Freshersworld.com Resource Center

12

First Job. Dream Job. Freshersworld.com

C++ Questions
Note : All the programs are tested under Turbo C++ 3.0, 4.5 and Microsoft VC++ 6.0 compilers. It is assumed that, Programs run under Windows environment, The underlying machine is an x86 based system, Program is compiled using Turbo C/C++ compiler. The program output may depend on the information based on this assumptions (for example sizeof(int) == 2 may be assumed). 1) class Sample { public: int *ptr; Sample(int i) { ptr = new int(i); } ~Sample() { delete ptr; } void PrintVal() { cout << "The value is " << *ptr; } }; void SomeFunc(Sample x) { cout << "Say i am in someFunc " << endl; } int main() { Sample s1= 10; SomeFunc(s1); s1.PrintVal(); } Answer: Say i am in someFunc Null pointer assignment(Run-time error) Explanation: As the object is passed by value to SomeFunc the destructor of the object is called when the control returns from the function. So when PrintVal is called it meets

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com up with ptr that has been freed.The solution is to pass the Sample object by reference to SomeFunc: void SomeFunc(Sample &x) { cout << "Say i am in someFunc " << endl; } because when we pass objects by refernece that object is not destroyed. while returning from the function.

2) Which is the parameter that is added to every non-static member function when it is called? Answer: this pointer 3) class base { public: int bval; base(){ bval=0;} }; class deri:public base { public: int dval; deri(){ dval=1;} }; void SomeFunc(base *arr,int size) { for(int i=0; i<size; i++,arr++) cout<<arr->bval; cout<<endl; } int main() { base BaseArr[5]; SomeFunc(BaseArr,5); deri DeriArr[5]; SomeFunc(DeriArr,5); } Answer:
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com 00000 01010 Explanation: The function SomeFunc expects two arguments.The first one is a pointer to an array of base class objects and the second one is the sizeof the array.The first call of someFunc calls it with an array of bae objects, so it works correctly and prints the bval of all the objects. When Somefunc is called the second time the argument passed is the pointeer to an array of derived class objects and not the array of base class objects. But that is what the function expects to be sent. So the derived class pointer is promoted to base class pointer and the address is sent to the function. SomeFunc() knows nothing about this and just treats the pointer as an array of base class objects. So when arr++ is met, the size of base class object is taken into consideration and is incremented by sizeof(int) bytes for bval (the deri class objects have bval and dval as members and so is of size >= sizeof(int)+sizeof(int) ). 4) class base { public: void baseFun(){ cout<<"from base"<<endl;} }; class deri:public base { public: void baseFun(){ cout<< "from derived"<<endl;} }; void SomeFunc(base *baseObj) { baseObj->baseFun(); } int main() { base baseObject; SomeFunc(&baseObject); deri deriObject; SomeFunc(&deriObject); } Answer: from base from base Explanation: As we have seen in the previous case, SomeFunc expects a pointer to a base class. Since a pointer to a derived class object is passed, it treats the argument only as a base class pointer and the corresponding base function is called. 5) class base {
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com public: virtual void baseFun(){ cout<<"from base"<<endl;} }; class deri:public base { public: void baseFun(){ cout<< "from derived"<<endl;} }; void SomeFunc(base *baseObj) { baseObj->baseFun(); } int main() { base baseObject; SomeFunc(&baseObject); deri deriObject; SomeFunc(&deriObject); } Answer: from base from derived Explanation: Remember that baseFunc is a virtual function. That means that it supports runtime polymorphism. So the function corresponding to the derived class object is called.

void main() { int a, *pa, &ra; pa = &a; ra = a; cout <<"a="<<a <<"*pa="<<*pa <<"ra"<<ra ; } /* Answer : Compiler Error: 'ra',reference must be initialized Explanation : Pointers are different from references. One of the main differences is that the pointers can be both initialized and assigned, whereas references can only be initialized. So this code issues an error. */ const int size = 5; void print(int *ptr)
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com { cout<<ptr[0]; } void print(int ptr[size]) { cout<<ptr[0]; } void main() { int a[size] = {1,2,3,4,5}; int *b = new int(size); print(a); print(b); } /* Answer: Compiler Error : function 'void print(int *)' already has a body Explanation: Arrays cannot be passed to functions, only pointers (for arrays, base addresses) can be passed. So the arguments int *ptr and int prt[size] have no difference as function arguments. In other words, both the functoins have the same signature and so cannot be overloaded. */ class some{ public: ~some() { cout<<"some's destructor"<<endl; } }; void main() { some s; s.~some(); } /* Answer: some's destructor some's destructor Explanation:
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com Destructors can be called explicitly. Here 's.~some()' explicitly calls the destructor of 's'. When main() returns, destructor of s is called again, hence the result. */ #include <iostream.h> class fig2d { int dim1; int dim2; public: fig2d() { dim1=5; dim2=6;} virtual void operator<<(ostream & rhs); }; void fig2d::operator<<(ostream &rhs) { rhs <<this->dim1<<" "<<this->dim2<<" "; } /*class fig3d : public fig2d { int dim3; public: fig3d() { dim3=7;} virtual void operator<<(ostream &rhs); }; void fig3d::operator<<(ostream &rhs) { fig2d::operator <<(rhs); rhs<<this->dim3; } */ void main() { fig2d obj1; // fig3d obj2; obj1 << cout; obj2 << cout;

// } /*

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com Answer : 56 Explanation: In this program, the << operator is overloaded with ostream as argument. This enables the 'cout' to be present at the right-hand-side. Normally, 'cout' is implemented as global function, but it doesn't mean that 'cout' is not possible to be overloaded as member function. Overloading << as virtual member function becomes handy when the class in which it is overloaded is inherited, and this becomes available to be overrided. This is as opposed to global friend functions, where friend's are not inherited. */ class opOverload{ public: bool operator==(opOverload temp); }; bool opOverload::operator==(opOverload temp){ if(*this == temp ){ cout<<"The both are same objects\n"; return true; } else{ cout<<"The both are different\n"; return false; } } void main(){ opOverload a1, a2; a1= =a2; } Answer : Runtime Error: Stack Overflow Explanation : Just like normal functions, operator functions can be called recursively. This program just illustrates that point, by calling the operator == function recursively, leading to an infinite loop.

class complex{ double re; double im;


Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com public: complex() : re(1),im(0.5) {} bool operator==(complex &rhs); operator int(){} }; bool complex::operator == (complex &rhs){ if((this->re == rhs.re) && (this->im == rhs.im)) return true; else return false; } int main(){ complex c1; cout<< c1; } Answer : Garbage value Explanation: The programmer wishes to print the complex object using output re-direction operator,which he has not defined for his lass.But the compiler instead of giving an error sees the conversion function and converts the user defined object to standard object and prints some garbage value.

class complex{ double re; double im; public: complex() : re(0),im(0) {} complex(double n) { re=n,im=n;}; complex(int m,int n) { re=m,im=n;} void print() { cout<<re; cout<<im;} }; void main(){ complex c3; double i=5; c3 = i; c3.print(); } Answer:
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com 5,5 Explanation: Though no operator= function taking complex, double is defined, the double on the rhs is converted into a temporary object using the single argument constructor taking double and assigned to the lvalue.

void main() { int a, *pa, &ra; pa = &a; ra = a; cout <<"a="<<a <<"*pa="<<*pa <<"ra"<<ra ; } Answer : Compiler Error: 'ra',reference must be initialized Explanation : Pointers are different from references. One of the main differences is that the pointers can be both initialized and assigned, whereas references can only be initialized. So this code issues an error. Try it Yourself 1) Determine the output of the 'C++' Codelet. class base { public : out() { cout<<"base "; } }; class deri{ public : out() { cout<<"deri "; } }; void main() { deri dp[3]; base *bp = (base*)dp; for (int i=0; i<3;i++) (bp++)->out(); }

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com 2) Justify the use of virtual constructors and destructors in C++. 3) Each C++ object possesses the 4 member fns,(which can be declared by the programmer explicitly or by the implementation if they are not available). What are those 4 functions? 4) What is wrong with this class declaration? class something { char *str; public: something(){ st = new char[10]; } ~something() { delete str; } }; 5) Inheritance is also known as -------- relationship. Containership as relationship. ________

6) When is it necessary to use member-wise initialization list (also known as header initialization list) in C++? 7) Which is the only operator in C++ which can be overloaded but NOT inherited. 8) Is there anything wrong with this C++ class declaration? class temp { int value1; mutable int value2; public : void fun(int val) const{ ((temp*) this)->value1 = 10; value2 = 10; } };

Freshersworld.com Resource Center

10

First Job. Dream Job. Freshersworld.com 1. What is a modifier? Answer: A modifier, also called a modifying function is a member function that changes the value of at least one data member. In other words, an operation that modifies the state of an object. Modifiers are also known as mutators. 2. What is an accessor? Answer: An accessor is a class operation that does not modify the state of an object. The accessor functions need to be declared as const operations 3. Differentiate between a template class and class template. Answer:
Template class:

A generic definition or a parameterized class not instantiated until the client provides the needed information. Its jargon for plain templates.
Class template:

A class template specifies how individual classes can be constructed much like the way a class specifies how individual objects can be constructed. Its jargon for plain classes. 4. When does a name clash occur? Answer: A name clash occurs when a name is defined in more than one place. For example., two different class libraries could give two different classes the same name. If you try to use many class libraries at the same time, there is a fair chance that you will be unable to compile or link the program because of name clashes. 5. Define namespace. Answer: It is a feature in c++ to minimize name collisions in the global name space. This namespace keyword assigns a distinct name to a library that allows other libraries to use the same identifier names without creating any name collisions. Furthermore, the compiler uses the namespace signature for differentiating the definitions. 6. What is the use of using declaration. Answer: A using declaration makes it possible to use a name from a namespace without the scope operator. 7. What is an Iterator class? Answer: A class that is used to traverse through the objects maintained by a container class. There are five categories of iterators: input iterators, output iterators,
Freshersworld.com Resource Center

11

First Job. Dream Job. Freshersworld.com forward iterators, bidirectional iterators, random access. An iterator is an entity that gives access to the contents of a container object without violating encapsulation constraints. Access to the contents is granted on a one-at-a-time basis in order. The order can be storage order (as in lists and queues) or some arbitrary order (as in array indices) or according to some ordering relation (as in an ordered binary tree). The iterator is a construct, which provides an interface that, when called, yields either the next element in the container, or some value denoting the fact that there are no more elements to examine. Iterators hide the details of access to and update of the elements of a container class. The simplest and safest iterators are those that permit read-only access to the contents of a container class. The following code fragment shows how an iterator might appear in code: cont_iter:=new cont_iterator(); x:=cont_iter.next(); while x/=none do ... s(x); ... x:=cont_iter.next(); end; In this example, cont_iter is the name of the iterator. It is created on the first line by instantiation of cont_iterator class, an iterator class defined to iterate over some container class, cont. Succesive elements from the container are carried to x. The loop terminates when x is bound to some empty value. (Here, none)In the middle of the loop, there is s(x) an operation on x, the current element from the container. The next element of the container is obtained at the bottom of the loop. 9. List out some of the OODBMS available. Answer: GEMSTONE/OPAL of Gemstone systems. ONTOS of Ontos. Objectivity of Objectivity inc. Versant of Versant object technology. Object store of Object Design. ARDENT of ARDENT software. POET of POET software. 10. List out some of the object-oriented methodologies. Answer: Object Oriented Development (OOD) (Booch 1991,1994). Object Oriented Analysis and Design (OOA/D) (Coad and Yourdon 1991). Object Modelling Techniques (OMT) (Rumbaugh 1991). Object Oriented Software Engineering (Objectory) (Jacobson 1992). Object Oriented Analysis (OOA) (Shlaer and Mellor 1992).
Freshersworld.com Resource Center

12

First Job. Dream Job. Freshersworld.com The Fusion Method (Coleman 1991).

11. What is an incomplete type? Answer: Incomplete types refers to pointers in which there is non availability of the implementation of the referenced location or it points to some location whose value is not available for modification. Example: int *i=0x400 // i points to address 400 *i=0; //set the value of memory location pointed by i. Incomplete types are otherwise called uninitialized pointers. 12. What is a dangling pointer? Answer: A dangling pointer arises when you use the address of an object after its lifetime is over. This may occur in situations like returning addresses of the automatic variables from a function or using the address of the memory block after it is freed. 13. Differentiate between the message and method. Answer: Message Method Objects communicate by sending messages Provides response to a message. to each other. A message is sent to invoke a method. It is an implementation of an operation. 14. What is an adaptor class or Wrapper class? Answer: A class that has no functionality of its own. Its member functions hide the use of a third party software component or an object with the non-compatible interface or a non- object- oriented implementation. 15. What is a Null object? Answer: It is an object of some class whose purpose is to indicate that a real object of that class does not exist. One common use for a null object is a return value from a member function that is supposed to return an object with some specified properties but cannot find such an object. 16. What is class invariant? Answer: A class invariant is a condition that defines all valid states for an object. It is a logical condition to ensure the correct working of a class. Class invariants must hold when an object is created, and they must be preserved under all operations of the class. In particular all class invariants are both preconditions and post-conditions for all operations or member functions of the class.
Freshersworld.com Resource Center

13

First Job. Dream Job. Freshersworld.com

17. What do you mean by Stack unwinding? Answer: It is a process during exception handling when the destructor is called for all local objects between the place where the exception was thrown and where it is caught. 18. Define precondition and post-condition to a member function. Answer: Precondition: A precondition is a condition that must be true on entry to a member function. A class is used correctly if preconditions are never false. An operation is not responsible for doing anything sensible if its precondition fails to hold. For example, the interface invariants of stack class say nothing about pushing yet another element on a stack that is already full. We say that isful() is a precondition of the push operation. Post-condition: A post-condition is a condition that must be true on exit from a member function if the precondition was valid on entry to that function. A class is implemented correctly if post-conditions are never false. For example, after pushing an element on the stack, we know that isempty() must necessarily hold. This is a post-condition of the push operation. 19. What are the conditions that have to be met for a condition to be an invariant of the class? Answer: The condition should hold at the end of every constructor. The condition should hold at the end of every mutator(non-const) operation. 20. What are proxy objects? Answer: Objects that stand for other objects are called proxy objects or surrogates. Example: template<class T> class Array2D { public: class Array1D { public: T& operator[] (int index); const T& operator[] (int index) const;
Freshersworld.com Resource Center

14

First Job. Dream Job. Freshersworld.com ... }; Array1D operator[] (int index); const Array1D operator[] (int index) const; ... }; The following then becomes legal: Array2D<float>data(10,20); ........ cout<<data[3][6]; // fine Here data[3] yields an Array1D object and the operator [] invocation on that object yields the float in position(3,6) of the original two dimensional array. Clients of the Array2D class need not be aware of the presence of the Array1D class. Objects of this latter class stand for one-dimensional array objects that, conceptually, do not exist for clients of Array2D. Such clients program as if they were using real, live, two-dimensional arrays. Each Array1D object stands for a one-dimensional array that is absent from a conceptual model used by the clients of Array2D. In the above example, Array1D is a proxy class. Its instances stand for one-dimensional arrays that, conceptually, do not exist. 21. Name some pure object oriented languages. Answer:

Smalltalk, Java, Eiffel, Sather.

22. Name the operators that cannot be overloaded. Answer: sizeof .

.*

.->

::

?:

23. What is a node class? Answer: A node class is a class that, relies on the base class for services and implementation, provides a wider interface to te users than its base class, relies primarily on virtual functions in its public interface depends on all its direct and indirect base class can be understood only in the context of the base class can be used as base for further derivation can be used to create objects.
Freshersworld.com Resource Center

15

First Job. Dream Job. Freshersworld.com A node class is a class that has added new services or functionality beyond the services inherited from its base class. 24. What is an orthogonal base class? Answer: If two base classes have no overlapping methods or data they are said to be independent of, or orthogonal to each other. Orthogonal in the sense means that two classes operate in different dimensions and do not interfere with each other in any way. The same derived class may inherit such classes with no difficulty.

25. What is a container class? What are the types of container classes? Answer: A container class is a class that is used to hold objects in memory or external storage. A container class acts as a generic holder. A container class has a predefined behavior and a well-known interface. A container class is a supporting class whose purpose is to hide the topology used for maintaining the list of objects in memory. When a container class contains a group of mixed objects, the container is called a heterogeneous container; when the container is holding a group of objects that are all the same, the container is called a homogeneous container. 26. What is a protocol class? Answer: An abstract class is a protocol class if: it neither contains nor inherits from classes that contain member data, nonvirtual functions, or private (or protected) members of any kind. it has a non-inline virtual destructor defined with an empty implementation, all member functions other than the destructor including inherited functions, are declared pure virtual functions and left undefined. 27. What is a mixin class? Answer: A class that provides some but not all of the implementation for a virtual base class is often called mixin. Derivation done just for the purpose of redefining the virtual functions in the base classes is often called mixin inheritance. Mixin classes typically don't share common bases. 28. What is a concrete class? Answer: A concrete class is used to define a useful object that can be instantiated as an automatic variable on the program stack. The implementation of a concrete class is defined. The concrete class is not intended to be a base class and no attempt to minimize dependency on other classes in the implementation or behavior of the class.
Freshersworld.com Resource Center

16

First Job. Dream Job. Freshersworld.com

29.What is the handle class? Answer: A handle is a class that maintains a pointer to an object that is programmatically accessible through the public interface of the handle class. Explanation: In case of abstract classes, unless one manipulates the objects of these classes through pointers and references, the benefits of the virtual functions are lost. User code may become dependent on details of implementation classes because an abstract type cannot be allocated statistically or on the stack without its size being known. Using pointers or references implies that the burden of memory management falls on the user. Another limitation of abstract class object is of fixed size. Classes however are used to represent concepts that require varying amounts of storage to implement them. A popular technique for dealing with these issues is to separate what is used as a single object in two parts: a handle providing the user interface and a representation holding all or most of the object's state. The connection between the handle and the representation is typically a pointer in the handle. Often, handles have a bit more data than the simple representation pointer, but not much more. Hence the layout of the handle is typically stable, even when the representation changes and also that handles are small enough to move around relatively freely so that the user neednt use the pointers and the references. 30. What is an action class? Answer: The simplest and most obvious way to specify an action in C++ is to write a function. However, if the action has to be delayed, has to be transmitted 'elsewhere' before being performed, requires its own data, has to be combined with other actions, etc then it often becomes attractive to provide the action in the form of a class that can execute the desired action and provide other services as well. Manipulators used with iostreams is an obvious example. Explanation: A common form of action class is a simple class containing just one virtual function. class Action { public: virtual int do_it( int )=0; virtual ~Action( ); } Given this, we can write code say a member that can store actions for later execution without using pointers to functions, without knowing anything about the

Freshersworld.com Resource Center

17

First Job. Dream Job. Freshersworld.com objects involved, and without even knowing the name of the operation it invokes. For example: class write_file : public Action { File& f; public: int do_it(int) { return fwrite( ).suceed( ); } }; class error_message: public Action { response_box db(message.cstr( ),"Continue","Cancel","Retry"); switch (db.getresponse( )) { case 0: return 0; case 1: abort(); case 2: current_operation.redo( );return 1; } }; A user of the Action class will be completely isolated from any knowledge of derived classes such as write_file and error_message.

31. When can you tell that a memory leak will occur? Answer: A memory leak occurs when a program loses the ability to free a block of dynamically allocated memory. 32.What is a parameterized type? Answer: A template is a parameterized construct or type containing generic code that can use or manipulate any type. It is called parameterized because an actual type is a parameter of the code body. Polymorphism may be achieved through parameterized types. This type of polymorphism is called parameteric polymorphism. Parameteric polymorphism is the mechanism by which the same code is used on different types passed as parameters. 33. Differentiate between a deep copy and a shallow copy? Answer:
Freshersworld.com Resource Center

18

First Job. Dream Job. Freshersworld.com Deep copy involves using the contents of one object to create another instance of the same class. In a deep copy, the two objects may contain ht same information but the target object will have its own buffers and resources. the destruction of either object will not affect the remaining object. The overloaded assignment operator would create a deep copy of objects. Shallow copy involves copying the contents of one object into another instance of the same class thus creating a mirror image. Owing to straight copying of references and pointers, the two objects will share the same externally contained contents of the other object to be unpredictable. Explanation: Using a copy constructor we simply copy the data values member by member. This method of copying is called shallow copy. If the object is a simple class, comprised of built in types and no pointers this would be acceptable. This function would use the values and the objects and its behavior would not be altered with a shallow copy, only the addresses of pointers that are members are copied and not the value the address is pointing to. The data values of the object would then be inadvertently altered by the function. When the function goes out of scope, the copy of the object with all its data is popped off the stack. If the object has any pointers a deep copy needs to be executed. With the deep copy of an object, memory is allocated for the object in free store and the elements pointed to are copied. A deep copy is used for objects that are returned from a function. 34. What is an opaque pointer? Answer: A pointer is said to be opaque if the definition of the type to which it points to is not included in the current translation unit. A translation unit is the result of merging an implementation file with all its headers and header files. 35. What is a smart pointer? Answer: A smart pointer is an object that acts, looks and feels like a normal pointer but offers more functionality. In C++, smart pointers are implemented as template classes that encapsulate a pointer and override standard pointer operators. They have a number of advantages over regular pointers. They are guaranteed to be initialized as either null pointers or pointers to a heap object. Indirection through a null pointer is checked. No delete is ever necessary. Objects are automatically freed when the last pointer to them has gone away. One significant problem with these smart pointers is that unlike regular pointers, they don't respect inheritance. Smart pointers are unattractive for polymorphic code. Given below is an example for the implementation of smart pointers.
Example:

template <class X> class smart_pointer { public: smart_pointer();

// makes a null pointer 19

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com smart_pointer(const X& x) X& operator *( ); const X& operator*( ) const; X* operator->() const; smart_pointer(const smart_pointer <X> &); const smart_pointer <X> & operator =(const smart_pointer<X>&); ~smart_pointer(); private: //... }; This class implement a smart pointer to an object of type X. The object itself is located on the heap. Here is how to use it: smart_pointer <employee> p= employee("Harris",1333); Like other overloaded operators, p will behave like a regular pointer, cout<<*p; p->raise_salary(0.5); 36. What is reflexive association? Answer: The 'is-a' is called a reflexive association because the reflexive association permits classes to bear the is-a association not only with their super-classes but also with themselves. It differs from a 'specializes-from' as 'specializes-from' is usually used to describe the association between a super-class and a sub-class. For example: Printer is-a printer. 37. What is slicing? Answer: Slicing means that the data added by a subclass are discarded when an object of the subclass is passed or returned by value or from a function expecting a base class object. Explanation: Consider the following class declaration: class base { ... base& operator =(const base&); base (const base&); } void fun( ) { base e=m; e=m; } // makes pointer to copy of x

Freshersworld.com Resource Center

20

First Job. Dream Job. Freshersworld.com As base copy functions don't know anything about the derived only the base part of the derived is copied. This is commonly referred to as slicing. One reason to pass objects of classes in a hierarchy is to avoid slicing. Other reasons are to preserve polymorphic behavior and to gain efficiency. 38. What is name mangling? Answer: Name mangling is the process through which your c++ compilers give each function in your program a unique name. In C++, all programs have at-least a few functions with the same name. Name mangling is a concession to the fact that linker always insists on all function names being unique.
Example:

In general, member names are made unique by concatenating the name of the member with that of the class e.g. given the declaration: class Bar { public: int ival; ... }; ival becomes something like: // a possible member name mangling ival__3Bar Consider this derivation: class Foo : public Bar { public: int ival; ... } The internal representation of a Foo object is the concatenation of its base and derived class members. // Pseudo C++ code // Internal representation of Foo class Foo { public: int ival__3Bar; int ival__3Foo; ...
Freshersworld.com Resource Center

21

First Job. Dream Job. Freshersworld.com }; Unambiguous access of either ival members is achieved through name mangling. Member functions, because they can be overloaded, require an extensive mangling to provide each with a unique name. Here the compiler generates the same name for the two overloaded instances(Their argument lists make their instances unique).

39. What are proxy objects? Answer: Objects that points to other objects are called proxy objects or surrogates. Its an object that provides the same interface as its server object but does not have any functionality. During a method invocation, it routes data to the true server object and sends back the return value to the object. 40. Differentiate between declaration and definition in C++. Answer: A declaration introduces a name into the program; a definition provides a unique description of an entity (e.g. type, instance, and function). Declarations can be repeated in a given scope, it introduces a name in a given scope. There must be exactly one definition of every object, function or class used in a C++ program. A declaration is a definition unless: it declares a function without specifying its body, it contains an extern specifier and no initializer or function body, it is the declaration of a static class data member without a class definition, it is a class name definition, it is a typedef declaration. A definition is a declaration unless: it defines a static class data member, it defines a non-inline member function.

41. What is cloning? Answer: An object can carry out copying in two ways i.e. it can set itself to be a copy of another object, or it can return a copy of itself. The latter process is called cloning.
Freshersworld.com Resource Center

22

First Job. Dream Job. Freshersworld.com

42. Describe the main characteristics of static functions. Answer: The main characteristics of static functions include, It is without the a this pointer, It can't directly access the non-static members of its class It can't be declared const, volatile or virtual. It doesn't need to be invoked through an object of its class, although for convenience, it may. 43. Will the inline function be compiled as the inline function always? Justify. Answer: An inline function is a request and not a command. Hence it won't be compiled as an inline function always. Explanation: Inline-expansion could fail if the inline function contains loops, the address of an inline function is used, or an inline function is called in a complex expression. The rules for inlining are compiler dependent. 44. Define a way other than using the keyword inline to make a function inline. Answer: The function must be defined inside the class. 45. How can a '::' operator be used as unary operator? Answer: The scope operator can be used to refer to members of the global namespace. Because the global namespace doesnt have a name, the notation :: member-name refers to a member of the global namespace. This can be useful for referring to members of global namespace whose names have been hidden by names declared in nested local scope. Unless we specify to the compiler in which namespace to search for a declaration, the compiler simple searches the current scope, and any scopes in which the current scope is nested, to find the declaration for the name. 46. What is placement new? Answer: When you want to call a constructor directly, you use the placement new. Sometimes you have some raw memory that's already been allocated, and you need to construct an object in the memory you have. Operator new's special version placement new allows you to do it. class Widget { public :
Freshersworld.com Resource Center

23

First Job. Dream Job. Freshersworld.com Widget(int widgetsize); ... Widget* Construct_widget_int_buffer(void *buffer,int widgetsize) { return new(buffer) Widget(widgetsize); } }; This function returns a pointer to a Widget object that's constructed within the buffer passed to the function. Such a function might be useful for applications using shared memory or memory-mapped I/O, because objects in such applications must be placed at specific addresses or in memory allocated by special routines.

OOAD 1. What do you mean by analysis and design? Analysis: Basically, it is the process of determining what needs to be done before how it should be done. In order to accomplish this, the developer refers the existing systems and documents. So, simply it is an art of discovery. Design: It is the process of adopting/choosing the one among the many, which best accomplishes the users needs. So, simply, it is compromising mechanism. 2. What are the steps involved in designing? Before getting into the design the designer should go through the SRS prepared by the System Analyst. The main tasks of design are Architectural Design and Detailed Design. In Architectural Design we find what are the main modules in the problem domain. In Detailed Design we find what should be done within each module. 3. What are the main underlying concepts of object orientation? Objects, messages, class, inheritance and polymorphism are the main concepts of object orientation. 4. What do u meant by "SBI" of an object? SBI stands for State, Behavior and Identity. Since every object has the above three. State: It is just a value to the attribute of an object at a particular time. Behaviour:
Freshersworld.com Resource Center

24

First Job. Dream Job. Freshersworld.com It describes the actions and their reactions of that object. Identity: An object has an identity that characterizes its own existence. The identity makes it possible to distinguish any object in an unambiguous way, and independently from its state. 5. Differentiate persistent & non-persistent objects? Persistent refers to an object's ability to transcend time or space. A persistent object stores/saves its state in a permanent storage system with out losing the information represented by the object. A non-persistent object is said to be transient or ephemeral. By default objects are considered as non-persistent. 6. What do you meant by active and passive objects? Active objects are one which instigate an interaction which owns a thread and they are responsible for handling control to other objects. In simple words it can be referred as client. Passive objects are one, which passively waits for the message to be processed. It waits for another object that requires its services. In simple words it can be referred as server. Diagram: client server (Active) (Passive) 7. What is meant by software development method? Software development method describes how to model and build software systems in a reliable and reproducible way. To put it simple, methods that are used to represent ones' thinking using graphical notations. 8. What are models and meta models? Model: It is a complete description of something (i.e. system). Meta model: It describes the model elements, syntax and semantics of the notation that allows their manipulation. 9. What do you meant by static and dynamic modeling? Static modeling is used to specify structure of the objects that exist in the problem domain. These are expressed using class, object and USECASE diagrams. But Dynamic modeling refers representing the object interactions during runtime. It is represented by sequence, activity, collaboration and statechart diagrams. 10. How to represent the interaction between the modeling elements? Model element is just a notation to represent (Graphically) the entities that
Freshersworld.com Resource Center

25

First Job. Dream Job. Freshersworld.com exist in the problem domain. e.g. for modeling element is class notation, object notation etc. Relationships are used to represent the interaction between the modeling elements. The following are the Relationships. Association: Its' just a semantic connection two classes. e.g.: uses class A class B Aggregation: Its' the relationship between two classes which are related in the fashion that master and slave. The master takes full rights than the slave. Since the slave works under the master. It is represented as line with diamond in the master area. ex: car contains wheels, etc. car car wheels

Containment: This relationship is applied when the part contained with in the whole part, dies when the whole part dies. It is represented as darked diamond at the whole part. example: class A{ //some code }; class B { A aa; // an object of class A; // some code for class B; }; In the above example we see that an object of class A is instantiated with in the class B. so the object class A dies when the object class B dies.we can represnt it in diagram like this. class A class B

Generalization: This relationship used when we want represents a class, which captures the common states of objects of different classes. It is represented as arrow line pointed at the class, which has captured the common states. class A

Freshersworld.com Resource Center

class B

26 class C

First Job. Dream Job. Freshersworld.com

Dependency: It is the relationship between dependent and independent classes. Any change in the independent class will affect the states of the dependent class. DIAGRAM: class A class B 11. Why generalization is very strong? Even though Generalization satisfies Structural, Interface, Behaviour properties. It is mathematically very strong, as it is Antisymmetric and Transitive. Antisymmetric: employee is a person, but not all persons are employees. Mathematically all As are B, but all Bs not A. Transitive: A=>B, B=>c then A=>c. A. Salesman. B. Employee. C. Person. Note: All the other relationships satisfy all the properties like Structural properties, Interface properties, Behaviour properties. 12. Differentiate Aggregation and containment? Aggregation is the relationship between the whole and a part. We can add/subtract some properties in the part (slave) side. It won't affect the whole part. Best example is Car, which contains the wheels and some extra parts. Even though the parts are not there we can call it as car. But, in the case of containment the whole part is affected when the part within that got affected. The human body is an apt example for this relationship. When the whole body dies the parts (heart etc) are died. 13. Can link and Association applied interchangeably? No, You cannot apply the link and Association interchangeably. Since link is used represent the relationship between the two objects. But Association is used represent the relationship between the two classes. link :: student:Abhilash course:MCA Association:: student course 14. what is meant by "method-wars"? Before 1994 there were different methodologies like Rumbaugh, Booch, Jacobson, Meyer etc who followed their own notations to model the systems. The developers were in a dilemma to choose the method which best accomplishes their needs. This particular span was called as "method-wars" 15. Whether unified method and unified modeling language are same or different?
Freshersworld.com Resource Center

27

First Job. Dream Job. Freshersworld.com Unified method is convergence of the Rumbaugh and Booch. Unified modeling lang. is the fusion of Rumbaugh, Booch and Jacobson as well as Betrand Meyer (whose contribution is "sequence diagram"). Its' the superset of all the methodologies. 16. Who were the three famous amigos and what was their contribution to the object community? The Three amigos namely, James Rumbaugh (OMT): A veteran in analysis who came up with an idea about the objects and their Relationships (in particular Associations). Grady Booch: A veteran in design who came up with an idea about partitioning of systems into subsystems. Ivar Jacobson (Objectory): The father of USECASES, who described about the user and system interaction. 17. Differentiate the class representation of Booch, Rumbaugh and UML? If you look at the class representaiton of Rumbaugh and UML, It is some what similar and both are very easy to draw. Representation: OMT UML. Diagram:

Booch: In this method classes are represented as "Clouds" which are not very easy to draw as for as the developer's view is concern. Diagram:

18. What is an USECASE? Why it is needed? A Use Case is a description of a set of sequence of actions that a system performs that yields an observable result of value to a particular action. In SSAD process <=> In OOAD USECASE. It is represented elliptically. Representation:

19. Who is an Actor?


Freshersworld.com Resource Center

28

First Job. Dream Job. Freshersworld.com An Actor is someone or something that must interact with the system.In addition to that an Actor initiates the process(that is USECASE). It is represented as a stickman like this. Diagram:

20. What is guard condition? Guard condition is one, which acts as a firewall. The access from a particular object can be made only when the particular condition is met. For Example, customer check customer number ATM. Here the object on the customer accesses the ATM facility only when the guard condition is met. 21. Differentiate the following notations? I: :obj1 :obj2 II: :obj1 :obj2

In the above representation I, obj1 sends message to obj2. But in the case of II the data is transferred from obj1 to obj2. 22. USECASE is an implementation independent notation. How will the designer give the implementation details of a particular USECASE to the programmer? This can be accomplished by specifying the relationship called "refinement which talks about the two different abstraction of the same thing. Or example, calculate pay calculate class1 class2 class3 23. Suppose a class acts an Actor in the problem domain, how to represent it in the static model? In this scenario you can use stereotype. Since stereotype is just a string that gives extra semantic to the particular entity/model element. It is given with in the << >>. class A << Actor>> attributes

Freshersworld.com Resource Center

29

First Job. Dream Job. Freshersworld.com methods. 24. Why does the function arguments are called as "signatures"? The arguments distinguish functions with the same name (functional polymorphism). The name alone does not necessarily identify a unique function. However, the name and its arguments (signatures) will uniquely identify a function. In real life we see suppose, in class there are two guys with same name, but they can be easily identified by their signatures. The same concept is applied here. ex: class person { public: char getsex(); void setsex(char); void setsex(int); }; In the above example we see that there is a function setsex() with same name but with different signature.

Freshersworld.com Resource Center

30

First Job. Dream Job. Freshersworld.com

Freshersworld.com Resource Center

31

1.
Can we declare a static function as virtual? Ans: No. The virtual function mechanism is used on the specific object that determines which virtual function to call. Since the static functions are not any way related to objects, they cannot be declared as virtual. -----------------------------------------------------------------------------------------------2. Can user-defined object be declared as static data member of another class? Ans: Yes. The following code shows how to initialize a user-defined object. #include class test { int i ; public : test ( int ii = 0 ) { i = ii ; } }; class sample { static test s ; }; test sample::s ( 26 ) ; Here we have initialized the object s by calling the one-argument constructor. We can use the same convention to initialize the object by calling multiple-argument constructor. -----------------------------------------------------------------------------------------------3. What is forward referencing and when should it be used? Ans: Consider the following program: class test { public : friend void fun ( sample, test ) ; }; class sample

{ public : friend void fun ( sample, test ) ; }; void fun ( sample s, test t ) { // code } void main( ) { sample s ; test t ; fun ( s, t ) ; } This program would not compile. It gives an error that sample is undeclared identifier in the statement friend void fun ( sample, test ) ; of the class test. This is so because the class sample is defined below the class test and we are using it before its definition. To overcome this error we need to give forward reference of the class sample before the definition of class test. The following statement is the forward reference of class sample. Forward referencing is generally required when we make a class or a function as a friend. -----------------------------------------------------------------------------------------------4. The istream_withassign class has been derived from the istream class and overloaded assignment operator has been added to it. The _withassign classes are much like their base classes except that they include overloaded assignment operators. Using these operators the objects of the _withassign classes can be copied. The istream, ostream, and iostream classes are made uncopyable by making their overloaded copy constructor and assignment operators private. -----------------------------------------------------------------------------------------------5. How do I write my own zero-argument manipulator that should work same as hex? Ans: This is shown in following program. #include ostream& myhex ( ostream &o ) { o.setf ( ios::hex) ; return o ; }

void main( ) { cout << endl << myhex << 2000 ; } -----------------------------------------------------------------------------------------------6. We all know that a const variable needs to be initialized at the time of declaration. Then how come the program given below runs properly even when we have not initialized p? #include void main( ) { const char *p ; p = "A const pointer" ; cout << p ; } Ans: The output of the above program is 'A const pointer'. This is because in this program p is declared as 'const char*' which means that value stored at p will be constant and not p and so the program works properly 7. How do I refer to a name of class or function that is defined within a namespace? Ans: There are two ways in which we can refer to a name of class or function that is defined within a namespace: Using scope resolution operator through the using keyword. This is shown in following example: namespace name1 { class sample1 { // code }; } namespace name2 { class sample2 { // code }; } using namespace name2 ; void main( ) { name1::sample1 s1 ; sample2 s2 ; }

Here, class sample1 is referred using the scope resolution operator. On the other hand we can directly refer to class sample2 because of the statement using namespace name2 ; the using keyword declares all the names in the namespace to be in the current scope. So we can use the names without any qualifiers. -----------------------------------------------------------------------------------------------8. While overloading a binary operator can we provide default values? Ans: No!. This is because even if we provide the default arguments to the parameters of the overloaded operator function we would end up using the binary operator incorrectly. This is explained in the following example: sample operator + ( sample a, sample b = sample (2, 3.5f ) ) { } void main( ) { sample s1, s2, s3 ; s3 = s1 + ; // error } -----------------------------------------------------------------------------------------------9. How do I carry out conversion of one object of user-defined type to another? Ans: To perform conversion from one user-defined type to another we need to provide conversion function. Following program demonstrates how to provide such conversion function. class circle { private : int radius ; public: circle ( int r = 0 ) { radius = r ; } }; class rectangle { private : int length, breadth ; public : rectangle( int l, int b ) { length = l ; breadth = b ;

} operator circle( ) { return circle ( length ) ; } }; void main( ) { rectangle r ( 20, 10 ) ; circle c; c=r; } Here, when the statement c = r ; is executed the compiler searches for an overloaded assignment operator in the class circle which accepts the object of type rectangle. Since there is no such overloaded assignment operator, the conversion operator function that converts the rectangle object to the circle object is searched in the rectangle class. We have provided such a conversion function in the rectangle class. This conversion operator function returns a circle object. By default conversion operators have the name and return type same as the object type to which it converts to. Here the type of the object is circle and hence the name of the operator function as well as the return type is circle. -----------------------------------------------------------------------------------------------10. How do I write code that allows to create only one instance of a class? Ans: This is shown in following code snippet. #include class sample { static sample *ptr ; private: sample( ) { } public: static sample* create( ) { if ( ptr == NULL ) ptr = new sample ; return ptr ; } }; sample *sample::ptr = NULL ; void main( ) { sample *a = sample::create( ) ; sample *b = sample::create( ) ; } Here, the class sample contains a static data member ptr, which is a pointer to the

object of same class. The constructor is private which avoids us from creating objects outside the class. A static member function called create( ) is used to create an object of the class. In this function the condition is checked whether or not ptr is NULL, if it is then an object is created dynamically and its address collected in ptr is returned. If ptr is not NULL, then the same address is returned. Thus, in main( ) on execution of the first statement one object of sample gets created whereas on execution of second statement, b holds the address of the first object. Thus, whatever number of times you call create( ) function, only one object of sample class will be available. 11. How do I write code to add functions, which would work as get and put properties of a class? Ans: This is shown in following code. #include class sample { int data ; public: __declspec ( property ( put = fun1, get = fun2 ) ) int x ; void fun1 ( int i ) { if ( i < 0 ) data = 0 ; else data = i ; } int fun2( ) { return data ; } }; void main( ) { sample a ; a.x = -99 ; cout << a.x ; } Here, the function fun1( ) of class sample is used to set the given integer value into data, whereas fun2( ) returns the current value of data. To set these functions as properties of a class we have given the statement as shown below: __declspec ( property ( put = fun1, get = fun2 )) int x ; As a result, the statement a.x = -99 ; would cause fun1( ) to get called to set the value in data. On the other hand, the last statement would cause fun2( ) to get called to return the value of data.

-----------------------------------------------------------------------------------------------12. How do I write code to make an object work like a 2-D array? Ans: Take a look at the following program. #include class emp { public : int a[3][3] ; emp( ) { int c = 1 ; for ( int i = 0 ; i <= 2 ; i++ ) { for ( int j = 0 ; j <= 2 ; j++ ) { a[i][j] = c ; c++ ; } } } int* operator[] ( int i ) { return a[i] ; } }; void main( ) { emp e ; cout << e[0][1] ; } The class emp has an overloaded operator [ ] function. It takes one argument an integer representing an array index and returns an int pointer. The statement cout << e[0][1] ; would get converted into a call to the overloaded [ ] function as e.operator[ ] ( 0 ). 0 would get collected in i. The function would return a[i] that represents the base address of the zeroeth row. Next the statement would get expanded as base address of zeroeth row[1] that can be further expanded as *( base address + 1 ). This gives us a value in zeroth row and first column. 13. What are formatting flags in ios class? Ans: The ios class contains formatting flags that help users to format the stream data. Formatting flags are a set of enum definitions. There are two types of formatting flags: On/Off flags

Flags that work in-group The On/Off flags are turned on using the setf( ) function and are turned off using the unsetf( ) function. To set the On/Off flags, the one argument setf( ) function is used. The flags working in groups are set through the two-argument setf( ) function. For example, to left justify a string we can set the flag as, cout.setf ( ios::left ) ; cout << "KICIT Nagpur" ; To remove the left justification for subsequent output we can say, cout.unsetf ( ios::left ) ; The flags that can be set/unset include skipws, showbase, showpoint, uppercase, showpos, unitbuf and stdio. The flags that work in a group can have only one of these flags set at a time. -----------------------------------------------------------------------------------------------14. What is the purpose of ios::basefield in the following statement? cout.setf ( ios::hex, ios::basefield ) ; Ans: This is an example of formatting flags that work in a group. There is a flag for each numbering system (base) like decimal, octal and hexadecimal. Collectively, these flags are referred to as basefield and are specified by ios::basefield flag. We can have only one of these flags on at a time. If we set the hex flag as setf ( ios::hex ) then we will set the hex bit but we won't clear the dec bit resulting in undefined behavior. The solution is to call setf( ) as setf ( ios::hex, ios::basefield ). This call first clears all the bits and then sets the hex bit. -----------------------------------------------------------------------------------------------15. Can we get the value of ios format flags? Ans: Yes! The ios::flags( ) member function gives the value format flags. This function takes no arguments and returns a long ( typedefed to fmtflags) that contains the current format flags. -----------------------------------------------------------------------------------------------16. Is there any function that can skip certain number of characters present in the input stream? Ans: Yes! This can be done using cin::ignore( ) function. The prototype of this function is as shown below: istream& ignore ( int n = 1, int d =EOF ) ; Sometimes it happens that some extra characters are left in the input stream while taking the input such as, the '\n' (Enter) character. This extra character is then passed to the next input and may pose problem. To get rid of such extra characters the cin::ignore( ) function is used. This is

equivalent to fflush ( stdin ) used in C language. This function ignores the first n characters (if present) in the input stream, stops if delimiter d is encountered. -----------------------------------------------------------------------------------------------17. Write a program that implements a date class containing day, month and year as data members. Implement assignment operator and copy constructor in this class. Ans: This is shown in following program: #include class date { private : int day ; int month ; int year ; public : date ( int d = 0, int m = 0, int y = 0 ) { day = d ; month = m ; year = y ; } // copy constructor date ( date &d ) { day = d.day ; month = d.month ; year = d.year ; } // an overloaded assignment operator date operator = ( date d ) { day = d.day ; month = d.month ; year = d.year ; return d ; } void display( ) { cout << day << "/" << month << "/" << year ; } }; void main( ) { date d1 ( 25, 9, 1979 ) ;

date d2 = d1 ; date d3 ; d3 = d2 ; d3.display( ) ; } 18. When should I use unitbuf flag? Ans: The unit buffering (unitbuf) flag should be turned on when we want to ensure that each character is output as soon as it is inserted into an output stream. The same can be done using unbuffered output but unit buffering provides a better performance than the unbuffered output. -----------------------------------------------------------------------------------------------19. What are manipulators? Ans: Manipulators are the instructions to the output stream to modify the output in various ways. The manipulators provide a clean and easy way for formatted output in comparison to the formatting flags of the ios class. When manipulators are used, the formatting instructions are inserted directly into the stream. Manipulators are of two types, those that take an argument and those that don't. -----------------------------------------------------------------------------------------------20. What is the difference between the manipulator and setf( ) function? Ans: The difference between the manipulator and setf( ) function are as follows: The setf( ) function is used to set the flags of the ios but manipulators directly insert the formatting instructions into the stream. We can create user-defined manipulators but setf( ) function uses data members of ios class only. The flags put on through the setf( ) function can be put off through unsetf( ) function. Such flexibility is not available with manipulators. -----------------------------------------------------------------------------------------------21. How do I get the current position of the file pointer? Ans: We can get the current position of the file pointer by using the tellp( ) member function of ostream class or tellg( ) member function of istream class. These functions return (in bytes) positions of put pointer and get pointer respectively. -----------------------------------------------------------------------------------------------22. What are put and get pointers? Ans: These are the long integers associated with the streams. The value present in the put pointer specifies the byte number in the file from where next write would take place in the file. The get pointer specifies

the byte number in the file from where the next reading should take place. -----------------------------------------------------------------------------------------------23. What do the nocreate and noreplace flag ensure when they are used for opening a file? Ans: nocreate and noreplace are file-opening modes. A bit in the ios class defines these modes. The flag nocreate ensures that the file must exist before opening it. On the other hand the flag noreplace ensures that while opening a file for output it does not get overwritten with new one unless ate or app is set. When the app flag is set then whatever we write gets appended to the existing file. When ate flag is set we can start reading or writing at the end of existing file. -----------------------------------------------------------------------------------------------24. What is the limitation of cin while taking input for character array? Ans: To understand this consider following statements, char str[5] ; cin >> str ; While entering the value for str if we enter more than 5 characters then there is no provision in cin to check the array bounds. If the array overflows, it may be dangerous. This can be avoided by using get( ) function. For example, consider following statement, cin.get ( str, 5 ) ; On executing this statement if we enter more than 5 characters, then get( ) takes only first five characters and ignores rest of the characters. Some more variations of get( ) are available, such as shown below: get ( ch ) - Extracts one character only get ( str, n ) - Extracts up to n characters into str get ( str, DELIM ) - Extracts characters into array str until specified delimiter (such as '\n'). Leaves delimiting character in stream. get ( str, n, DELIM ) - Extracts characters into array str until n characters or DELIM character, leaving delimiting character in stream. -----------------------------------------------------------------------------------------------25. What is the purpose of istream class? Ans: The istream class performs activities specific to input. It is derived from the ios class. The most commonly used member function of this class is the overloaded >> operator which can extract values of all basic types. We can extract even a string using this operator.

-----------------------------------------------------------------------------------------------26. Would the following code work? #include void main( ) { ostream o ; o << "Dream. Then make it happen!" ; } Ans: No! This is because we cannot create an object of the ostream class since its constructor and copy constructor are declared private. 27. Can we use this pointer inside static member function? Ans: No! The this pointer cannot be used inside a static member function. This is because a static member function is never called through an object. -----------------------------------------------------------------------------------------------28. What is strstream? Ans: strstream is a type of input/output stream that works with the memory. It allows using section of the memory as a stream object. These streams provide the classes that can be used for storing the stream of bytes into memory. For example, we can store integers, floats and strings as a stream of bytes. There are several classes that implement this in-memory formatting. The class ostrstream derived from ostream is used when output is to be sent to memory, the class istrstream derived from istream is used when input is taken from memory and strstream class derived from iostream is used for memory objects that do both input and output. -----------------------------------------------------------------------------------------------29. Ans: When we want to retrieve the streams of bytes from memory we can use istrestream. The following example shows the use of istrstream class. #include void main( ) { int age ; float salary ; char name[50] ; char str[] = "22 12004.50 K. Vishwanatth" ; istrstream s ( str ) ;

s >> age >> salary >> name ; cout << age << endl << salary << endl << name ; cout << endl << s.rdbuf( ) ; } Here, s is the object of the class istrstream. When we are creating the object s, the constructor of istrstream gets called that receives a pointer to the zero terminated character array str. The statement s >> age >> salary >> name ; extracts the age, salary and the name from the istrstream object s. However, while extracting the name, only the first word of name gets extracted. The balance is extracted using rdbuf( ). -----------------------------------------------------------------------------------------------30. When the constructor of a base class calls a virtual function, why doesn't the override function of the derived class gets called? Ans: While building an object of a derived class first the constructor of the base class and then the constructor of the derived class gets called. The object is said an immature object at the stage when the constructor of base class is called. This object will be called a matured object after the execution of the constructor of the derived class. Thus, if we call a virtual function when an object is still immature, obviously, the virtual function of the base class would get called. This is illustrated in the following example. #include class base { protected : int i ; public : base ( int ii = 0 ) { i = ii ; show( ) ; } virtual void show( ) { cout << "base's show( )" << endl ; } }; class derived : public base { private : int j ; public : derived ( int ii, int jj = 0 ) : base ( ii ) {

j = jj ; show( ) ; } void show( ) { cout << "derived's show( )" << endl ; } }; void main( ) { derived dobj ( 20, 5 ) ; } The output of this program would be: base's show( ) derived's show( ) 31. Can I have a reference as a data member of a class? If yes, then how do I initialise it? Ans: Yes, we can have a reference as a data member of a class. A reference as a data member of a class is initialised in the initialisation list of the constructor. This is shown in following program. #include class sample { private : int& i ; public : sample ( int& ii ) : i ( ii ) { } void show( ) { cout << i << endl ; } }; void main( ) { int j = 10 ; sample s ( j ) ; s.show( ) ; } Here, i refers to a variable j allocated on the stack. A point to note here is that we cannot bind a reference to an object passed to the constructor as a value. If we do so, then the reference i would refer to the function parameter (i.e. parameter ii in the constructor), which would disappear as soon as the function returns, thereby creating a situation of dangling reference. -----------------------------------------------------------------------------------------------

-32. Why does the following code fail? #include class sample { private : char *str ; public : sample ( char *s ) { strcpy ( str, s ) ; } ~sample( ) { delete str ; } }; void main( ) { sample s1 ( "abc" ) ; } Ans: Here, through the destructor we are trying to deal locate memory, which has been allocated statically. To remove an exception, add following statement to the constructor. sample ( char *s ) { str = new char[strlen(s) + 1] ; strcpy ( str, s ) ; } Here, first we have allocated memory of required size, which then would get deal located through the destructor. -----------------------------------------------------------------------------------------------33. assert( ) macro... We can use a macro called assert( ) to test for conditions that should not occur in a code. This macro expands to an if statement. If test evaluates to 0, assert prints an error message and calls abort to abort the program. #include #include void main( ) { int i ; cout << "\nEnter an integer: " ;

cin >> i ; assert ( i >= 0 ) ; cout << i << endl ; } 34. Why it is unsafe to deal locate the memory using free( ) if it has been allocated using new? Ans: This can be explained with the following example: #include class sample { int *p ; public : sample( ) { p = new int ; } ~sample( ) { delete p ; } }; void main( ) { sample *s1 = new sample ; free ( s1 ) ; sample *s2 = ( sample * ) malloc ( sizeof ( sample )); delete s2 ; } The new operator allocates memory and calls the constructor. In the constructor we have allocated memory on heap, which is pointed to by p. If we release the object using the free( ) function the object would die but the memory allocated in the constructor would leak. This is because free( ) being a C library function does not call the destructor where we have deal located the memory. As against this, if we allocate memory by calling malloc( ) the constructor would not get called. Hence p holds a garbage address. Now if the memory is deal located using delete, the destructor would get called where we have tried to release the memory pointed to by p. Since p contains garbage this may result in a runtime error. ------------------------------------------------------------------------------------------------

35.

Can we distribute function templates and class templates in object libraries? Ans: No! We can compile a function template or a class template into object code (.obj file). The code that contains a call to the function template or the code that creates an object from a class template can get compiled. This is because the compiler merely checks whether the call matches the declaration (in case of function template) and whether the object definition matches class declaration (in case of class template). Since the function template and the class template definitions are not found, the compiler leaves it to the linker to restore this. However, during linking, linker doesn't find the matching definitions for the function call or a matching definition for object creation. In short the expanded versions of templates are not found in the object library. Hence the linker reports error. -----------------------------------------------------------------------------------------------36. What is the difference between an inspector and a mutator ? Ans: An inspector is a member function that returns information about an object's state (information stored in object's data members) without changing the object's state. A mutator is a member function that changes the state of an object. In the class Stack given below we have defined a mutator and an inspector. class Stack { public : int pop( ) ; int getcount( ) ; } In the above example, the function pop( ) removes top element of stack thereby changing the state of an object. So, the function pop( ) is a mutator. The function getcount( ) is an inspector because it simply counts the number of elements in the stack without changing the stack. 37. Namespaces: The C++ language provides a single global namespace. This can cause problems with global name clashes. For instance, consider these two C++ header files: // file1.h float f ( float, int ) ; class sample { ... } ; // file2.h class sample { ... } ; With these definitions, it is impossible to use both header files in a single program; the sample classes will clash.A namespace is a declarative region that attaches an additional identifier to any names declared inside it. The additional identifier thus avoids the possibility that a name will conflict with names declared elsewhere in the

program. It is possible to use the same name in separate namespaces without conflict even if the names appear in the same translation unit. As long as they appear in separate namespaces, each name will be unique because of the addition of the namespace identifier. For example: // file1.h namespace file1 { float f ( float, int ) ; class sample { ... } ; } // file2.h namespace file2 { class sample { ... } ; } Now the class names will not clash because they become file1::sample and file2::sample, respectively. -----------------------------------------------------------------------------------------------38. What would be the output of the following program? #include class user { int i ; float f ; char c ; public : void displaydata( ) { cout << endl << i << endl << f << endl << c ; } }; void main( ) { cout << sizeof ( user ) ; user u1 ; cout << endl << sizeof ( u1 ) ; u1.displaydata( ) ; } Ans: The output of this program would be, 9 or 7 9 or 7 Garbage Garbage Garbage

Since the user class contains three elements, int, float and char its size would be 9 bytes (int-4, float-4, char-1) under Windows and 7 bytes (int-2, float-4, char-1) under DOS. Second output is again the same because u1 is an object of the class user. Finally three garbage values are printed out because i, f and c are not initialized anywhere in the program. Note that if you run this program you may not get the answer shown here. This is because packing is done for an object in memory to increase the access efficiency. For example, under DOS, the object would be aligned on a 2-byte boundary. As a result, the size of the object would be reported as 6 bytes. Unlike this, Windows being a 32-bit OS the object would be aligned on a 4-byte boundary. Hence the size of the object would be reported as 12 bytes. To force the alignment on a 1-byte boundary, write the following statement before the class declaration. #pragma pack ( 1 ) -----------------------------------------------------------------------------------------------39. Write a program that will convert an integer pointer to an integer and vice-versa. Ans: The following program demonstrates this. #include void main( ) { int i = 65000 ; int *iptr = reinterpret_cast ( i ) ; cout << endl << iptr ; iptr++ ; cout << endl << iptr ; i = reinterpret_cast ( iptr ) ; cout << endl << i ; i++ ; cout << endl << i ; } 40. What is a const_cast? Ans. The const_cast is used to convert a const to a non-const. This is shown in the following program: #include void main( ) { const int a = 0 ; int *ptr = ( int * ) &a ; //one way ptr = const_cast_ ( &a ) ; //better way }

Here, the address of the const variable a is assigned to the pointer to a non-const variable. The const_cast is also used when we want to change the data members of a class inside the const member functions. The following code snippet shows this: class sample { private: int data; public: void func( ) const { (const_cast (this))->data = 70 ; } }; -----------------------------------------------------------------------------------------------41. What is forward referencing and when should it be used? Ans: Forward referencing is generally required when we make a class or a function as a friend. Consider following program: class test { public: friend void fun ( sample, test ) ; }; class sample { public: friend void fun ( sample, test ) ; }; void fun ( sample s, test t ) { // code } void main( ) { sample s ; test t ; fun ( s, t ) ; } On compiling this program it gives error on the following statement of test class. It gives an error that sample is undeclared identifier. friend void fun ( sample, test ) ; This is so because the class sample is defined below the class test and we are using it before its definition. To overcome this error we need to give forward reference of the class sample before the definition of class test. The following statement is the forward reference of class sample. class sample ; -----------------------------------------------------------------------------------------------42.

How would you give an alternate name to a namespace? Ans: An alternate name given to namespace is called a namespace-alias. namespace-alias is generally used to save the typing effort when the names of namespaces are very long or complex. The following syntax is used to give an alias to a namespace. namespace myname = my_old_very_long_name ; -----------------------------------------------------------------------------------------------43. Using a smart pointer can we iterate through a container? Ans: Yes. A container is a collection of elements or objects. It helps to properly organize and store the data. Stacks, linked lists, arrays are examples of containers. Following program shows how to iterate through a container using a smart pointer. #include class smartpointer { private : int *p ; // ordinary pointer public : smartpointer ( int n ) { p = new int [ n ] ; int *t = p ; for ( int i = 0 ; i <= 9 ; i++ ) *t++ = i * i ; } int* operator ++ ( int ) { return p++ ; } int operator * ( ) { return *p ; } }; void main( ) { smartpointer sp ( 10 ) ; for ( int i = 0 ; i <= 9 ; i++ ) cout << *sp++ << endl ; } Here, sp is a smart pointer. When we say *sp, the operator * ( ) function gets called. It returns the integer being pointed to by p. When we say sp++ the operator ++ ( ) function gets called. It increments p to point to the next element in the array and then returns the address of this new location.

44. Can objects read and write themselves? Ans: Yes! This can be explained with the help of following example: #include #include class employee { private : char name [ 20 ] ; int age ; float salary ; public : void getdata( ) { cout << "Enter name, age and salary of employee : " ; cin >> name >> age >> salary ; } void store( ) { ofstream file ; file.open ( "EMPLOYEE.DAT", ios::app | ios::binary ) ; file.write ( ( char * ) this, sizeof ( *this ) ) ; file.close( ) ; } void retrieve ( int n ) { ifstream file ; file.open ( "EMPLOYEE.DAT", ios::binary ) ; file.seekg ( n * sizeof ( employee ) ) ; file.read ( ( char * ) this, sizeof ( *this ) ) ; file.close( ) ; } void show( ) { cout << "Name : " << name << endl << "Age : " << age << endl << "Salary :" << salary << endl ; } }; void main( ) { employee e [ 5 ] ; for ( int i = 0 ; i <= 4 ; i++ ) { e [ i ].getdata( ) ;

e [ i ].store( ) ; } for ( i = 0 ; i <= 4 ; i++ ) { e [ i ].retrieve ( i ) ; e [ i ].show( ) ; } } Here, employee is the class whose objects can write and read themselves. The getdata( ) function has been used to get the data of employee and store it in the data members name, age and salary. The store( ) function is used to write an object to the file. In this function a file has been opened in append mode and each time data of current object has been stored after the last record (if any) in the file.Function retrieve( ) is used to get the data of a particular employee from the file. This retrieved data has been stored in the data members name, age and salary. Here this has been used to store data since it contains the address of the current object. The function show( ) has been used to display the data of employee. -----------------------------------------------------------------------------------------------45. Why is it necessary to use a reference in the argument to the copy constructor? Ans : If we pass the copy constructor the argument by value, its copy would get constructed using the copy constructor. This means the copy constructor would call itself to make this copy. This process would go on and on until the compiler runs out of memory. This can be explained with the help of following example: class sample { int i ; public : sample ( sample p ) { i = p.i ; } }; void main( ) { sample s ; sample s1 ( s ) ; } While executing the statement sample s1 ( s ), the copy constructor would get called. As the copy construct here accepts a value, the value of s would be passed which would get collected in p. We can think of this statement as sample p = s. Here p is getting created and initialized. Means again the copy constructor would get called. This would result into recursive calls. Hence we must use a reference as an argument in a copy constructor. 46. Virtual Multiple Inheritance: A class b is defined having member variable i. Suppose two classes d1 and d2 are derived from class b and a class multiple is derived from both d1 and d2. If variable i

is accessed from a member function of multiple then it gives error as 'member is ambiguous'. To avoid this error derive classes d1 and d2 with modifier virtual as shown in the following program. #include class b { public : int i ; public : fun( ) { i=0; } }; class d1 : virtual public b { public : fun( ) { i=1; } }; class d2 : virtual public b { public : fun( ) { i=2; } }; class multiple : public d1, public d2 { public : fun( ) { i = 10 ; } }; void main( ) { multiple d ; d.fun( ) ; cout << d.i ; } -----------------------------------------------------------------------------------------------47. Can we use this pointer in a class specific, operator-overloading function for new operator? Ans: No! The this pointer is never passed to the overloaded operator new() member function because this function gets called before the object is created. Hence there is

no question of the this pointer getting passed to operator new( ). -----------------------------------------------------------------------------------------------48. Can we allocate memory dynamically for a reference? Ans: No! It is not possible to allocate memory dynamically for a reference. This is because, when we create a reference, it gets tied with some variable of its type. Now, if we try to allocate memory dynamically for a reference, it is not possible to mention that to which variable the reference would get tied. 49. When should I overload new operator on a global basis or a class basis? Ans: We overload operator new in our program, when we want to initialize a data item or a class object at the same place where it has been allocated memory. The following example shows how to overload new operator on global basis. #include #include void * operator new ( size_t s ) { void *q = malloc ( s ) ; return q ; } void main( ) { int *p = new int ; *p = 25 ; cout << *p ; } When the operator new is overloaded on global basis it becomes impossible to initialize the data members of a class as different classes may have different types of data members. The following example shows how to overload new operator on class-by-class basis. #include #include class sample { int i ; public : void* operator new ( size_t s, int ii ) { sample *q = ( sample * ) malloc ( s ) ; q -> i = ii ; return q ; } };

class sample1 { float f ; public : void* operator new ( size_t s, float ff ) { sample1 *q = ( sample1 * ) malloc ( s ) ; q -> f = ff ; return q ; } }; void main( ) { sample *s = new ( 7 ) sample ; sample1 *s1 = new ( 5.6f ) sample1 ; } Overloading the operator new on class-by-class basis makes it possible to allocate memory for an object and initialize its data members at the same place. -----------------------------------------------------------------------------------------------50. How would you define a pointer to a data member of the type pointer to pointer? Ans: The following program demonstrates this... #include class sample { public : sample ( int **pp ) { p = pp ; } int **p ; }; int **sample::*ptr = &sample::p ; void main( ) { int i = 9 ; int *pi = &i ; sample s ( &pi ) ; cout << ** ( s.*ptr ) ; } Here, ptr is the pointer to data member p of class sample, which in turn is a pointer pointing to an int. -----------------------------------------------------------------------------------------------51. How do I write a code to catch multiple types of exceptions in one single catch block? Ans: The following program demonstrates the use of a single catch block to catch

multiple exceptions. #include class test { }; class sample { public : void fun1( ) { throw 99 ; } void fun2( ) { throw 3.14f ; } void fun3( ) { throw "error" ; } void fun4( ) { throw test( ) ; } }; void main( ) { try { sample s ; s.fun4( ) ; s.fun1( ) ; s.fun2( ) ; s.fun3( ) ; } catch ( ... ) { cout << "strange" ; } } Here, different types of exceptions are thrown by the member functions of the class sample. While catching the exception instead of four different catch blocks we can as well define one single catch block. Note the syntax for defining the catch block, where we have used three dots () in the formal parameter list. This indicates that any thrown exception should get caught in the same catch block. When the exception is thrown from the fun4( ) control reaches the catch block, ignoring the rest of the calls.

52. Can we return an error value from the constructor of a class? Ans: No. We cannot return any error value from the constructor, as the constructor doesn't have any return type. However, by throwing an exception we can pass value to catch block. This is shown in the following example: #include class sample { public : sample ( int i ) { if ( i == 0 ) throw "error" ; } }; void main( ) { try { sample s ( 0 ) ; } catch ( char * str ) { cout << str ; } } In this program, the statement throw "error" ; would throw an exception when an object s of the class sample would get created. The catch block would collect the string error. -----------------------------------------------------------------------------------------------53. How do I define the member function of a template class, which has to be defined outside the template class. The function receives an object of its own class as a parameter and returns the value of the same type. Ans: The following example shows how we can define such a function. sample sample::fun ( sample s ) { // code } Here, the first sample indicates the return type of the function and the next sample is used for the scope of function. -----------------------------------------------------------------------------------------------54. How name mangling can be prevented?

Ans: To avoid name mangling the function should be declared with an extern "C" attribute. Functions declared as extern "C" are treated as C-style functions. Hence the compiler does not mangle them. The following code snippet shows how to declare such a function. #include extern "C" void display( ) { cout << "See the effect of C in C++ " ; } void main( ) { display( ) ; } -----------------------------------------------------------------------------------------------55. Can we allocate memory dynamically for a reference? Ans: No, it is not possible to allocate memory dynamically for a reference. A reference is initialized at the time of creation. Trying to allocate memory dynamically for a reference creates a problem in initializing it. Thus, the compiler does not allow us to dynamically allocate the memory for references. -----------------------------------------------------------------------------------------------56. What is RTTI? Ans: RTTI stands for 'Run Time Type Information'. We use virtual function mechanism where we can call derived class's member functions using base class's pointer. However, many times we wish to know the exact type of the object. We can know the type of the object using RTTI. A function that returns the type of the object is known as RTTI functions. C++ supports two ways to obtain information about the object's class at run time, they are typeid( ) operator and dynamic_cast operator. 57. What is Data Conversion? Ans: Assignments between types whether they are basic or user-defined, are handled by the compiler. If the variables are of different basic types compiler calls a special routine to convert the value. But if we want to convert between user-defined data type and basic types we have to write conversion routine ourselves. A conversion routine to convert user-defined data type string to integer is shown below: class string { private : char str[20] ; public : string( ) { }

string ( char *s ) { strcpy ( str, s ) ; } operator int( ) { return 123 ; // Write logic to convert string to integer } }; main( ) { string s2 = "123" ; int i1 = int ( s2 ) ; cout << endl << i1 ; } ------------------------------------------------------------------------------------------------

58. How to obtain type information using typeid( ) operator? Ans: typeid( ) operator takes an object, a reference or a pointer and returns its type. Following program shows how to use the typeid( ) operator. #include #include class Base { public : virtual void show( ) { } }; class Der1 : public Base { }; void main( ) { Base *b1 ; cout << endl << typeid ( b1 ).name( ) ; Der1 d1 ; b1 = &d1 ; cout << endl << typeid ( *b1 ).name( ) ; cout << endl << typeid ( 12 ).name( ) << endl << typeid ( 12.5 ).name( ) ; }

The output of this program will be Base* Der1 int double RTTI operators must be used for polymorphic class (class having virtual function) only. For non-polymorphic class static type information is returned. -----------------------------------------------------------------------------------------------59. How to use RTTI with class templates? Ans: Templates can generate different classes. We may wish to get the type of class, which we are working in. The following program shows how to use RTTI operator typeid( ) with class template. #include #include template class base { public : base( ) { cout << typeid ( *this ).name( ) << "Constructor" << endl ; } T add ( T a, T b ) { return a + b ; } ~base( ) { cout << typeid ( *this ).name( ) << "Destructor" << endl ; } }; void main( ) { base b1 ; cout << b1.add ( 10, 20 ) << endl ; base b2 ; cout << b2.add ( 5.5, 10.5 ) << endl ; } 60. We can use following C++ operators for typecasting.static_cast is used for castless

conversions, narrowing conversions, conversion from void* and implicit type conversions. const_cast is used to convert a const to a non-const. reinterpret_cast is used to assign one kind of pointer to another. -----------------------------------------------------------------------------------------------61. What will be the output of the following program? #include class A { public : A( ) { cout << "Reached in Constructor\n" ; } }; void main( ) { A a( ) ; Ab; } Output : Reached in Constructor Constructor gets called only once when the object b is created. When the statement A a( ) ; gets executed constructor does not get called. This is because compiler takes this statement as a prototype declaration of function a( ) that returns an object of class A. However, if we pass arguments like A a ( 10 ) ; Compiler would search for one argument constructor and if not found would flash an error. -----------------------------------------------------------------------------------------------62. What is a container? Ans: A container is an object that holds other objects. Various collection classes like List, Hash Table, AbstractArray, etc. are the examples of containers. We can use the classes to hold objects of any derived classes. The containers provide various methods using which we can get the number of objects stored in the container and iterate through the objects stored in it. -----------------------------------------------------------------------------------------------63. Function template overloading One can declare several function templates with the same name and even declare a combination of function templates and ordinary functions with the same name. When an overloaded function is called, overload resolution is necessary to find the right

function or template function to invoke. For example: template < class T > T sqrt ( T ) ; template < class T > complex < T > sqrt ( complex < T > ) ;double sqrt ( double ) ; void f ( complex < double > z ) { sqrt ( 2 ) ; // sqrt < int > ( int ) sqrt ( 2.0 ) ; // sqrt ( double ) sqrt ( z ) ; // sqrt < complex < double > ( complex < double > ) } In the same way that a template function is a generalization of the notion of a function, the rules for resolution in the presence of function templates are generalizations of the function overload resolution rules. Basically, for each template we find the specialization that is best for the set of function arguments. Then we apply the usual function overload resolution rules to these specializations and all ordinary functions. 64. Exception Handling in C++ In C++ we can handle run-time errors generated by c++ classes by using three new keywords: throw, catch, and try. We also have to create an exception class. If during the course of execution of a member function of this class a run-time error occurs, then this member function informs the application that an error has occurred. This process of informing is called 'throwing' an exception. The following code shows how to deal with exception handling. class sample { public : class errorclass { }; void fun( ) { if ( some error occurs ) throw errorclass( ) // throws exception } }; //application void main( ) { try { sample s ; s.fun( ) ; } catch ( sample::errorclass ) { // do something about the error } }

-----------------------------------------------------------------------------------------------65. Consider the following code: #include class base { public : int data ; }; class d1 : public base { }; class d2 : public base { }; class der : public d1, public d2 { public : void showdata( ) { cout << data ; } }; void main( ) { der d ; d.showdata( ) ; } If you run this program it is bound to give you errors. This is because of the rules of inheritance: 1. Each base class not specified virtual will have its own sub-object representing it. In the above program, if we create object of d1 it will have a sub-object of class base containing a data member data. If we create an object of class der it will have subobjects of classes d1 and d2 and both the sub-objects will refer to a separate copy of data. Hence, to access data from class der we will have to mention the class name. For example, d1::data or d2::data. 2. If we want that only one sub-object should exist we must use the concept of virtual base class. The single object of this will represent every base class of given name that is specified to be virtual class. After making d1 and d2 as virtual base class if we create an object of der only one sub-object would exist and so accessing data would no longer give us errors. -----------------------------------------------------------------------------------------------66.

How to declare a pointer to a member function? Ans: Suppose, I wish to declare a pointer to a member function that receives an int and returns an int. I will have to declare it as int (A::* ) ( int ). Following is an example. #include class A { public : int fun ( int f ) { cout << "in fun\n" ; return f * f ; } }; typedef int ( A:: *pfun ) ( int ) ; void main( ) { pfun p = A::fun ; Aa; int s = ( a.*p ) ( 6 ) ; cout << s ; } 67. What is the disadvantage of a template function? Ans: A template function cannot be distributed in the obj form. This is because, with which parameters the template function is going to be called is decided at the run time only. Therefore an obj form of a template function cannot be made by merely compiling it. -----------------------------------------------------------------------------------------------68. How to declare a pointer to the data members of a class? Ans: Following program shows how to declare a pointer to non-function members of a class. #include class A { public : int a ;

void print( ) { cout << a ; } }; void main( ) { int A::*pa = &A::a ; A obj ; obj.*pa = 20 ; obj.print( ) ; } Here, we have initialised the data member a using the pointer pa. -----------------------------------------------------------------------------------------------69. How to allocate memory for a multidimensional array dynamically? Ans: Many times we need to allocate memory for a multidimensional array dynamically. Because of complexity of pointers many find this difficult. Following program allocates memory for a 3 x 3 array dynamically, copies contents of a 3 x 3 array in it and prints the contents using the pointer. #include #include int a[ ][3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; void main( ) { int **p ; p = new int *[3] ; for ( int i = 0 ; i < 3 ; i++ ) p[i] = new int[3] ; for ( i = 0 ; i < 3 ; i++ ) for ( int j = 0 ; j < 3 ; j++ ) p[i][j] = a[i][j] ; for ( { for ( cout cout i = 0 ; i < 3 ; i++ ) j = 0 ; j < 3 ; j++ ) << p[i][j] ; << "\n" ;

} } 70. When should we use the :: ( scope resolution ) operator to invoke the virtual functions? Ans: Generally, :: operator is used to call a virtual function from constructor or destructor. This is because, if we call a virtual function from base class constructor or destructor the virtual function of the base class would get called even if the object being constructed or destroyed would be the object of the derived class. Thus, whenever we want to bypass the dynamic binding mechanism we must use the :: operator to call a virtual function. -----------------------------------------------------------------------------------------------71. How do I use operators .* and ->* in a program? Ans: The following code snippet demonstrates the use of .* and ->* operators. #include class sample { public : int i ; void fun( ) { cout << "fun" << endl ; } }; void ( sample::*pf )( ) = &sample::fun ; int sample::*pdm = &sample::i ; void main( ) { sample s ; sample *p = new sample ; ( s .* pf )( ) ; ( p ->* pf )( ) ; s .* pdm = 1 ; p ->* pdm = 2 ; cout << s .* pdm << endl ; cout << p ->* pdm << endl ; } In the above program pf is a pointer to a function fun( ) of class sample, and pdm is a pointer to a data member i of the same class sample. The object s of the class

sample is created statically. Next, p is a pointer to an object created dynamically. The using the operator .* and ->* the member functions are called and also the public data member is accessed. -----------------------------------------------------------------------------------------------72. What happens when we add an int value to a user defined type of object? Ans: Whenever an int value is added to an object of user defined type, the object would search for an overloaded operator int( ). This operator must be defined in such a way that it always returns an int value. However, we need not specify the return type as on doing so the compiler flashes an error. #include class sample { int i ; public : sample ( ) { i = 10 ; } operator int( ) { return this -> i ; } }; void main( ) { sample s ; int i ; i = s + 10 ; cout << i ; } In the above program on adding 10 to an object s, the value of i would become 20. 73. Can we have a reference to an array? Ans: Yes, we can have a reference to an array. int a[ ] = { 8, 2, 12, 9 } ; int ( &r ) [ 4 ] = a ; // reference to an array Here, r is a reference to an array of four elements. We can even print the elements of array with the help of reference. This is shown in the following code segment: for ( int i = 0 ; i < 4 ; i++ ) cout << r [i] << endl ; -----------------------------------------------------------------------------------------------74.

When friend function becomes indispensable... Ans: Consider the following program. #include class distance { private : int feet ; public : distance( ) { feet = 0 ; } distance ( int f ) { feet = f ; } distance operator + ( distance x ) { int f = feet + x.feet ; return distance ( f ) ; } }; void main( ) { distance d1 ( 20 ), d2, d3 ; d2 = d1 + 10 ; d3 = 10 + d2 ; } If you run this program it is bound to give errors. The error lies in the statement d3 = 10 + d2 ; We may think that since we have overloaded + operator this statement would add 10 to d2. But this does not happen. This is because the specified statement will get converted as d3 = 10.operator+ ( d2 ) ; This means that this statement should call the operator+( ) function that takes an object of distance class as parameter written in the float class, which is not possible. The solution is to write operator+( ) as a 'friend' function. Declare operator+ function in distance class as given below: friend distance operator + ( distance x1, distance x2 ) ; and define it outside the class as shown below: distance operator + ( distance x1, distance x2 ) { int f = x1.feet + x2.feet ; return distance ( f ) ; } When compiler would see that the 'friend' operator+( ) function is available it would convert the statement d3 = 10 + d2 as operator+ (10, d2 ). Now since 10 is passed as a parameter not as a calling object there would be no error. Thus in such cases

'friend' function becomes indispensable. -----------------------------------------------------------------------------------------------75. How to use a memory as a stream? Ans: Suppose, details of an employee such as name, designation, age, etc. are stored in different types of variables. Now, if we wish to concatenate these details in a character array we will have to use various string manipulation functions like strcpy( ) and strcat( ). Instead of using these functions we can use more easy and clean way to gather the details in the char array in the form of streams. We can declare the memory allocated for the array as stream and use the << operator to store variables having different types in this memory. Following program shows how to achieve this. #include void main( ) { char buff [50] ; char str[ ] = "Sanjay" ; char desig[ ] = "Manager" ; char jd[ ] = "27/12/1995" ; int age = 35 ; ostrstream o ( buff, sizeof ( buff ) ) ; o << str << endl << desig << endl << jd << endl << age << ends ; cout << buff ; } As shown in the program we can also use the manipulators and formatting flags. The output of this program will be: Sanjay Manager 27/12/1995 35 -----------------------------------------------------------------------------------------------76. How would you declare and initialize reference to a data member? Ans: Sometimes we may need to declare a data member, which is a reference to another data member of the class as shown below: class A { public : char *p ; char *&rp ; }; We can't initialize a reference to a data member at the time of declaration. It should be initialized using 'member wise initialization as shown below. #include class A {

public : char *p ; char *&rp ; A( ) : rp ( p ) { p = "" ; } A ( char *s ) : rp ( p ) { p=s; } }; void main( ) { A a ( "abcd" ) ; cout << a.rp ; } 77. iostream library has made it easy to read data from various input devices and write data to the output devices. The following program shows how to print a disk file 'data.dat' on the printer using stream classes. Every hardware device has a familiar name given by the operating system. The printer is generally connected to the first parallel port. So, the file name for the printer should be PRN or lpt1. #include void main( ) { ifstream i ( "data.dat" ) ; ofstream o ; o.open ( "PRN" ) ; char ch ; while ( 1 ) { i.get ( ch ) ; if ( i.eof( ) ) break ; o.put ( ch ) ; } o.put ( '\x0C' ) ; } -----------------------------------------------------------------------------------------------78. We know that a destructor is automatically called when an object of a class goes out of scope. There is another case where destructor is called automatically. If an object is created in a try block and an exception is thrown after the object is created, then the destructor is called automatically. -----------------------------------------------------------------------------------------------79.

Can a function call be at the left hand side of the assignment operator? Ans: Yes. Following program shows how it is possible. #include class ref { private : struct data { int a ; char *p ; } d1, d2 ; public : data &set ( ) { return d1 ; } data &get ( ) { cin >> d2.a >> d2.p ; return d2 ; } }; void main( ) { ref r ; r.set( ) = r.get( ) ; r.print( ) ; } In the above program the functions get( ) and set( ) both return a reference to the object of the structure data. We have assigned the reference returned by get( ) to the reference returned by set( ) function. That is, we are assigning d2 to d1. So, the values of d2 would get assigned to d1. You can check this out by printing the values of d1. -----------------------------------------------------------------------------------------------80. If a class contains a virtual function a pointer called VPTR is created. This VPTR becomes a part of every object of that class. The first two bytes (in DOS) are occupied by VPTR. We can prove this by displaying the first two bytes of memory allocated for the objects. Following program shows how this can be achieved. #include class vir { public : virtual void f( ) { } };

void main( ) { vir v, v1 ; int *p1 = ( int* ) &v ; int *p2 = ( int* ) &v1 ; cout << endl << *p1 << " " << *p2 ; } 81. Exception Handling in C++ In C++ we can handle run-time errors generated by c++ classes by using three new keywords: throw, catch, and try. We also have to create an exception class. If during the course of execution of a member function of this class a run-time error occurs, then this member function informs the application that an error has occurred. This process of informing is called 'throwing' an exception. The following code shows how to deal with exception handling. class sample { public : class errorclass { }; void fun( ) { if ( some error occurs ) throw errorclass( ) // throws exception } }; //application void main( ) { try { sample s ; s.fun( ) ; } catch ( sample::errorclass ) { // do something about the error } } -----------------------------------------------------------------------------------------------82. Accessing a private data member from a different Object... Different objects of the same class can access each other's members, even if these members are private. For example: #include < iostream.h >

class sample { float f ; public : sample ( float ff ) { f = ff ; } void fun ( sample* objptr ) { objptr -> n = 0 ; cout << "Value of this objects f is : " << f << endl ; cout << "Value of other objects f" << objptr -> n << endl ; } // another object's private member! }; void main( ) { sample s1 ( 6.5f ) , s2 ( 2.5f ) ; s1.f ( &s2 ) ; // s1 changes s2's n } Typically, this coding style should be avoided. However, you should be aware that private members of an object can be changed by another object of the same type. Therefore, in certain special conditions, this coding style may be useful. -----------------------------------------------------------------------------------------------83. Can you access private data members of a class from out side the class? Ans: Yes. This program shows how. #include class emp private : int i ; public : emp( ) { i = 10 ; } }; void main( ) emp *p = new emp ; int *pi = (int*) p ; cout << *pi ; *pi = 20 ; cout << *pi ; } The pointer to the class is typecasted in an integer pointer. With the help of this pointer private data member 'i' is accessed in main( ). -----------------------------------------------------------------------------------------------84. Why creating array of references is not possible?

Ans: The array name always refers or points to the zeroeth element. If array is of references then the array name would point to the zeroeth element which happens to be a reference. Creating pointer to a reference is not valid. So, creating array of references too is not possible. 85. How do I call a virtual function of a class using a pointer to a function ? Ans : #include class Cvirtual { public : virtual float vfun( ) { cout << "from vfun" << endl ; return 7.03f ; } }; void main( ) { Cvirtual obj ; int **p = ( int ** ) &obj ; float ( *pf1 ) ( ) ; pf1 = ( float ( * ) ( ) ) **p ; float f = ( *pf1 ) ( ) ; cout << "return val = " << f << endl ; } In the above program class Cvirtual consists of a virtual function vfun(). In variable p we have stored the address of an object of class Cvirtual. While doing so, we have type casted the address of obj to int **, because obj holds a hidden data member called vptr, which in turn holds the address of virtual function vfun( ). In pf1, a pointer to a function, we are collecting the address of the virtual function vfun( ). Thus the value returned by vfun( ) would then get collected in f. -----------------------------------------------------------------------------------------------86. Why an overloaded new operator defined in a class is static? Ans: An overloaded new function is by default static even if it is not declared so. This is because non-static member functions can be called through an object only. But when an overloaded new operator function gets called the object doesn't stand created. Since new operator function itself is responsible for creating the object. Hence to be able to call a function without an object, the function must be static. -----------------------------------------------------------------------------------------------87. What is a pure virtual destructor? Ans: Like a pure virtual function we can also have a pure virtual destructor. If a base

class contains a pure virtual destructor it becomes necessary for the derived classes to implement the destructor. An ordinary pure virtual function does not have a body but pure virtual destructor must have a body. This is because all the destructors in the hierarchy of inheritance are always called as a part of destruction. -----------------------------------------------------------------------------------------------88. When we are required to find offset of an element within a structure? or, how do we call the function of an outer class from a function in the inner class? (The inner class is nested in the outer class) Ans: #include class outer { int i ; float f ; public : class inner { public : infunc( ) { outer *pout ; pout = (outer*) this - ( size_t ) &( ( ( outer* ) 0 ) -> in ) ; pout -> outfunc( ) ; } }; inner in ; outfunc( ) { cout << "in outer class's function" ; } }; void main( ) { outer out ; out.in.infunc( ) } In the above example we are calling outer::outfunc( ) from inner::infunc(). To call outfunc( ) we need a pointer to the outer class. To get the pointer we have subtracted offset of the inner class's object (base address of outer class's object - address of inner class's object) from address of inner class's object. 89. void f ( float n, int i = 10 ) ; void f ( float a ) ; void main( ) { f ( 12.6 ) ; } void f ( float n, int i )

{ } void f ( float n ) { } The above program results in an error (ambiguous call) since without the default argument the two functions have arguments that are matching in number, order and type. -----------------------------------------------------------------------------------------------90. Some programs need to exercise precise control over the memory areas where data is placed. For example, suppose we wish to read the contents of the boot sector into a structure. For this the byte arrangement of the structure elements must match the arrangement of various fields in the boot sector of the disk. The #pragma pack directives offer a way to fulfill this requirement. The #pragma pack directive specifies packing alignment for structure and union members. The #pragma takes effect at the first structure or union declaration after the #pragma is seen. Consider the following structure: #pragma pack (1) struct emp { int a ; float s ; char ch ; }; #pragma pack( ) Here, #pragma pack ( 1 ) lets each structure element to begin on a 1-byte boundary. Hence the size of the structure will be 9. (int - 4, float - 4, char - 1). If we use #pragma pack ( 2 ) each structure element can begin on a 2-byte boundary. Hence the size of the structure will be 10. (int - 4, float - 4, char - 2). -----------------------------------------------------------------------------------------------91. How to restrict a friend class's access to the private data members? Ans: If we declare a class as a friend of our class the friend class can access the private data members of our class. However, if we want we can restrict this access to some selective functions of the class. Following program shows how to achieve this: #include class X { public : void print ( class Z &z ) ; }; class Z

{ private : int i ; public : Z ( int ii ) { i = ii ; } friend X::print ( class Z &z ) ; }; void X::print ( Z &z1 ) { cout << z1.i ; } main( ) { Z z ( 10 ) ; Xx; x.print ( 10 ) ; } In the above program only the X::print( ) function can access the private data members of class Z. -----------------------------------------------------------------------------------------------92. What is name mangling? Ans: C++ enables you to assign the same function name to more than one functions but with different parameter types. This feature is called function overloading. But when we give several functions the same name, how does the compiler decide which particular function is to be called? C++ solves this problem by applying a process called name mangling. Name mangling applies a decorated name to the function. The mangled name includes tokens that identify the functions' return type and the types of its arguments. class test { public : void fun ( int a, char b ) ; void fun ( char *c, float y ) ; }; void main( ) { test s1 ; s1.fun ( 65, 'A' ) ; s1.fun ( "Anil", 5.5f ) ; } At the time of resolving the calls to fun( ) function the linker would not be able to find the definition of the overloaded function fun( ) and it would report an error. If you look at these errors you will see the mangled names like,

(?fun@test@@QAEXJJ@Z) and (?fun@test@@QAEXMM@Z). Note that different compilers may use different name mangling schemes. 93. How would you call a C function from C++ code? Ans: Using extern "C". The function prototype must be preceded by extern "C". More than one C can be grouped inside braces as shown below: extern "C" { void f( ) ; void f1( ) ; } // In cfunc.c #include void f( ) { printf ( "in f( )" ) ; } // In func.cpp #include extern "C" void f( ) ; void main( ) { f( ) ; } Ensure that both .c and .cpp files are in the same project.

functions

-----------------------------------------------------------------------------------------------94. How to restrict the number of floating-point digits displayed ? Ans: When we display floating-point values, we can use the setprecision manipulator to specify the desired number of digits to the right of the decimal point. For example, cout << setprecision ( 3 ) << 12.34678 ; This statement would give the output as 12.347. -----------------------------------------------------------------------------------------------95. What is a wild pointer ? Ans: A wild pointer is the one that points to a garbage value. For example, an uninitialized pointer that contains garbage value or a pointer that refers to something that no longer exists. ------------------------------------------------------------------------------------------------

96. How friend function helps to increase the versatility of overloaded operators? Ans: Consider the following statement, s2 = s1 * 2 ; where, s1 and s2 are objects of sample class. This statement would work if the overloaded operator * ( sample s ) or conversion function is provided in the class. Internally this statement would get converted to, s2 = s1.operator * ( 2 ) ; The function materializes because it is called with an object s1. The this pointer of s1 would get passed implicitly. To collect 2 in s, first the compiler would call the oneargument constructor, then it would build a nameless object, which then would get collected in s. However, if we write the above statement as, s2 = 2 * s1 ; then it won't compile. This is because the call now would get treated as, s2 = 2.operator * ( s1 ) ; and 2 is not an object. The friend function helps to get rid of such a situation. This is shown in the following program. #include class sample { private : int i ; public : sample ( int ii = 0 ) { i = ii ; } void showdata( ) { cout << i << endl ; } friend sample operator * ( sample, sample ) ; }; sample operator * ( sample s1, sample s2 ) { sample temp ; temp.i = s1.i * s2.i ; return ( temp ) ; } void main( ) { sample s1 ( 10 ), s2 ; s2 = s1 * 2 ; s2.showdata( ) ;

s1 = 2 * s2 ; s1.showdata( ) ; } Here the operator *( ) function takes two parameters. This is because the operator function is no longer a member function of the class. It is a friend of the class sample. Thus the statement s2 = s1 * 2 ; would not take the form s2.operator * ( 2 ). This example shows that using friend permits the overloaded operators to be more versatile. 97. What is a const_cast? Ans: The const_cast is used to convert a const to a non-const. This is shown in the following program. #include void main( ) { const int a = 0 ; int *ptr = ( int * ) &a ; // one way ptr = const_cast ( &a ) ; // better way } Here, the address of the const variable a is assigned to the pointer to a non-const variable. The const_cast is also used when we want to change the data members of a class inside the const member functions. The following code snippet shows how to do this. class sample { private : int data ; public : void fun( ) const { ( const_cast ( this ) ) -> data = 70 ; } }; -----------------------------------------------------------------------------------------------98. Using a smart pointer we can make an object appear like a pointer. If a class overloads the operator -> then any object of that class can appear like a pointer when the operator -> ( ) is called. The following program illustrates this. #include class test { public :

void fun( ) { cout << "fun of smart pointer" ; } }; class smartpointer { test t ; public : test* operator ->( ) { return &t ; } }; void main( ) { smartpointer sp ; sp -> fun( ) ; } The beauty of overloading operator -> is that even though sp is an object we can make it work like a pointer. The operator -> ( ) returns the address of the object of the type test. Using this address of the test object the function fun( ) of the class test gets called. Thus even though fun( ) is not a member of smartpointer class we can still call it using sp. -----------------------------------------------------------------------------------------------99. Can we apply delete on this pointer inside a member function? Ans : Yes! If the member function of a class is called using a pointer to an object, which is allocated dynamically, the object would get deleted. But if the member function is called using the object, which is allocated statically, then a runtime error would occur. This is because we cannot call delete on statically allocated objects. This is illustrated in the following example. class sample { private : int i ; public : void fun( ) { delete this ; } }; void main( ) { sample *s = new sample ; s -> fun( ) ; // no error

sample s1 ; s1.fun( ) ; // would throw a runtime error } 100. Why can't data members of a class be initialized at the time of declaration as given in the following code? class emp { private : int j = 10 ; }; Ans: Memory for data members of a class is allocated only when object of that class is created. One cannot store data in a memory location, which does not exist at all. Therefore initialization at the time of declaration is not possible. -----------------------------------------------------------------------------------------------101. Why in a copy constructor an object is collected in a reference to object as shown below? #include class emp { public : emp( ) { } emp ( emp& ) { cout << "copy" ; } }; void main( ) { emp e ; emp e1 = e ; } Ans: A copy constructor is called when an object is created and initialised at the same time. It is also called when object is passed to a function. So, If we pass the object to copy constructor copy constructor would get called recursively. Thus it will stuck up in an infinite loop. -----------------------------------------------------------------------------------------------102. What is Early Binding and Dynamic Binding? Ans: The term binding refers to the connection between a function call and the actual code executed as a result of the call. Early Binding: If which function is to be called is known at the compile-time it is known as static or early binding. Dynamic Binding: If which function is to be called is decided at run time it is called as late or dynamic binding. Dynamic binding is so called because the actual function called at run-time

depends on the contents of the pointer. For example, call to virtual functions, call to functions to be linked from dlls use late binding. -----------------------------------------------------------------------------------------------103. When can we use the function ostrstream::freeze( )? Ans: While outputting data to memory in the in-memory formatting we need to create an object of the class ostrstream. The constructor of ostrstream receives the address of the buffer but if we want that the ostrstream object should do its own memory management then we need to create an ostrstream object with no constructor arguments as: ostrstream s ; Now s will do its own memory management. We can stuff as many bytes into it as we want. If it falls short of memory, it will allocate more memory. If it cannot, it may even move the block of memory. When the object goes out of scope, the heap storage is automatically released. This is a more flexible approach if we do not know how much space we are going to need. If we want the physical address of the memory used by s we can obtain it by calling the str( ) member function: char* p = s.str( ) ; Once str( ) has been called then the block of memory allocated by ostrstream cannot be moved. This is logical. It can't move the block since we are now expecting it to be at a particular location. In such a case we say that ostrstream has freezed itself. Once frozen we can't add any more characters to it. Adding characters to a frozen ostrstream results in undefined behavior. In addition, the ostrstream is no longer responsible for cleaning up the storage. You took over that responsibility when you asked for the char * with str( ). We can clean the storage in two ways: Using the delete operator as shown below: ostrstream s ; char *p ; p = s.str( ) ; delete p ; By unfreezing the ostrstream. You do this by calling freeze( ), with an argument 1. During freezing it is called with the default argument of 0.

1. What will be the output of the following code? void main () { int i = 0 , a[3] ; a[i] = i++; printf (%d",a[i]) ; } Ans: The output for the above code would be a garbage value. In the statement a[i] = i++; the value of the variable i would get assigned first to a[i] i.e. a[0] and then the value of i would get incremented by 1. Since a[i] i.e. a[1] has not been initialized, a[i] will have a garbage value. -----------------------------------------------------------------------------------------------2. Why doesn't the following code give the desired result? int x = 3000, y = 2000 ; long int z = x * y ; Ans: Here the multiplication is carried out between two ints x and y, and the result that would overflow would be truncated before being assigned to the variable z of type long int. However, to get the correct output, we should use an explicit cast to force long arithmetic as shown below: long int z = ( long int ) x * y ; Note that ( long int )( x * y ) would not give the desired effect. -----------------------------------------------------------------------------------------------3. Why doesn't the following statement work? char str[ ] = "Hello" ; strcat ( str, '!' ) ; Ans: The string function strcat( ) concatenates strings and not a character. The basic difference between a string and a character is that a string is a collection of characters, represented by an array of characters whereas a character is a single character. To make the above statement work writes the statement as shown below: strcat ( str, "!" ) ; -----------------------------------------------------------------------------------------------4. How do I know how many elements an array can hold?

Ans: The amount of memory an array can consume depends on the data type of an array. In DOS environment, the amount of memory an array can consume depends on the current memory model (i.e. Tiny, Small, Large, Huge, etc.). In general an array cannot consume more than 64 kb. Consider following program, which shows the maximum number of elements an array of type int, float and char can have in case of Small memory model. main( ) { int i[32767] ; float f[16383] ; char s[65535] ; } -----------------------------------------------------------------------------------------------5. How do I write code that reads data at memory location specified by segment and offset? Ans: Use peekb( ) function. This function returns byte(s) read from specific segment and offset locations in memory. The following program illustrates use of this function. In this program from VDU memory we have read characters and its attributes of the first row. The information stored in file is then further read and displayed using peek( ) function. #include <stdio.h> #include <dos.h> main( ) { char far *scr = 0xB8000000 ; FILE *fp ; int offset ; char ch ; if ( ( fp = fopen ( "scr.dat", "wb" ) ) == NULL ) { printf ( "\nUnable to open file" ) ; exit( ) ; } // reads and writes to file for ( offset = 0 ; offset < 160 ; offset++ ) fprintf ( fp, "%c", peekb ( scr, offset ) ) ; fclose ( fp ) ;

if ( ( fp = fopen ( "scr.dat", "rb" ) ) == NULL ) { printf ( "\nUnable to open file" ) ; exit( ) ; } // reads and writes to file for ( offset = 0 ; offset < 160 ; offset++ ) { fscanf ( fp, "%c", &ch ) ; printf ( "%c", ch ) ; } fclose ( fp ) ; } 6. How do I compare character data stored at two different memory locations? Ans: Sometimes in a program we require to compare memory ranges containing strings. In such a situation we can use functions like memcmp( ) or memicmp( ). The basic difference between two functions is that memcmp( ) does a case-sensitive comparison whereas memicmp( ) ignores case of characters. Following program illustrates the use of both the functions. #include <mem.h> main( ) { char *arr1 = "Kicit" ; char *arr2 = "kicitNagpur" ; int c ; c = memcmp ( arr1, arr2, sizeof ( arr1 ) ) ; if ( c == 0 ) printf ( "\nStrings arr1 and arr2 compared using memcmp are identical" ) ; else printf ( "\nStrings arr1 and arr2 compared using memcmp are not identical" ); c = memicmp ( arr1, arr2, sizeof ( arr1 ) ) ;

if ( c == 0 ) printf ( "\nStrings arr1 and arr2 compared using memicmp are identical" ) ; else printf ( "\nStrings arr1 and arr2 compared using memicmp are not identical" ) ; } -----------------------------------------------------------------------------------------------7. Fixed-size objects are more appropriate as compared to variable size data objects. Using variable-size data objects saves very little space. Variable size data objects usually have some overhead. Manipulation of fixed-size data objects is usually faster and easier. Use fixed size when maximum size is clearly bounded and close to average. And use variable-size data objects when a few of the data items are bigger than the average size. For example, char *num[10] = { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten" } ; Instead of using the above, use char num[10][6] = { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten" } ; The first form uses variable-size data objects. It allocates 10 pointers, which are pointing to 10 string constants of variable size. Assuming each pointer is of 4 bytes, it requires 90 bytes. On the other hand, the second form uses fixed size data objects. It allocates 10 arrays of 6 characters each. It requires only 60 bytes of space. So, the variable-size in this case does not offer any advantage over fixed size. -----------------------------------------------------------------------------------------------8. The Spawnl( ) function... DOS is a single tasking operating system, thus only one program runs at a time. The Spawnl( ) function provides us with the capability of starting the execution of one program from within another program. The first program is called the parent process and the second program that gets called from within the first program is called a child process. Once the second program starts execution, the first is put on hold until the second program completes execution. The first program is then restarted. The following program demonstrates use of spawnl( ) function. /* Mult.c */ int main ( int argc, char* argv[ ] ) { int a[3], i, ret ; if ( argc < 3 || argc > 3 )

{ printf ( "Too many or Too few arguments..." ) ; exit ( 0 ) ; } for ( i = 1 ; i < argc ; i++ ) a[i] = atoi ( argv[i] ) ; ret = a[1] * a[2] ; return ret ; } /* Spawn.c */ #include <process.h> #include <stdio.h> main( ) { int val ; val = spawnl ( P_WAIT, "C:\\Mult.exe", "3", "10", "20", NULL ) ; printf ( "\nReturned value is: %d", val ) ; } Here, there are two programs. The program 'Mult.exe' works as a child process whereas 'Spawn.exe' works as a parent process. On execution of 'Spawn.exe' it invokes 'Mult.exe' and passes the command-line arguments to it. 'Mult.exe' in turn on execution, calculates the product of 10 and 20 and returns the value to val in 'Spawn.exe'. In our call to spawnl( ) function, we have passed 6 parameters, P_WAIT as the mode of execution, path of '.exe' file to run as child process, total number of arguments to be passed to the child process, list of command line arguments and NULL. P_WAIT will cause our application to freeze execution until the child process has completed its execution. This parameter needs to be passed as the default parameter if you are working under DOS. under other operating systems that support multitasking, this parameter can be P_NOWAIT or P_OVERLAY. P_NOWAIT will cause the parent process to execute along with the child process, P_OVERLAY will load the child process on top of the parent process in the memory. -----------------------------------------------------------------------------------------------9. Are the following two statements identical? char str[6] = "Kicit" ; char *str = "Kicit" ; Ans: No! Arrays are not pointers. An array is a single, pre-allocated chunk of contiguous elements (all of the same type), fixed in size and location. A pointer on the other hand, is a reference to any data element (of a particular type) located anywhere. A pointer must be assigned to point to space allocated elsewhere, but it can be reassigned any time. The array declaration char str[6] ; requests that space for 6 characters be set aside, to be known by name str. In other words there is a location named str at which six characters are stored. The pointer declaration char *str ; on the other hand, requests a place that

holds a pointer, to be known by the name str. This pointer can point almost anywhere to any char, to any contiguous array of chars, or nowhere. -----------------------------------------------------------------------------------------------10. Is the following code fragment correct? const int x = 10 ; int arr[x] ; Ans: No! Here, the variable x is first declared as an int so memory is reserved for it. Then it is qualified by a const qualifier. Hence, const qualified object is not a constant fully. It is an object with read only attribute, and in C, an object associated with memory cannot be used in array dimensions.

11. How do I write code to retrieve current date and time from the system and display it as a string? Ans: Use time( ) function to get current date and time and then ctime( ) function to display it as a string. This is shown in following code snippet. #include <sys\types.h> void main( ) { time_t curtime ; char ctm[50] ; time ( &curtime ) ; //retrieves current time & stores in curtime printf ( "\nCurrent Date & Time: %s", ctime ( &curtime ) ) ; } -----------------------------------------------------------------------------------------------12. How do I change the type of cursor and hide a cursor? Ans: We can change the cursor type by using function _setcursortype( ). This function can change the cursor type to solid cursor and can even hide a cursor. Following code shows how to change the cursor type and hide cursor. #include <conio.h> main( ) {

/* Hide cursor */ _setcursortype ( _NOCURSOR ) ; /* Change cursor to a solid cursor */ _setcursortype ( _SOLIDCURSOR ) ; /* Change back to the normal cursor */ _setcursortype ( _NORMALCURSOR ) ; } -----------------------------------------------------------------------------------------------13. How do I write code that would get error number and display error message if any standard error occurs? Ans: Following code demonstrates this. #include <stdio.h> #include <stdlib.h> #include <errno.h> main( ) { char *errmsg ; FILE *fp ; fp = fopen ( "C:\file.txt", "r" ) ; if ( fp == NULL ) { errmsg = strerror ( errno ) ; printf ( "\n%s", errmsg ) ; } } Here, we are trying to open 'file.txt' file. However, if the file does not exist, then it would cause an error. As a result, a value (in this case 2) related to the error generated would get set in errno. errno is an external int variable declared in 'stdlib.h' and also in 'errno.h'. Next, we have called sterror( ) function which takes an error number and returns a pointer to standard error message related to the given error number. -----------------------------------------------------------------------------------------------14. How do I write code to get the current drive as well as set the current drive? Ans: The function getdisk( ) returns the drive number of current drive. The drive number 0 indicates 'A' as the current drive, 1 as 'B' and so on. The Setdisk( ) function sets the current drive. This function takes one argument which is an integer indicating the drive to be set. Following program demonstrates use of both the functions.

#include <dir.h> main( ) { int dno, maxdr ; dno = getdisk( ) ; printf ( "\nThe current drive is: %c\n", 65 + dno ); maxdr = setdisk ( 3 ) ; dno = getdisk( ) ; printf ( "\nNow the current drive is: %c\n", 65 + dno ) ; } -----------------------------------------------------------------------------------------------15. The functions memcmp( ) and memicmp( ) The functions memcmp( ) and memicmp( ) compares first n bytes of given two blocks of memory or strings. However, memcmp( ) performs comparison as unsigned chars whereas memicmp( ) performs comparison as chars but ignores case (i.e. upper or lower case). Both the functions return an integer value where 0 indicates that two memory buffers compared are identical. If the value returned is greater than 0 then it indicates that the first buffer is bigger than the second one. The value less than 0 indicate that the first buffer is less than the second buffer. The following code snippet demonstrates use of both #include <stdio.h> #include <mem.h> main( ) { char str1[] = "This string contains some characters" ; char str2[] = "this string contains" ; int result ; result = memcmp ( str1, str2, strlen ( str2 ) ) ; printf ( "\nResult after comapring buffer using memcmp( )" ) ; show ( result ) ; result = memicmp ( str1, str2, strlen ( str2 ) ) ; printf ( "\nResult after comapring buffer using memicmp( )" ) ; show ( result ) ; }

show ( int r ) { if ( r == 0 ) printf ( "\nThe buffer str1 and str2 hold identical data" ) ; if ( r > 0 ) printf ( "\nThe buffer str1 is bigger than buffer str2" ) ; if ( r < 0 ) printf ( "\nThe buffer str1 is less than buffer str2" ) ; } -----------------------------------------------------------------------------------------------16. How do I write code to find an amount of free disk space available on current drive? Ans: Use getdfree( ) function as shown in follow code. #include #include #include #include <stdio.h> <stdlib.h> <dir.h> <dos.h>

main( ) { int dr ; struct dfree disk ; long freesp ; dr = getdisk( ) ; getdfree ( dr + 1 , &disk ) ; if ( disk.df_sclus == 0xFFFF ) { printf ( "\ngetdfree( ) function failed\n"); exit ( 1 ) ; } freesp = ( long ) disk.df_avail * ( long ) disk.df_bsec * ( long ) disk.df_sclus ; printf ( "\nThe current drive %c: has %ld bytes available as free space\n", 'A' + dr, freesp ) ; } 17. Use of array indices... If we wish to store a character in a char variable ch and the character to be stored

depends on the value of another variable say color (of type int), then the code would be as shown below: switch ( color ) { case 0 : ch = 'R' ; break ; case 1 : ch = 'G' ; break ; case 2 : ch = 'B' ; break ; } In place of switch-case we can make use of the value in color as an index for a character array. How to do this is shown in following code snippet. char *str = "RGB' ; char ch ; int color ; // code ch = str[ color ] ; -----------------------------------------------------------------------------------------------18. Function atexit( ) recevies parameter as the address of function of the type void fun ( void ). The function whose address is passed to atexit( ) gets called before the termination of program. If atexit( ) is called for more than one function then the functions are called in "first in last out" order. You can verify that from the output. #include <stdio.h> #include <stdlib.h> void fun1( ) { printf("Inside fun1\n"); } void fun2( ) { printf("Inside fun2\n"); } main( ) { atexit ( fun1 ) ; /* some code */ atexit ( fun2 ) ; printf ( "This is the last statement of program?\n" ); }

-----------------------------------------------------------------------------------------------19. How do I write a user-defined function, which deletes each character in a string str1, which matches any character in string str2? Ans: The function is as shown below: Compress ( char str1[], char str2[] ) { int i, j, k ; for ( i = k = 0 ; str1[i] != \0 ; i++ ) { for ( j = 0 ; str2[j] != \0 && str2[j] != str1[i] ; j++ ) ; if ( str2[j] == \0 ) str1[k++] = str1[I] ; } str1[k] = \0 } -----------------------------------------------------------------------------------------------20. How does free( ) know how many bytes to free? Ans: The malloc( ) / free( ) implementation remembers the size of each block allocated and returned, so it is not necessary to remind it of the size when freeing. -----------------------------------------------------------------------------------------------21. What is the use of randomize( ) and srand( ) function? Ans: While generating random numbers in a program, sometimes we require to control the series of numbers that random number generator creates. The process of assigning the random number generators starting number is called seeding the generator. The randomize( ) and srand( ) functions are used to seed the random number generators. The randomize( ) function uses PC's clock to produce a random seed, whereas the srand( ) function allows us to specify the random number generator's starting value. -----------------------------------------------------------------------------------------------22.

How do I determine amount of memory currently available for allocating? Ans: We can use function coreleft( ) to get the amount of memory available for allocation. However, this function does not give an exact amount of unused memory. If, we are using a small memory model, coreleft( ) returns the amount of unused memory between the top of the heap and stack. If we are using a larger model, this function returns the amount of memory between the highest allocated memory and the end of conventional memory. The function returns amount of memory in terms of bytes. -----------------------------------------------------------------------------------------------23. How does a C program come to know about command line arguments? Ans: When we execute our C program, operating system loads the program into memory. In case of DOS, it first loads 256 bytes into memory, called program segment prefix. This contains file table, environment segment, and command line information. When we compile the C program the compiler inserts additional code that parses the command, assigning it to the argv array, making the arguments easily accessible within our C program. 24. When we open a file, how does functions like fread( )/fwrite( ), etc. get to know from where to read or to write the data? Ans: When we open a file for read/write operation using function like fopen( ), it returns a pointer to the structure of type FILE. This structure stores the file pointer called position pointer, which keeps track of current location within the file. On opening file for read/write operation, the file pointer is set to the start of the file. Each time we read/write a character, the position pointer advances one character. If we read one line of text at a step from the file, then file pointer advances to the start of the next line. If the file is opened in append mode, the file pointer is placed at the very end of the file. Using fseek( ) function we can set the file pointer to some other place within the file. ------------------------------------------------------------------------------------------------

25. The sizeof( ) function doesnt return the size of the block of memory pointed to by a pointer. Why? Ans: The sizeof( ) operator does not know that malloc( ) has been used to allocate a pointer. sizeof( ) gives us the size of pointer itself. There is no handy way to find out the size of a block allocated by malloc( ). -----------------------------------------------------------------------------------------------

-26. FP_SEG And FP_OFF Sometimes while working with far pointers we need to break a far address into its segment and offset. In such situations we can use FP_SEG and FP_OFF macros. Following program illustrates the use of these two macros. #include <dos.h> main( ) { unsigned s, o ; char far *ptr = "Hello!" ; s = FP_SEG ( ptr ) ; o = FP_OFF ( ptr ) ; printf ( "\n%u %u", s, o ) ; } -----------------------------------------------------------------------------------------------27. How do I write a program to convert a string containing number in a hexadecimal form to its equivalent decimal? Ans: The following program demonstrates this: main( ) { char str[] = "0AB" ; int h, hex, i, n ; n=0;h=1; for ( i = 0 ; h == 1 ; i++ ) { if ( str[i] >= '0' && str[i] <= '9' ) hex = str[i] - '0' ; else { if ( str[i] >= 'a' && str[i] <= 'f' ) hex = str[i] - 'a' + 10 ; else if ( str[i] >= 'A' && str[i] <= 'F' ) hex = str[i] - 'A' + 10 ; else h=0; } if ( h == 1 ) n = 16 * n + hex ; } printf ( "\nThe decimal equivalent of %s is %d", str, n ) ; } The output of this program would be the decimal equivalent of 0AB is 171. -----------------------------------------------------------------------------------------------

-28. How do I write code that reads the segment register settings? Ans: We can use segread( ) function to read segment register settings. There are four segment registerscode segment, data segment, stack segment and extra segment. Sometimes when we use DOS and BIOS services in a program we need to know the segment register's value. In such a situation we can use segread( ) function. The following program illustrates the use of this function. #include <dos.h> main( ) { struct SREGS s ; segread ( &s ) ; printf ( "\nCS: %X DS: %X SS: %X ES: %X",s.cs, s.ds, s.ss, s.es ) ; } -----------------------------------------------------------------------------------------------29. What is environment and how do I get environment for a specific entry? Ans: While working in DOS, it stores information in a memory region called environment. In this region we can place configuration settings such as command path, system prompt, etc. Sometimes in a program we need to access the information contained in environment. The function getenv( ) can be used when we want to access environment for a specific entry. Following program demonstrates the use of this function. #include <stdio.h> #include <stdlib.h> main( ) { char *path = NULL ; path = getenv ( "PATH" ) ; if ( *path != NULL ) printf ( "\nPath: %s", path ) ; else printf ( "\nPath is not set" ) ; } -----------------------------------------------------------------------------------------------30. How do I display current date in the format given below?

Saturday October 12, 2002 Ans: Following program illustrates how we can display date in above given format. #include <stdio.h> #include <time.h> main( ) { struct tm *curtime ; time_t dtime ; char str[30] ; time ( &dtime ) ; curtime = localtime ( &dtime ) ; strftime ( str, 30, "%A %B %d, %Y", curtime ) ; printf ( "\n%s", str ) ; } Here we have called time( ) function which returns current time. This time is returned in terms of seconds, elapsed since 00:00:00 GMT, January 1, 1970. To extract the week day, day of month, etc. from this value we need to break down the value to a tm structure. This is done by the function localtime( ). Then we have called strftime( ) function to format the time and store it in a string str.

31. If we have declared an array as global in one file and we are using it in another file then why doesn't the sizeof operator works on an extern array? Ans: An extern array is of incomplete type as it does not contain the size. Hence we cannot use sizeof operator, as it cannot get the size of the array declared in another file. To resolve this use any of one the following two solutions: 1. In the same file declare one more variable that holds the size of array. For example, array.c int arr[5] ; int arrsz = sizeof ( arr ) ; myprog.c extern int arr[] ; extern int arrsz ; 2. Define a macro which can be used in an array declaration. For example, myheader.h

#define SZ 5 array.c #include "myheader.h" int arr[SZ] ; myprog.c #include "myheader.h" extern int arr[SZ] ; -----------------------------------------------------------------------------------------------32. How do I write printf( ) so that the width of a field can be specified at runtime? Ans: This is shown in following code snippet. main( ) { int w, no ; printf ( "Enter number and the width for the number field:" ) ; scanf ( "%d%d", &no, &w ) ; printf ( "%*d", w, no ) ; } Here, an '*' in the format specifier in printf( ) indicates that an int value from the argument list should be used for the field width. -----------------------------------------------------------------------------------------------33. How to find the row and column dimension of a given 2-D array? Ans: Whenever we initialize a 2-D array at the same place where it has been declared, it is not necessary to mention the row dimension of an array. The row and column dimensions of such an array can be determined programmatically as shown in following program. void main( ) { int a[][3] = { 0, 1, 2, 9,-6, 8, 7, 5, 44, 23, 11,15 } ;

int c = sizeof ( a[0] ) / sizeof ( int ) ; int r = ( sizeof ( a ) / sizeof ( int ) ) / c ; int i, j ; printf ( "\nRow: %d\nCol: %d\n", r, c ) ; for ( i = 0 ; i < r ; i++ ) { for ( j = 0 ; j < c ; j++ ) printf ( "%d ", a[i][j] ) ; printf ( "\n" ) ; } } -----------------------------------------------------------------------------------------------34. The access( ) function... The access( ) function checks for the existence of a file and also determines whether it can be read, written to or executed. This function takes two arguments the filename and an integer indicating the access mode. The values 6, 4, 2, and 1 checks for read/write, read, write and execute permission of a given file, whereas value 0 checks whether the file exists or not. Following program demonstrates how we can use access( ) function to check if a given file exists. #include <io.h> main( ) { char fname[67] ; printf ( "\nEnter name of file to open" ) ; gets ( fname ) ; if ( access ( fname, 0 ) != 0 ) { printf ( "\nFile does not exist." ) ; return ; } } -----------------------------------------------------------------------------------------------35. How do I convert a floating-point number to a string? Ans: Use function gcvt( ) to convert a floating-point number to a string. Following program demonstrates the use of this function. #include <stdlib.h>

main( ) { char str[25] ; float no ; int dg = 5 ; /* significant digits */ no = 14.3216 ; gcvt ( no, dg, str ) ; printf ( "String: %s\n", str ) ; } 36. What is a stack ? Ans: The stack is a region of memory within which our programs temporarily store data as they execute. For example, when a program passes parameters to functions, C places the parameters on the stack. When the function completes, C removes the items from the stack. Similarly, when a function declares local variables, C stores the variable's values on the stack during the function's execution. Depending on the program's use of functions and parameters, the amount of stack space that a program requires will differ. -----------------------------------------------------------------------------------------------37. Allocating memory for a 3-D array #include "alloc.h" #define MAXX 3 #define MAXY 4 #define MAXZ 5 main( ) { int ***p, i, j, k ; p = ( int *** ) malloc ( MAXX * sizeof ( int ** ) ) ; for ( i = 0 ; i < MAXX ; i++ ) { p[i] = ( int ** ) malloc ( MAXY * sizeof ( int * ) ) ; for ( j = 0 ; j < MAXY ; j++ ) p[i][j] = ( int * ) malloc ( MAXZ * sizeof ( int ) ) ; } for ( k = 0 ; k < MAXZ ; k++ ) { for ( i = 0 ; i < MAXX ; i++ ) { for ( j = 0 ; j < MAXY ; j++ ) { p[i][j][k] = i + j + k ; printf ( "%d ", p[i][j][k] ) ; } printf ( "\n" ) ; } printf ( "\n\n" ) ; }

} Data Structures How to distinguish between a binary tree and a tree? Ans: A node in a tree can have any number of branches. While a binary tree is a tree structure in which any node can have at most two branches. For binary trees we distinguish between the subtree on the left and subtree on the right, whereas for trees the order of the subtrees is irrelevant. Consider the following figure... This above figure shows two binary trees, but these binary trees are different. The first has an empty right subtree while the second has an empty left subtree. If the above are regarded as trees (not the binary trees), then they are same despite the fact that they are drawn differently. Also, an empty binary tree can exist, but there is no tree having zero nodes. -----------------------------------------------------------------------------------------------38. How do I use the function ldexp( ) in a program? Ans: The math function ldexp( ) is used while solving the complex mathematical equations. This function takes two arguments, a double value and an int respectively. The order in which ldexp( ) function performs calculations is ( n * pow ( 2, exp ) ) where n is the double value and exp is the integer. The following program demonstrates the use of this function. #include <stdio.h> #include <math.h> void main( ) { double ans ; double n = 4 ; ans = ldexp ( n, 2 ) ; printf ( "\nThe ldexp value is : %lf\n", ans ) ; } Here, ldexp( ) function would get expanded as ( 4 * 2 * 2 ), and the output would be the ldexp value is : 16.000000 -----------------------------------------------------------------------------------------------39. Can we get the mantissa and exponent form of a given number? Ans: The function frexp( ) splits the given number into a mantissa and exponent form. The function takes two arguments, the number to be converted as a double value and an int to store the exponent form. The function returns the mantissa part as a double value. Following example demonstrates the use of this function. #include <math.h> #include <stdio.h>

void main( ) { double mantissa, number ; int exponent ; number = 8.0 ; mantissa = frexp ( number, &exponent ) ; printf ( "The number %lf is ", number ) ; printf ( "%lf times two to the ", mantissa ) ; printf ( "power of %d\n", exponent ) ; return 0 ; } -----------------------------------------------------------------------------------------------40. How do I write code that executes certain function only at program termination? Ans: Use atexit( ) function as shown in following program. #include <stdlib.h> main( ) { int ch ; void fun ( void ) ; atexit ( fun ) ; // code } void fun( void ) { printf ( "\nTerminate program......" ) ; getch( ) ; } -----------------------------------------------------------------------------------------------41. What are memory models? Ans: The compiler uses a memory model to determine how much memory is allocated to the program. The PC divides memory into blocks called segments of size 64 KB. Usually, program uses one segment for code and a second segment for data. A memory model defines the number of segments the compiler can use for each. It is important to know which memory model can be used for a program. If we use wrong memory model, the program might not have enough memory to execute. The problem can be solved using larger memory model. However, larger the memory model, slower is your program execution. So we must choose the smallest memory model that satisfies our program needs. Most of the compilers support memory models like tiny, small, medium, compact, large and huge. 36. What is a stack ?

Ans: The stack is a region of memory within which our programs temporarily store data as they execute. For example, when a program passes parameters to functions, C places the parameters on the stack. When the function completes, C removes the items from the stack. Similarly, when a function declares local variables, C stores the variable's values on the stack during the function's execution. Depending on the program's use of functions and parameters, the amount of stack space that a program requires will differ. -----------------------------------------------------------------------------------------------37. Allocating memory for a 3-D array #include "alloc.h" #define MAXX 3 #define MAXY 4 #define MAXZ 5 main( ) { int ***p, i, j, k ; p = ( int *** ) malloc ( MAXX * sizeof ( int ** ) ) ; for ( i = 0 ; i < MAXX ; i++ ) { p[i] = ( int ** ) malloc ( MAXY * sizeof ( int * ) ) ; for ( j = 0 ; j < MAXY ; j++ ) p[i][j] = ( int * ) malloc ( MAXZ * sizeof ( int ) ) ; } for ( k = 0 ; k < MAXZ ; k++ ) { for ( i = 0 ; i < MAXX ; i++ ) { for ( j = 0 ; j < MAXY ; j++ ) { p[i][j][k] = i + j + k ; printf ( "%d ", p[i][j][k] ) ; } printf ( "\n" ) ; } printf ( "\n\n" ) ; } } Data Structures How to distinguish between a binary tree and a tree? Ans: A node in a tree can have any number of branches. While a binary tree is a tree structure in which any node can have at most two branches. For binary trees we distinguish between the subtree on the left and subtree on the right, whereas for trees the order of the subtrees is irrelevant. Consider the following figure... This above figure shows two binary trees, but these binary trees are different. The first has an empty right subtree while the second has an empty left subtree. If the above are regarded as trees (not the binary trees), then they are same despite the fact that they are drawn differently. Also, an empty binary tree can exist, but there is

no tree having zero nodes. -----------------------------------------------------------------------------------------------38. How do I use the function ldexp( ) in a program? Ans: The math function ldexp( ) is used while solving the complex mathematical equations. This function takes two arguments, a double value and an int respectively. The order in which ldexp( ) function performs calculations is ( n * pow ( 2, exp ) ) where n is the double value and exp is the integer. The following program demonstrates the use of this function. #include <stdio.h> #include <math.h> void main( ) { double ans ; double n = 4 ; ans = ldexp ( n, 2 ) ; printf ( "\nThe ldexp value is : %lf\n", ans ) ; } Here, ldexp( ) function would get expanded as ( 4 * 2 * 2 ), and the output would be the ldexp value is : 16.000000 -----------------------------------------------------------------------------------------------39. Can we get the mantissa and exponent form of a given number? Ans: The function frexp( ) splits the given number into a mantissa and exponent form. The function takes two arguments, the number to be converted as a double value and an int to store the exponent form. The function returns the mantissa part as a double value. Following example demonstrates the use of this function. #include <math.h> #include <stdio.h> void main( ) { double mantissa, number ; int exponent ; number = 8.0 ; mantissa = frexp ( number, &exponent ) ; printf ( "The number %lf is ", number ) ; printf ( "%lf times two to the ", mantissa ) ; printf ( "power of %d\n", exponent ) ;

return 0 ; } -----------------------------------------------------------------------------------------------40. How do I write code that executes certain function only at program termination? Ans: Use atexit( ) function as shown in following program. #include <stdlib.h> main( ) { int ch ; void fun ( void ) ; atexit ( fun ) ; // code } void fun( void ) { printf ( "\nTerminate program......" ) ; getch( ) ; } -----------------------------------------------------------------------------------------------41. What are memory models? Ans: The compiler uses a memory model to determine how much memory is allocated to the program. The PC divides memory into blocks called segments of size 64 KB. Usually, program uses one segment for code and a second segment for data. A memory model defines the number of segments the compiler can use for each. It is important to know which memory model can be used for a program. If we use wrong memory model, the program might not have enough memory to execute. The problem can be solved using larger memory model. However, larger the memory model, slower is your program execution. So we must choose the smallest memory model that satisfies our program needs. Most of the compilers support memory models like tiny, small, medium, compact, large and huge. 42. How does C compiler store elements in a multi-dimensional array? Ans: The compiler maps multi-dimensional arrays in two waysRow major order and Column order. When the compiler places elements in columns of an array first then it is called column-major order. When the compiler places elements in rows of an array first then it is called row-major order. C compilers store multidimensional arrays in row-major order. For example, if there is a multi-dimensional array a[2][3], then according row-major order, the elements would get stored in memory following order: a[0][0], a[0][1], a[0][2], a[1][0], a[1][1], a[1][2] -----------------------------------------------------------------------------------------------43.

If the result of an _expression has to be stored to one of two variables, depending on a condition, can we use conditional operators as shown below? ( ( i < 10 ) ? j : k ) = l * 2 + p ; Ans: No! The above statement is invalid. We cannot use the conditional operators in this fashion. The conditional operators like most operators, yields a value, and we cannot assign the value of an _expression to a value. However, we can use conditional operators as shown in following code snippet. main( ) { int i, j, k, l ; i = 5 ; j = 10 ; k = 12, l = 1 ; * ( ( i < 10 ) ? &j : &k ) = l * 2 + 14 ; printf ( "i = %d j = %d k = %d l = %d", i, j, k, l ) ; } The output of the above program would be as given below: i = 5 j = 16 k = 12 l = 1 -----------------------------------------------------------------------------------------------44. How can I find the day of the week of a given date? Ans: The following code snippet shows how to get the day of week from the given date. dayofweek ( int yy, int mm, int dd ) { /*Monday = 1 and Sunday = 0 */ /* month number >= 1 and <= 12, yy > 1752 or so */ static int arr[ ] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 } ; yy = yy - mm < 3 ; return ( yy + yy / 4 - yy / 100 + yy / 400 + arr[ mm - 1] + dd ) % 7 ; } void main( ) { printf ( "\n\n\nDay of week : %d ", dayofweek ( 2002, 5, 18 ) ) ; } ------------------------------------------------------------------------------------------------

45. What's the difference between these two declarations?

struct str1 { ... } ; typedef struct { ... } str2 ; Ans : The first form declares a structure tag whereas the second declares a typedef. The main difference is that the second declaration is of a slightly more abstract type -- its users don't necessarily know that it is a structure, and the keyword struct is not used when declaring instances of it. -----------------------------------------------------------------------------------------------46. How do I print the contents of environment variables? Ans:. The following program shows how to achieve this: main( int argc, char *argv[ ], char *env[ ] ) { int i = 0 ; clrscr( ) ; while ( env[ i ] ) printf ( "\n%s", env[ i++ ] ) ; } main( ) has the third command line argument env, which is an array of pointers to the strings. Each pointer points to an environment variable from the list of environment variables. -----------------------------------------------------------------------------------------------47. div( )... The function div( ) divides two integers and returns the quotient and remainder. This function takes two integer values as arguments; divides first integer with the second one and returns the answer of division of type div_t. The data type div_t is a structure that contains two long ints, namely quot and rem, which store quotient and remainder of division respectively. The following example shows the use of div( ) function. #include <stdlib.h> void main( ) { div_t res ; res = div ( 32, 5 ) ; printf ( "\nThe quotient = %d and remainder = %d ", res.quot, res.rem ) ; } 48. What would the second and the third printf( ) output the following program? main( ) { char *str[ ] = { "Good Morning"

"Good Evening" "Good Afternoon" }; printf ( "\nFirst string = %s", str[0] ) ; printf ( "\nSecond string = %s", str[1] ) ; printf ( "\nThird string = %s", str[2] ) ; } Ans: For the above given program, we expect the output as Good Evening and Good Afternoon, for the second and third printf( ). However, the output would be as shown below. First string = Good MorningGood EveningGood Afternoon Second string = ( null ) Third string = What is missing in the above given code snippet is a comma separator which should separate the strings Good Morning, Good Evening and Good Afternoon. On adding comma, we would get the output as shown below. First string = Good Morning Second string = Good Evening Third string = Good Afternoon -----------------------------------------------------------------------------------------------49. How do I use scanf( ) to read the date in the form 'dd-mm-yy' ? Ans: There are two ways to read the date in the form of 'dd-mm-yy' one possible way is... int dd, mm, yy ; char ch ; /* for char '-' */ printf ( "\nEnter the date in the form of dd-mm-yy : " ) ; scanf( "%d%c%d%c%d", &dd, &ch, &mm, &ch, &yy ) ; And another best way is to use suppression character * as... int dd, mm, yy ; scanf( "%d%*c%d%*c%d", &dd, &mm, &yy ) ; The suppression character * suppresses the input read from the standard input buffer for the assigned control character. -----------------------------------------------------------------------------------------------50. How do I print a floating-point number with higher precision say 23.34568734 with only precision up to two decimal places? Ans: This can be achieved through the use of suppression char '*' in the format string of printf( ) as shown in the following program.

main( ) { int i = 2 ; float f = 23.34568734 ; printf ( "%.*f", i, f ) ; } The output of the above program would be 23.35. -----------------------------------------------------------------------------------------------51. Are the expressions *ptr++ and ++*ptr same? Ans: No. *ptr++ increments the pointer and not the value pointed by it, whereas ++*ptr increments the value being pointed to by ptr. -----------------------------------------------------------------------------------------------52. strpbrk( ) The function strpbrk( ) takes two strings as parameters. It scans the first string, to find, the first occurrence of any character appearing in the second string. The function returns a pointer to the first occurrence of the character it found in the first string. The following program demonstrates the use of string function strpbrk( ). #include <string.h> main( ) { char *str1 = "Hello!" ; char *str2 = "Better" ; char *p ; p = strpbrk ( str1, str2 ) ; if ( p ) printf ( "The first character found in str1 is %c", *p ) ; else printf ( "The character not found" ) ; } The output of the above program would be the first character found in str1 is e 53. Can we convert an unsigned long integer value to a string? Ans: The function ultoa( ) can be used to convert an unsigned long integer value to a string. This function takes three arguments, first the value that is to be converted, second the base address of the buffer in which the converted number has to be stored (with a string terminating null character '\0') and the last argument specifies the base to be used in converting the value. Following example demonstrates the use of this function.

#include <stdlib.h> void main( ) { unsigned long ul = 3234567231L ; char str[25] ; ultoa ( ul, str, 10 ) ; printf ( "str = %s unsigned long = %lu\n", str, ul ) ; } -----------------------------------------------------------------------------------------------54. ceil( ) and floor( ) The math function ceil( ) takes a double value as an argument. This function finds the smallest possible integer to which the given number can be rounded up. Similarly, floor( ) being a math function, takes a double value as an argument and returns the largest possible integer to which the given double value can be rounded down. The following program demonstrates the use of both the functions. #include <math.h> void main( ) { double no = 1437.23167 ; double down, up ; down = floor ( no ) ; up = ceil ( no ) ; printf ( "The original number %7.5lf\n", no ) ; printf ( "The number rounded down %7.5lf\n", down ) ; printf ( "The number rounded up %7.5lf\n", up ) ; } The output of this program would be, The original number 1437.23167 The number rounded down 1437.00000 The number rounded up 1438.00000 -----------------------------------------------------------------------------------------------55. How do I use function ecvt( ) in a program? Ans: The function ecvt( ) converts a floating-point value to a null terminated string. This function takes four arguments, such as, the value to be converted to string, the number of digits to be converted to string, and two integer pointers. The two-integer pointer stores the position of the decimal point (relative to the string) and the sign of the number, respectively. If the value in a variable, used to store sign is 0, then the number is positive and, if it is non-zero, then the number is negative. The function returns a pointer to the string containing digits. Following program demonstrates the use of this function.

#include <stdlib.h> main( ) { char *str ; double val ; int dec, sign ; int ndig = 4 ; val = 22 ; str = ecvt ( val, ndig, &dec, &sign ) ; printf ( "string = %s dec = %d sign = %d\n", str, dec, sign ) ; val = -345.67 ; ndig = 8 ; str = ecvt ( val, ndig, &dec, &sign ) ; printf ( "string = %s dec = %d sign = %d\n", str, dec, sign ) ; // number with a scientific notation val = 3.546712e5 ; ndig = 5 ; str = ecvt ( val, ndig, &dec, &sign ) ; printf ( "string = %s dec = %d sign = %d\n", str, dec, sign ) ; } The output of this program would be string = 2200 dec = 2 sign = 0 string = 34567000 dec = 3 sign = 1 string = 35467 dec = 6 sign = 0 -----------------------------------------------------------------------------------------------56. How to run DIR command programmatically? Ans: We can use the system( ) function to execute the DIR command along with its options. Following program shows how this can be achieved: // mydir.c main ( int argc, char *argv[ ] ) { char str[30] ; if ( argc < 2 ) exit ( 0 ) ; sprintf ( str, "dir %s %s", argv[1], argv[2] ) ; system ( str ) ;

} If we run the executable file of this program at command prompt passing the command line arguments as follows: > mydir abc.c /s This will search the file 'abc.c' in the current directory. -----------------------------------------------------------------------------------------------57. Suppose I have a structure having fields name, age, salary and have passed address of age to a function fun( ). How I can access the other member of the structure using the address of age? Ans: struct emp { char name[20] ; int age ; float salary ; }; main( ) { struct emp e ; printf ( "\nEnter name: " ) ; scanf ( "%s", e.name ) ; printf ( "\nEnter age: " ) ; scanf ( "%d", &e.age ) ; printf ( "\nEnter salary: " ) ; scanf ( "%f", &e.salary ) ; fun ( &e.age ) ; } fun ( int *p ) { struct emp *q ; int offset ; offset = ( char * ) ( & ( ( struct emp * ) 0 ) -> age ) - ( char * ) ( ( struct emp* ) 0 ) ; q = ( struct emp * ) ( ( char * ) p - offset ) ; printf ( "\nname: %s", q -> name ) ; printf ( "\nage: %d", q -> age ) ; printf ( "\nsalary: %f", q -> salary ) ; }

58. How to restrict the program's output to a specific screen region? Ans: A C function window( ) can be used to restrict the screen output to a specific region. The window( ) function defines a text-mode window. The parameters passed

to this function defines the upper-left and lower-right corner of the region within which you want the output. In the following program, the string 'Hello!' gets printed within the specified region. To print the string we must use cprintf( ) function which prints directly on the text-mode window. #include <conio.h> main( ) { int i, j ; window ( 20, 8, 60, 17 ) ; for ( i = 0 ; i < 8 ; i++ ) for ( j = 0 ; j < 10 ; j++ ) cprintf ( "Hello!" ) ; } -----------------------------------------------------------------------------------------------59. Sometimes you need to prompt the user for a password. When the user types in the password, the characters the user enters should not appear on the screen. A standard library function getpass( ) can be used to perform such function. Maximum number of characters that can be entered as password is 8. main( ) { char *pwd ; pwd = getpass ( "Enter Password" ) ; if ( strcmp ( pwd, "orgcity" ) ) printf ( "\nPassword %s is incorrect", pwd ) ; else printf ( "\nCorrect Password" ) ; } -----------------------------------------------------------------------------------------------60. How to obtain the current drive through C ? Ans: We can use the function _getdrive( ) to obtain the current drive. The _getdrive( ) function uses DOS function 0X19 to get the current drive number #include <direct.h> main( ) { int disk ; disk = _getdrive( ) + 'A' - 1 ; printf ( "The current drive is: %c\n", disk ) ; } -----------------------------------------------------------------------------------------------61.

How come the output for both the programs is different when the logic is same? main( ) { int i, j ; for ( i = 1, j = 1 ; i <= 5, j <= 100 ; i++, j++ ) { gotoxy ( 1, 1, ) ; printf ( "%d %d", i, j ) ; } } main( ) { int i, j ; for ( i =1, j = 1; j <= 100, i <= 5; i++, j++ ) { gotoxy ( 1, 1 ) ; printf ( "%d %d", i, j ) ; } } Output -> 5 5 Even if logic of both the programs is same the output of the first program comes out to be 100, 100, but of the second program it is 5, 5. The comma operator plays a vital role inside the for loop. It always considers the value of the latest variable. So, at the time of testing the condition in for loop, the value of j will be considered in the first program and value of i in the second. -----------------------------------------------------------------------------------------------62. Can we get the x and y coordinate of the current cursor position ? Ans : The function wherex( ) and wherey( ) returns the x-coordinate and ycoordinate of the current cursor position respectively. Both the functions return an integer value. The value returned by wherex( ) is the horizontal position of cursor and the value returned by wherey( ) is the vertical position of the cursor. Following program shows how to use the wherex( ) and wherey( ) functions. #include <conio.h> main( ) { printf ( "Just\n To\n Test\n Where\n the cursor\n goes" ) ; printf ( "Current location is X: %d Y: %d\n", wherex( ), wherey( ) ) ; } 63. How do I programmatically delete lines in the text window? Ans: While writing programs that perform screen-based I/O, you may want to-delete

the current line's contents, moving one line up, all of the output that follows. In such cases a function called delline( ) can be used. Following code snippet illustrates the use of function delline( ). #include <conio.h> main( ) { int i ; clrscr( ) ; for ( i = 0; i <= 23; i++ ) printf ( "Line %d\r\n", i ) ; printf ( "Press a key to continue : " ) ; getch( ) ; gotoxy ( 2, 6 ) ; for ( i = 6; i <= 12; i++ ) delline( ) ; getch( ) ; } -----------------------------------------------------------------------------------------------64. How do I get the time elapsed between two function calls ? Ans: The function difftime( ) finds the difference between two times. It calculates the elapsed time in seconds and returns the difference between two times as a double value. #include <time.h> #include <stdio.h> #include <dos.h> main( ) { int a[] = { 2, -34, 56, 78, 112, 33, -7, 11, 45, 29, 6 } ; int s ; time_t t1, t2 ; // time_t defines the value used for time function s = sizeof ( a ) / 2 ; t1 = time ( NULL ) ; sel_sort ( a, s ) ; // sort array by selection sort bub_sort ( a, s ) ; // sort array by bubble sort method t2 = time ( NULL ) ; printf ( "\nThe difference between two function calls is %f", difftime ( t2, t1 ) ) ; } In the above program we have called difftime( ) function that returns the time

elapsed from t1 to t2. -----------------------------------------------------------------------------------------------65. How do I use swab( ) in my program ? Ans: The function swab( ) swaps the adjacent bytes of memory. It copies the bytes from source string to the target string, provided that the number of characters in the source string is even. While copying, it swaps the bytes which are then assigned to the target string. #include <stdlib.h> #include <stdio.h> #include <string.h> main ( ) { char *str1 = "hS eesll snsiasl not eh es as oher " ; char *str2 ; clrscr( ) ; swab ( str1, str2, strlen ( str1 ) ) ; printf ( "The target string is : %s\n", str2 ) ; // output -- She sells snails on the sea shore getch( ) ; } -----------------------------------------------------------------------------------------------66. Turbo C provides various command line compiler options which we can use through TCC. The compiler options include : displaying specific warning messages, generating 8087 hardware instructions, using a filename for generating assembly code, etc. Instead of compiler options being executed at command line we can use these compiler options in our program. This can be achieved using #pragma options. We can use various flags with #pragma options to use the compiler options. All these flags are available in turbo C's online help. -----------------------------------------------------------------------------------------------67. I have an array declared in file 'F1.C' as, int a[ ] = { 1, 2, 3, 4, 5, 6 } ; and used in the file 'F2.C' as, extern int a[ ] ; In the file F2.C, why sizeof doesn't work on the array a[ ]? Ans: An extern array of unspecified size is an incomplete type. You cannot apply sizeof to it, because sizeof operates during compile time and it is unable to learn the size of an array that is defined in another file. You have three ways to resolve this

problem: 1. In file 'F1.C' define as, int a[ ] = { 1, 2, 3, 4, 5, 6 } ; int size_a = sizeof ( a ) ; and in file F2.C declare as, extern int a[ ] ; extern int size_a ; 2. In file 'F1.H' define, #define ARR_SIZ 6 In file F1.C declare as, #include "F1.H" int a[ ARR_SIZ ] ; and in file F2.C declare as, #include "F1.H" extern int a[ ARR_SIZ ] ; 3. In file 'F1.C' define as, int a[ ] = { 1, 2, 3, 4, 5, 6, -1 } ; and in file 'F2.C' declare as, extern int a[ ] ; Here the element -1 is used as a sentinel value, so the code can understand the end without any explicit size. 68. How to delete a line from text displayed on the screen? Ans: Sometimes, specially when we are creating a text editor like program we may wish to allow user to delete a line. We can do so by using two functions namely clreol( ) and delline( ). The clreol( ) function deletes the line from the current cursor position to the end of line. The delline() function deletes the entire line at the current cursor position and moves up the following line. Following program shows how to use these functions. #include <conio.h> main( ) { int i ; for ( i = 1 ; i <= 20 ; i++ ) printf ( "This is Line %d\n", i ) ; getch( ) ; gotoxy ( 1, 7 ) ; clreol( ) ; getch( ) ; gotoxy ( 1, 12 ) ; delline( ) ;

getch( ) ; } -----------------------------------------------------------------------------------------------69. How do I programmatically insert lines in the text window? Ans: We can insert a blank line in the text window using the insline( ) function. This function inserts line at current cursor position. While doing so, it shifts down the lines that are below the newly inserted line. #include <conio.h> void main( ) { printf ( "The little snail was slowly moving up. She wanted\r\n" ) ; printf ( "to reach the top of the tree. It was chilly\r\n" ) ; printf ( "winter season. Most of the animals were resting in\r\n" ) ; printf ( "their nests as there was a heavy snow fall.\r\n" ) ; printf ( "\r\nPress any key to continue:" ) ; gotoxy ( 10, 2 ) ; getch( ) ; insline( ) ; getch( ) ; } -----------------------------------------------------------------------------------------------70. What will be the output of the following program? main( ) { unsigned int num ; int i ; printf ( "\nEnter any number" ) ; scanf ( "%u", &num ) ; for ( i = 0 ; i < 16 ; i++ ) printf ( "%d", ( num << i & 1 << 15 ) ? 1 : 0 ) ; } Ans: The output of this program is the binary equivalent of the given number. We have used bitwise operators to get the binary number. -----------------------------------------------------------------------------------------------71. Graphics

Building Mouse Cursors... In text mode the mouse cursor appears as a block, whereas in graphics mode it appears as an arrow. If we wish we can change the graphics cursor to any other shape the way Windows does. The mouse cursor in graphics mode occupies a 16 by 16 pixel box. By highlighting or dehighlighting some of the pixels in this box we can get the desired shape. For example, the following bit-pattern can be used to generate the cursor which looks like an hour-glass. 1111111111111111 0000000000000000 1000000000000001 0000000000000000 1111111111111111 0000000000000000 1000000000000001 0000000000000000 0100000000000010 1000000000000001 0010000000000100 1100000000000011 0000100000010000 1111000000001111 0000001001000000 1111110000111111 0000001001000000 1111110000111111 0000100000010000 1111000000001111 0010000000000100 1100000000000011 0100000000000010 1000000000000001 1000000000000001 0000000000000000 1111111111111111 0000000000000000 1000000000000001 0000000000000000 1111111111111111 0000000000000000 Mouse pointer bitmap Screen Mask the one's in the mouse pointer bitmap indicate that the pixel would be drawn whereas the zeros indicate that the pixel would stand erased. It is important to note that the mouse pointer bit pattern is 32 bytes long. However, while actually writing a program to change the pointer shape we need a 64 byte bit-map. This provision is made to ensure that when the cursor reaches a position on the screen where something is already written or drawn only that portion should get overwritten which is to be occupied by the mouse cursor. Of the 64 bytes the first 32 bytes contain a bit mask which is first ANDed with the screen image, and then the second 32 bytes bit mask is XORed with the screen image. The following program changes the mouse cursor in graphics mode to resemble an hour glass. # include "graphics.h" # include "dos.h" union REGS i, o ; struct SREGS s ; int cursor[32] = { /* Hour-glass screen mask */ 0x0000, 0x0000, 0x0000, 0x0000, 0x8001, 0xc003, 0xf00f, 0xfc3f, 0xfc3f, 0xf00f, 0xc003, 0x8001, 0x0000, 0x0000, 0x0000, 0x0000, /* The mouse pointer bitmap */ 0xffff, 0x8001, 0xffff, 0x8001,

0x4002, 0x2004, 0x1008, 0x0240, 0x0240, 0x0810, 0x2004, 0x4002, 0x8001, 0xffff, 0x8001, 0xffff, }; main( ) { int gd = DETECT, gm ; initgraph ( &gd, &gm, "c:\\tc\\bgi" ) ; if ( initmouse( ) == -1 ) { closegraph( ) ; printf ( "\n Mouse not installed!" ) ; exit( ) ; } gotoxy ( 10, 1 ) ; printf ( "Press any key to exit..." ) ; changecursor ( cursor ) ; showmouseptr( ) ; getch( ) ; } initmouse( ) { i.x.ax = 0 ; int86 ( 0x33, &i, &o ) ; return ( o.x.ax == 0 ? -1 : 0 ) ; } showmouseptr( ) { i.x.ax = 1 ; int86 ( 0x33, &i, &o ) ; } changecursor ( int *shape ) { i.x.ax = 9 ; /* service number */ i.x.bx = 0 ; /* actual cursor position from left */ i.x.cx = 0 ; /* actual cursor position from top */ i.x.dx = ( unsigned ) shape ; /* offset address of pointer image*/ segread ( &s ) ; s.es = s.ds ; /* segment address of pointer */ int86x ( 0x33, &i, &i, &s ) ; } 72. Towers Of Hanoi Suppose there are three pegs labeled A, B and C. Four disks are placed on peg A. The bottom-most disk is largest, and disks go on decreasing in size with the topmost disk being smallest. The objective of the game is to move the disks from peg A to peg C, using peg B as an auxiliary peg. The rules of the game are as follows: Only one disk may be moved at a time, and it must be the top disk on one of the pegs. A larger disk should never be placed on the top of a smaller disk. Suppose we are to write a program to print out the sequence in which the disks should be moved such that all disks on peg A are finally transferred to peg C. Here it is...

main( ) { int n = 4 ; move ( n, 'A', 'B', 'C' ) ; } move ( n, sp, ap, ep ) int n ; char sp, ap, ep ; { if ( n == 1 ) printf ( "\n Move from %c to %c ", sp, ep ) ; else { move ( n - 1, sp, ep, ap ) ; move ( 1, sp, ' ', ep ) ; move ( n - 1, ap, sp, ep ) ; } } And here is the output... Move Move Move Move Move Move Move Move Move Move Move Move Move Move Move from from from from from from from from from from from from from from from A A B A C C A A B B C B A A B to to to to to to to to to to to to to to to B C C B A B B C C A A C B C C

This problem is the famous Towers of Hanoi problem, wherein three pegs are to be employed for transferring the disks with the given criteria. Here's how we go about it. We have three pegs: the starting peg, sp, the auxiliary peg ap, and the ending peg, ep, where the disks must finally be. First, using the ending peg as an auxiliary or supporting peg, we transfer all but the last disk to ap. Next the last disk is moved from sp to ep. Now, using sp as the supporting peg, all the disks are moved from ap to ep. A, B and C denote the three pegs. The recursive function move( ) is called with different combinations of these pegs as starting, auxiliary and ending pegs. -----------------------------------------------------------------------------------------------73. What would be the output of following program?

struct syntax { int i ; float g ; char c ; } main( ) { printf ( "I won't give you any error" ) ; } Ans: The above program would get compiled successfully and on execution it would print the message given in printf(). What strikes in the above code snippet is the structure syntax which is declared but not terminated with the statement terminator, the semicolon. The compiler would not give any error message for it, as it assumes that main( ) function have a return type of struct syntax and hence would successfully compile and execute the program. -----------------------------------------------------------------------------------------------74. How to get the memory size ? Ans: Consider the following program #include <stdio.h> #include <bios.h> main( ) { int memsize; memsize = biosmemory( ) ; printf ( "RAM size = %dK\n",memsize ) ; return 0 ; } The function biosmemory uses BIOS interrupt 0x12 to return the size of memory. -----------------------------------------------------------------------------------------------75. Float Format How does C compiler stores float values ? Ans: In C, the float values are stored in a mantissa and exponent form. While writing a number we specify the exponent part in the form of base 10. But, in case of C compiler, the exponent for floats is stored in the form of base 2. Obviously, because, computer stores the numbers in binary form. The C compiler follows an IEEE standard to store a float. The IEEE format expresses a floating-point number in a binary form known as `normalized' form. Normalization involves adjusting the exponent so that the "binary point" (the binary analog of the decimal point) in the mantissa always lies to the right of most significant nonzero digit. In binary representation, this means that the most significant digit of the mantissa is always a

1. This property of the normalized representation is exploited by the IEEE format when storing the mantissa. Let us consider an example of generating the normalized form of a floating point number. Suppose we want to represent the decimal number 5.375. Its binary equivalent can be obtained as shown below: 2|5 .375 x 2 = 0.750 0 |-----.750 x 2 = 1.500 1 2|21 .500 x 2 = 1.000 1 |-----2|10 |-----|01 Writing remainders in reverse writing whole parts in the same order we get 101 order in which they are obtained we get 011 thus the binary equivalent of 5.375 would be 101.011. The normalized form of this binary number is obtained by adjusting the exponent until the decimal point is to the right of most significant 1. In this case the result is 1.01011 x 22. The IEEE format for floating point storage uses a sign bit, a mantissa and an exponent for representing the power of 2. The sign bit denotes the sign of the number: a 0 represents a positive value and a 1 denotes a negative value. The mantissa is represented in binary. Converting the floating-point number to its normalized form results in a mantissa whose most significant digit is always 1. The IEEE format takes advantage of this by not storing this bit at all. The exponent is an integer stored in unsigned binary format after adding a positive integer bias. This ensures that the stored exponent is always positive. The value of the bias is 127 for floats and 1023 for doubles. Thus, 1.01011 x 22 is represented as shown below: --- --------------- ---------------------------------------------| 0 | 100 0000 1 | 010 1100 0000 0000 0000 0000 | --- ---------------- --------------------------------------------sign bit exponent- mantissa stored in normalized form obtained after adding a bias 127 to exponent 2 Data Structures Which is the best sorting method? Ans: There is no sorting method that is universally superior to all others. The programmer must carefully examine the problem and the desired results before deciding the particular sorting method. Some of the sorting methods are given below: Bubble sort : When a file containing records is to be sorted then Bubble sort is the best sorting method when sorting by address is used. Bsort : It can be recommended if the input to the file is known to be nearly sorted. Meansort : It can be recommended only for input known to be very nearly sorted. Quick Sort : In the virtual memory environment, where pages of data are constantly being swapped back and forth between external and internal storage. In practical

situations, quick sort is often the fastest available because of its low overhead and its average behavior. Heap sort : Generally used for sorting of complete binary tree. Simple insertion sort and straight selection sort : Both are more efficient than bubble sort. Selection sort is recommended for small files when records are large and for reverse situation insertion sort is recommended. The heap sort and quick sort are both more efficient than insertion or selection for large number of data. Shell sort : It is recommended for moderately sized files of several hundred elements. Radix sort : It is reasonably efficient if the number of digits in the keys is not too large. 76. Calculating Wasted Bytes On Disk When a file gets stored on the disk, at a time DOS allocates one cluster for it. A cluster is nothing but a group of sectors. However, since all file sizes cannot be expected to be a multiple of 512 bytes, when a file gets stored often part of the cluster remains unoccupied. This space goes waste unless the file size grows to occupy these wasted bytes. The following program finds out how much space is wasted for all files in all the directories of the current drive. #include <dir.h> #include <dos.h> #include <stdio.h> #include <string.h> #include <stdlib.h> unsigned bytes_per_cluster ; unsigned long wasted_bytes ; unsigned long num_files = 0 ; main( ) { int ptr = 0, flag = 0, first = 0 ; struct ffblk f[50] ; struct dfree free ; /* get cluster information and calculate bytes per cluster */ getdfree ( 0, &free ) ; bytes_per_cluster = free.df_bsec * free.df_sclus ; chdir ( "\\" ) ; /* check out files in root directory first */ cal_waste( ) ; /* loop until all directories scanned */ while ( ptr != -1 ) { /* should I do a findfirst or a findnext? */ if ( first == 0 ) flag = findfirst ( "*.*", &f[ptr], FA_DIREC ) ;

else flag = findnext ( &f[ptr] ) ; while ( flag == 0 ) { /* make sure its a directory and skip over . & .. entries */ if ( f[ptr].ff_attrib == FA_DIREC && f[ptr].ff_name[0] != '.' ) { flag = chdir ( f[ptr].ff_name ) ; /* try changing directories */ if ( flag == 0 ) /* did change dir work? */ { cal_waste( ) ; first = 0 ; /* set for findfirst on next pass */ break ; } } flag = findnext ( &f[ptr] ) ; /* search for more dirs */ } if ( flag != 0 || ptr == 49 ) /* didn't find any more dirs */ { ptr-- ; chdir ( ".." ) ; /* go back one level */ first = 1 ; /* set to findnext on next pass */ } else ptr++ ; } printf ( "There are %lu bytes wasted in %lu files.\n", wasted_bytes, num_files ) ; } cal_waste( ) { int flag = 0 ; long full_cluster ; struct ffblk ff ; /* look for all file types */ flag = findfirst ( "*.*", &ff, FA_RDONLY | FA_HIDDEN | FA_SYSTEM | FA_ARCH ); while ( flag == 0 ) { num_files++ ; full_cluster = ff.ff_fsize / bytes_per_cluster * bytes_per_cluster ; wasted_bytes += bytes_per_cluster - ( ff.ff_fsize - full_cluster ) ; flag = findnext ( &ff ) ; } } Data Structures Polish Notation The method of writing all operators either before their operation, or after them, is called Polish notation, in honor of its discoverer, the Polish mathematician Jan

Lukasiewicz. When the operators are written before their operands, it is called the prefix form. When the operators come after their operands. It is called the postfix form, or, sometimes reverse Polish form or suffix form. In this context, it is customary to use the coined phrase infix form to denote the usual custom of writing binary operators between their operands. For example, the expression A + B becomes +AB in prefix form and AB+ in postfix form. In the expression A + B x C, the multiplication is done first, so we convert it first, obtaining first A + ( BCx ) and then ABCx+ in postfix form. The prefix form of this expression is +A x BC. The prefix and postfix forms are not related by taking mirror images or other such simple transformation. Also all parentheses have been omitted in the Polish forms. -----------------------------------------------------------------------------------------------77. The Longjmp And Setjmp The C programming language does not let you nest functions. You cannot write a function definition inside another function definition, as in: int fun1( ) { int fun2() /* such nesting of functions is not allowed */ { ..... } } Because of this restriction it is not possible to hide function names inside a hierarchy. As a result all the functions that you declare within a program are visible to each other. This of course is not a major drawback since one can limit visibility by grouping functions within separate C source files that belong to different logical units of the program. C does, however, suffer in another way because of this design decision. It provides no easy way to transfer control out of a function except by returning to the expression that called the function. For the vast majority of function calls, that is a desirable limitation. You want the discipline of nested function calls and returns to help you understand flow of control through a program. Nevertheless, on some occasions that discipline is too restrictive. The program is sometimes easier to write, and to understand, if you can jump out of one or more function invocations at a single stroke. You want to bypass the normal function returns and transfer control to somewhere in an earlier function invocation. For example, you may want to return to execute some code for error recovery no matter where an error is detected in your application. The setjmp and the longjmp functions provide the tools to accomplish this. The setjmp function saves the "state" or the "context" of the process and the longjmp uses the saved context to revert to a previous point in the program. What is the context of the process? In general, the context of a process refers to information that enables you to reconstruct exactly the way the process is at a particular point in its flow of execution. In C program the relevant information includes quantities such as values of SP, SS, FLAGS, CS, IP, BP, DI, ES, SI and DS registers. To save this information Turbo C uses the following structure, which is defined, in the header file 'setjmp.h'.

typedef struct { unsigned j_sp ; unsigned j_ss ; unsigned j_flag ; unsigned j_cs ; unsigned j_ip ; unsigned j_bp ; unsigned j_di ; unsigned j_es ; unsigned j_si ; unsigned j_ds ; } jmp_buf[1] ; This is a system-dependent data type because different systems might require different amounts of information to capture the context of a process. In Turbo C, jmp_buf is simply an array of ten 2-byte integers. To understand the mechanics of setjmp and longjmp, look at the following code fragment. #include "setjmp.h" jmp_buf buf ; main( ) { if ( setjmp ( buf ) == 0 ) process( ) ; else handle_error( ) ; /* executed when longjmp is called */ } process( ) { int flag = 0 ; /* some processing is done here */ /* if an error occurs during processing flag is set up */ if ( flag ) longjmp ( buf, 1 ) ; } Upon entry to setjmp the stack contains the address of the buffer buf and the address of the if statement in the main function, to which setjmp will return. The setjmp function copies this return address as well as the current values of registers, SP, SS, FLAGS, BP, DI, ES, SI and DS, into the buffer buf. Then setjmp returns with a zero. In this case, the if statement is satisfied and the process( ) function is called. If something goes wrong in process( ) (indicated by the flag variable), we call longjmp with two arguments: the first is the buffer that contains the context to which we will return. When the stack reverts back to this saved state, and the return statement in longjmp is executed, it will be as if we were returning from the call to setjmp, which originally saved the buffer buf. The second argument to longjmp specifies the return value to be used during this return. It should be other than zero so that in the if statement we can tell whether the return is induced by a longjmp. The setjmp/longjmp combination enables you to jump unconditionally from one C function to another without using the conventional return statements. Essentially, setjmp marks the destination of the jump and longjmp is a non-local goto that

executes the jump. Data Structures Comparison Trees... The comparison trees also called decision tree or search tree of an algorithm, is obtained by tracing through the actions of the algorithm, representing each comparison of keys by a vertex of the tree (which we draw as a circle). Inside the circle we put the index of the key against which we are comparing the target key. Branches (lines) drawn down from the circle represent the possible outcomes of the comparison and are labeled accordingly. When the algorithm terminates, we put either F (for failure) or the location where the target is found at the end of the appropriate branch, which we call a leaf, and draw as a square. Leaves are also sometimes called end vertices or external vertices of the tree. The remaining vertices are called the internal vertices of the tree. The comparison tree for sequential search is especially simple. -----------------------------------------------------------------------------------------------78. Suppose we have a floating-point number with higher precision say 12.126487687 and we wish it to be printed with only precision up to two decimal places. How can I do this? Ans. This can achieved through the use of suppression char '*' in the format string of printf( ) which is shown in the following program. main( ) { int p = 2 ; float n = 12.126487687 ; printf ( "%.*f",p, n ) ; } -----------------------------------------------------------------------------------------------79. Spawning All programs that we execute from DOS prompt can be thought of as children of COMMAND.COM. Thus, the program that we execute is a child process, whereas COMMAND.COM running in memory is its parent. The process of a parent process giving birth to a child process is known as 'spawning'. If the spawned program so desires, it may in turn spawn children of its own, which then execute and return control to their parent. Who is the parent of COMMAND.COM? COMMAND.COM itself. We can trace the ancestors of our program using the field Parent Process ID (PID) present at offset 0x16 in the Program Segment Prefix (PSP). To trace this ancestry our program should first locate its PSP, extract the parent process ID from it and then use this to find PSP of the parent. This process can be repeated till we reach COMMAND.COM (process ID of COMMAND.COM is its own PSP), the father of all processes. Here is a program which achieves this... /* SPAWN.C */ #include "dos.h"

unsigned oldpsp, newpsp, far *eb_seg, i ; char far *eb_ptr ; main( ) { oldpsp = _psp ; while ( 1 ) { printf ( "\n" ) ; printname ( oldpsp ) ; printf ( " spawned by " ) ; newpsp = * ( ( unsigned far * ) MK_FP ( oldpsp, 0x16 ) ) ; if ( * ( ( unsigned * ) MK_FP ( newpsp, 0x16 ) ) == newpsp ) break ; else oldpsp = newpsp ; printname ( newpsp ) ; } printf ( "%-20s (%04X)", "COMMAND.COM", newpsp ) ; } printname ( unsigned lpsp ) { char drive[5], dir[68], name[13], ext[5] ; eb_seg = ( unsigned far * ) MK_FP ( lpsp, 0x2C ) ; eb_ptr = MK_FP ( *eb_seg, 0 ) ; i=0; while ( 1 ) { if ( eb_ptr[i] == 0 ) { if ( eb_ptr[i + 1] == 0 && eb_ptr[i + 2] == 1 ) { i += 4 ; break ; } } i++ ; } fnsplit ( eb_ptr + i, drive, dir, name, ext ) ; strcat ( name, ext ) ; printf ( "%-20s (%04X)", name, oldpsp ) ; }

On running the program from within TC the output obtained is shown below. SPWAN.EXE (58A9) spawned by TC.EXE (0672) TC.EXE (0672) spawned by COMMAND.COM (05B8). The program simply copies its own process ID in the variable oldpsp and then uses it to extract its own filename from its environment block. This is done by the function printname( ). The value in oldpsp is then used to retrieve the parent's PID in newpsp. From there the program loops reporting the values of oldpsp, newpsp and the corresponding file names until the program reaches COMMAND.COM. The printname( ) function first locates the environment block of the program and then extracts the file name from the environment block. The fnsplit( ) function has been used to eliminate the path present prior to the file name. Do not run the program from command line since it would give you only one level of ancestry. Data Structures Choosing the data structures to be used for information retrieval. For problems of information retrieval, consider the size, number, and location of the records along with the type and structure of the keys while choosing the data structures to be used. For small records, high-speed internal memory will be used, and binary search trees will likely prove adequate. For information retrieval from disk files, methods employing multiway branching, such as trees, B-trees , and hash tables, will usually be superior. Tries are particularly suited to applications where the keys are structured as a sequence of symbols and where the set of keys is relatively dense in the set of all possible keys. For other applications, methods that treat the key as a single unit will often prove superior. B-trees, together with various generalization and extensions, can be usefully applied to many problems concerned with external information retrieval. 80. Variably Dimensioned Arrays While dealing with Scientific or Engineering problems one is often required to make use of multi-dimensioned array. However, when it comes to passing multidimensional arrays to a function C is found wanting. This is because the C compiler wants to know the size of all but the first dimension of any array passed to a function. For instance, we can define a function compute ( int n, float x[] ), but not compute ( int n, x[][]). Thus, C can deal with variably dimensioned 1-D arrays, but when an array has more than one dimension, the C compiler has to know the size of the last dimensions expressed as a constant. This problem has long been recognized, and some of the solutions that are often used are: Declare the arrays in the functions to be big enough to tackle all possible situations. This can lead to a wastage of lot of precious memory in most cases. Another solution is to construct multiple-dimension array as an array of pointers. For example, a matrix (2-D array) of floats can be declared as a 1-D array of float pointers, with each element pointing to an array of floats. The problem with this method is that the calling function has to define all arrays in this fashion. This means that any other computations done on the arrays must take this special structure into account.

Another easy solution, though seldom used, exists. This is based on the following method: Pass the array to the function as though it is a pointer to an array of floats (or the appropriate data type), no matter how many dimensions the array actually has, along with the dimensions of the array. Reference individual array elements as offsets from this pointer. Write your algorithm so that array elements are accessed in storage order. The following program for multiplying two matrices illustrates this procedure. # define M 3 # define N 2 # define P 4 float a[M][N], b[N][P], c[M][P] ; void mulmat ( int, int, int, float*, float*, float* ) ; main( ) { int i, j ; for ( i = 0 ; i < M ; i++ ) for ( j = 0 ; j < N ; j++ ) a[i][j] = i + j ; for ( i = 0 ; i < N ; i++ ) for ( j = 0 ; j < P ; j++ ) b[i][j] = i + j ; mulmat ( M, N, P, a, b, c ) ; for ( i = 0 ; i < M ; i++ ) { printf ( "\n" ) ; for ( j = 0 ; j < P ; j++ ) printf ( "%f\t", c[i][j] ) ; } } void mulmat ( int m, int n, int p, float *a, float *b, float *c ) { float *ptrtob, *ptrtoc ; int i, j, k, nc ; /* set all elements of matrix c to 0 */ for ( i = 0 ; i < m * p ; i++ ) *( c + i ) = 0 ; for ( i = 0 ; i < m ; i++ ) { ptrtob = b ; for ( k = 0 ; k < n ; k++ ) { ptrtoc = c ;

for ( j = 0 ; j < p ; j++ ) *ptrtoc++ += *a * *ptrtob++ ; a++ ; } c += p ; } } We know that C stores array elements in a row-major order. Hence to ensure that the elements are accessed in the storage order the above program uses a variation of the normal matrix-multiplication procedure. The pseudo code for this is given below: for i = 1 to m for j = 1 to p c[i][j] = 0 end for k = 1 to n for j = 1 to p c[i][j] = c[i][j] + a[i][k] * b[k][j] end end end -----------------------------------------------------------------------------------------------81. Why is it not possible to scan strings from keyboard in case of array of pointers to string? Ans: When an array is declared, dimension of array should be specified so that compiler can allocate memory for the array. When array of pointers to strings is declared its elements would contain garbage addresses. These addresses would be passed to scanf( ). So strings can be received but they would get stored at unkown locations. This is unsafe. -----------------------------------------------------------------------------------------------82. Bit Arrays If in a program a variable is to take only two values 1 and 0, we really need only a single bit to store it. Similarly, if a variable is to take values from 0 to 3, then two bits are sufficient to store these values. And if a variable is to take values from 0 through 7, then three bits will be enough, and so on. Why waste an entire integer when one or two or three bits will do? Because there aren't any one bit or two bit or three bit data types available in C. However, when there are several variables whose maximum values are small enough to pack into a single memory location, we can use `bit fields' to store several values in a single integer. Bit fields are discussed in most standard C texts. They are usually used when we want to store assorted information which can be accommodated in 1, 2, 3 bits etc. For example, the following data about an employee can be easily stored using bit fields.

male or female single, married, divorced or widowed have one of the eight different hobbies can choose from any of the fifteen different schemes proposed by the company to pursue his/her hobby. This means we need one bit to store gender, two to store marital status, three for hobby, and four for scheme (with one value used for those who are not desirous of availing any of the schemes). We need ten bits altogether, which means we can pack all this information into a single integer, since an integer is 16 bits long. At times we may need to store several True or False statuses. In such cases instead of using bit fields using an array of bits would be more sensible. On this array we may be required to perform the following operations: Set a bit (make it 1). Clear a bit (make it 0). Test the status of a bit in the array. Reach the appropriate bit slot in the array. Generate a bit mask for setting and clearing a bit. We can implement these operations using macros given below: #define #define #define #define #define #define #define CHARSIZE 8 MASK ( y ) ( 1 << y % CHARSIZE ) BITSLOT ( y ) ( y / CHARSIZE ) SET ( x, y ) ( x[BITSLOT( y )] |= MASK( y ) ) CLEAR ( x, y ) ( x[BITSLOT( y )] &= ~MASK( y ) ) TEST ( x, y ) ( x[BITSLOT( y )] & MASK( y ) ) NUMSLOTS ( n ) ( ( n + CHARSIZE - 1) / CHARSIZE )

Using these macros we can declare an array of 50 bits be saying, char arr[NUMSLOTS(50)] ; To set the 20th bit we can say, SET(arr, 20 ) ; And if we are to test the status of 40th bit we may say, if ( TEST ( arr, 40 ) ) Using bit arrays often results into saving a lot of precious memory. For example, the following program which implements the Sieve of Eratosthenes for generating prime numbers smaller than 100 requires only 13 bytes. Had we implemented the same logic using an array of integers we would have required an array of 100 integers, that is 200 bytes. #include <stdio.h> #include <string.h> #define MAX 100 main( ) {

char arr[NUMSLOTS( MAX )] ; int i, j ; memset ( arr, 0, NUMSLOTS( MAX ) ) ; for ( i = 2 ; i < MAX ; i++ ) { if ( !TEST ( arr, i ) ) { printf ( "\n%d", i ) ; for ( j = i + i ; j < MAX ; j += i ) SET ( arr, j ) ; } } } -----------------------------------------------------------------------------------------------83. Information Hiding in C Though C language doesn't fully support encapsulation as C++ does, there is a simple technique through which we can implement encapsulation in C. The technique that achieves this is modular programming in C. Modular programming requires a little extra work from the programmer, but pays for itself during maintenance. To understand this technique let us take the example of the popular stack data structure. There are many methods of implementing a stack (array, linked list, etc.). Information hiding teaches that users should be able to push and pop the stack's elements without knowing about the stack's implementation. A benefit of this sort of information hiding is that users don't have to change their code even if the implementation details change. Consider the following scenario: To be able to appreciate the benefits of modular programming and thereby information hiding, would first show a traditional implementation of the stack data structure using pointers and a linked list of structures. The main( ) function calls the push( ) and pop( ) functions. #include <alloc.h> typedef int element ; void initialize_stack ( struct node ** ) ; void push ( struct node **, element ) ; element pop ( struct node * ) ; int isempty ( struct node * ) ; struct node { element data ; struct node *next ; }; void main( ) { struct node *top ; element num ;

initialize_stack ( &top ) ; push ( &top, 10 ) ; push ( &top, 20 ) ; push ( &top, 30 ) ; if ( isempty ( top ) ) printf ( "\nStack is empty" ) ; else { num = pop ( top ) ; printf ( "\n Popped %d", num ) ; } } void initialize_stack ( struct node **p ) { *p = NULL ; } void push ( struct node **p, element n ) { struct node *r ; r = ( struct node *) malloc ( sizeof ( struct node ) ) ; r -> data = n ; if ( *p == NULL ) r -> next = NULL ; else r -> next = *p ; *p = r ; } element pop ( struct node *p ) { element n ; struct node *r ; n = p -> data ; r=p; p = p -> next ; free ( r ) ; return ( n ) ; } int isempty ( struct node *p ) { if ( p == NULL ) return ( -1 ) ; else return ( 0 ) ; } Notice how the specific implementation of the data structure is strewn throughout main( ). main( ) must see the definition of the structure node to use the push( ), pop( ), and other stack functions. Thus the implementation is not hidden, but is mixed with the abstract operations. Data Structures Radix Sort

This sorting technique is based on the values of the actual digits in the positional representations of the numbers being sorted. Using the decimal base, for example, where the radix is 10, the numbers can be partitioned into ten groups on the sorter. For example, to sort a collection of numbers where each number is a four-digit number, then, All the numbers are first sorted according to the the digit at unit's place. In the second pass, the numbers are sorted according to the digit at tenth place. In the third pass, the numbers are sorted according to the digit at hundredth place. In the forth and last pass, the numbers are sorted according to the digit at thousandth place. During each pass, each number is taken in the order in which it appears in partitions from unit's place onwards. When these actions have been performed for each digit, starting with the least significant and ending with most significant, the numbers are sorted. This sorting method is called the radix sort. Let us take another example. Suppose we have a list of names. To sort these names using radix sort method we will have to classify them into 26 groups The list is first sorted on the first letter of each name, i.e. the names are arranged in 26 classes, where the first class consists of those names that begin with alphabet 'A', the second class consists of those names that begin with alphabet 'B' and so on. During the second pass each class is alphabetized according to the second letter of the name, and so on. 84. Exception Handling in C Consider the following program: #include <math.h> void main( ) { float i ; i = pow ( -2, 3 ) ; printf ( "%f", i ) ; } int matherr ( struct exception *a ) { if ( a -> type == DOMAIN ) { if ( !strcmp ( a -> name, "pow" ) ) { a -> retval = pow ( - ( a -> arg1 ), a -> arg2 ) ; return 1 ; } } return 0 ; } If we pass a negative value in pow( ) function a run time error occurs. If we wish to get the proper output even after passing a negative value in the pow( ) function we

must handle the run time error. For this, we can define a function matherr( ) which is declared in the 'math.h' file. In this function we can detect the run-time error and write our code to correct the error. The elements of the exception structure receives the function name and arguments of the function causing the exception. Data Structures AVL Trees For ideal searching in a binary search tree, the heights of the left and right sub-trees of any node should be equal. But, due to random insertions and deletions performed on a binary search tree, it often turns out to be far from ideal. A close approximation to an ideal binary search tree is achievable if it can be ensured that the difference between the heights of the left and the right sub trees of any node in the tree is at most one. A binary search tree in which the difference of heights of the right and left sub-trees of any node is less than or equal to one is known as an AVL tree. AVL tree is also called as Balanced Tree. The name "AVL Tree" is derived from the names of its inventors who are Adelson-Veilskii and Landi. A node in an AVL tree have a new field to store the "balance factor" of a node which denotes the difference of height between the left and the right sub-trees of the tree rooted at that node. And it can assume one of the three possible values {-1,0,1}. -----------------------------------------------------------------------------------------------85. Unique combinations for a given number How do I write a program which can generate all possible combinations of numbers from 1 to one less than the given number ? main( ) { long steps, fval, bstp, cnt1 ; int num, unit, box[2][13], cnt2, cnt3, cnt4 ; printf ( "Enter Number " ) ; scanf ( "%d", &num ) ; num = num < 1 ? 1 : num > 12 ? 12 : num ; for ( steps = 1, cnt1 = 2 ; cnt1 <= num ; steps *= cnt1++ ) ; for ( cnt1 = 1 ; cnt1 <= steps ; cnt1++ ) { for ( cnt2 = 1 ; cnt2 <= num ; cnt2++ ) box[0][cnt2] = cnt2 ; for ( fval = steps, bstp = cnt1, cnt2 = 1 ; cnt2 <= num ; cnt2++ ) { if ( bstp == 0 ) { cnt4=num ; while ( box[0][cnt4] == 0 ) cnt4-- ; } else { fval /= num - cnt2 + 1 ;

unit = ( bstp + fval - 1 ) / fval ; bstp %= fval ; for ( cnt4 = 0, cnt3 = 1 ; cnt3 <= unit ; cnt3++ ) while ( box[0][++cnt4] == 0 ) ; } box[1][cnt2] = box[0][cnt4] ; box[0][cnt4] = 0 ; } printf ( "\nSeq.No.%ld:", cnt1 ) ; for ( cnt2 = 1 ; cnt2 <= num ; cnt2++ ) printf ( " %d", box[1][cnt2] ) ; } } This program computes the total number of steps. But instead of entering into the loop of the first and last combination to be generated it uses a loop of 1 to number of combinations. For example, in case of input being 5 the number of possible combinations would be factorial 5, i.e. 120. The program suffers from the limitation that it cannot generate combinations for input beyond 12 since a long int cannot handle the resulting combinations. Data Structures Hashing... Hashing or hash addressing is a searching technique. Usually, search of an element is carried out via a sequence of comparisons. Hashing differs from this as it is independent of the number of elements n in the collection of data. Here, the address or location of an element is obtained by computing some arithmetic function. Hashing is usually used in file management. The general idea is of using the key to determine the address of a record. For this, a function fun( ) is applied to each key, called the hash function. Some of the popular hash functions are: 'Division' method, 'Midsquare' method, and 'Folding' method. Two records cannot occupy the same position. Such a situation is called a hash collision or a hash clash. There are two basic methods of dealing with a hash clash. The first technique, called rehashing, involves using secondary hash function on the hash key of the item. The rehash function is applied successively until an empty position is found where the item can be inserted. If the hash position of the item is found to be occupied during a search, the rehash function is again used to locate the item. The second technique, called chaining, builds a linked list of all items whose keys hash to the same values. During search, this short linked list is traversed sequentially for the desired key. This technique involves adding an extra link field to each table position. -----------------------------------------------------------------------------------------------86. The following program demonstrates how to get input from the user in graphics mode, echoed in the current colors and font size and font style. #define ON 1 #define OFF 0 #include <graphics.h> main( )

{ char nameString[80], ageString[80] ; int age, gd = DETECT, gm ; initgraph ( &gd, &gm, "c:\\tc\\bgi" ) ; setbkcolor ( BLUE ) ; setcolor ( YELLOW ) ; settextstyle ( GOTHIC_FONT, HORIZ_DIR, 0 ) ; moveto ( 0, 0 ) ; outtext ( "Enter your name: " ) ; getGrString ( nameString ) ; moveto ( 0, gety( ) + textheight ( "A" ) ) ; outtext ( "Name: " ) ; outtext ( nameString ) ; moveto ( 0, gety( ) + textheight ( "A" ) ) ; outtext ( "Press key to exit! " ) ; getch( ) ; closegraph( ) ; restorecrtmode( ) ; } getGrString ( char *inputString ) { int stringIndex = 0, oldColor ; char ch, outString[2] ; /* xVal will store the screen position for each char */ int xVal[255] ; outString[1] = 0 ; xVal[0] = getx( ) ; do { cursor ( ON ) ; ch = getch( ) ; cursor ( OFF ) ; if ( ch == 0 ) /* avoid dealing with all special keys */ getch( ) ; else { if ( ch == 8 ) /* backspace */ { oldColor = getcolor( ) ; --stringIndex ; if ( stringIndex < 0 ) stringIndex = 0 ; /* move to ( old horz position, current vert position ) */ moveto ( xVal[stringIndex], gety( ) ) ; setcolor ( getbkcolor( ) ) ; outString[0] = inputString[stringIndex] ; outtext ( outString ) ; moveto ( xVal [stringIndex], gety( ) ) ; setcolor ( oldColor ) ; } else { inputString[stringIndex] = ch ;

outString[0] = ch ; outtext ( outString ) ; ++stringIndex ; xVal[stringIndex] = getx( ) ; } } } while ( ch != 13 && ch != 10 ) ; inputString[stringIndex] = 0 ; } cursor ( int on ) { int curX, oldColor ; /* we'll use an underscore as a cursor */ char uBarStr[2] = { '_', 0 } ; if ( !on ) { oldColor = getcolor( ) ; setcolor ( getbkcolor( ) ) ; } /* save horizontal position before drawing cursor */ curX = getx( ) ; outtext ( uBarStr ) ; moveto ( curX, gety( ) ) ; /* if we changed the color to erase cursor, change it back */ if ( !on ) setcolor ( oldColor ) ; } The function getGrString( ) echoes graphically the user input and stores it in a buffer, and the function cursor( ) handles the cursor position. System Utility What is garbage collection? Ans: Suppose some memory space becomes reusable because a node is released from a linked list. Hence, we want the space to be available for future use. One way to bring this about is to immediately reinsert the space into the free-storage list. However, this method may be too time-consuming for the operating system. The operating system may periodically collect all the deleted space onto the free-storage list. The technique that does this collection is called Garbage Collection. Garbage Collection usually takes place in two steps: First the Garbage Collector runs through all lists, tagging whose cells are currently in use, and then it runs through the memory, collecting all untagged space onto the free-storage list. The Garbage Collection may take place when there is only some minimum amount of space or no space at all left in the free-storage list, or when the CPU is idle and has time to do the collection. Generally speaking, the Garbage Collection is invisible to the programmer.

87.

How do I get the time elapsed between two function calls ? Ans: The function difftime( ) finds the difference between two times. It calculates the elapsed time in seconds and returns the difference between two times as a double value. #include <time.h> #include <stdio.h> #include <dos.h> main( ) { int a[] = { 2, -34, 56, 78, 112, 33, -7, 11, 45, 29, 6 } ; int s ; time_t t1, t2 ; // time_t defines the value used for time function s = sizeof ( a ) / 2 ; t1 = time ( NULL ) ; sel_sort ( a, s ) ; // sort array by selection sort bub_sort ( a, s ) ; // sort array by bubble sort method t2 = time ( NULL ) ; printf ( "\nThe difference between two function calls is %f", difftime ( t2, t1 ) ) ; } In the above program we have called difftime( ) function that returns the time elapsed from t1 to t2. -----------------------------------------------------------------------------------------------88. General main( ) { char *s ; s = fun ( 128, 2 ) ; printf ( "\n%s", s ) ; } fun ( unsigned int num, int base ) { static char buff[33] ; char *ptr ; ptr = &buff [ sizeof ( buff ) - 1 ] ; *ptr = '\0' ; do { *--ptr = "0123456789abcdef"[ num % base ] ; num /= base ; } while ( num != 0 ) ; return ptr ; } The above program would convert the number 128 to the base 2. You can convert a

number to a hexadecimal or octal form by passing the number and the base, to the function fun( ). Data Structures What is a priority queue? Ans: As we know in a stack, the latest element is deleted and in a queue the oldest element is deleted. It may be required to delete an element with the highest priority in the given set of values and not only the oldest or the newest one. A data structure that supports efficient insertions of a new element and deletions of elements with the highest priority is known as priority queue. There are two types of priority queues: an ascending priority queue is a collection of items into which items can be inserted arbitrarily and from which only the smallest item can be removed. A descending order priority queue is similar but allows only the largest item to be deleted. -----------------------------------------------------------------------------------------------89. What is the difference between const char *p, char const *p, and char* const p ? 'const char *p' and 'char const *p' are the same, i.e. p points to a constant character. On the other hand, 'char* const p' means p is a constant pointer pointing to a character which means we cannot change the pointer p but we can change the character which p is pointing to. -----------------------------------------------------------------------------------------------90. What's the difference between a null pointer, a NULL macro, the ASCII NUL character and a null string? Ans: A null pointer is a pointer which doesn't point anywhere. A NULL macro is used to represent the null pointer in source code. It has a value 0 associated with it. The ASCII NUL character has all its bits as 0 but doesn't have any relationship with the null pointer. The null string is just another name for an empty string "". System Utility Sparse Matrix... A sparse matrix is one where most of its elements are zero. There is no precise definition as to know whether a matrix is sparsed or not, but it is a concept which we all can recognize intuitively. The natural method of representing matrices in memory as two-dimensional arrays may not be suitable for sparse matrices. That is one may save space by storing only those entries which may be nonzero. If this is done, then the matrix may be thought of as an ordered list of non-zero elements only. Information about a non-zero element has three parts: an integer representing its row, an integer representing its column and the data associated with this element.

That is, each element of a matrix is uniquely characterized by its row and column position, say i, j. We might store that matrix as a list of 3-tuples of the form (i, j, data), as shown below, Although the non-zero elements may be stored in the array in any order, keeping them ordered in some fashion may be advantageous for further processing. Note that above array is arranged in increasing order of the row number of non-zero elements. Moreover, for elements in the same row number, the array is arranged in order of increasing column number. -----------------------------------------------------------------------------------------------91. Pointers What does the error "Null Pointer Assignment" mean and what causes this error? Ans: The Null Pointer Assignment error is generated only in small and medium memory models. This error occurs in programs which attempt to change the bottom of the data segment. In Borland's C or C++ compilers, Borland places four zero bytes at the bottom of the data segment, followed by the Borland copyright notice "Borland C++ - Copyright 1991 Borland Intl.". In the small and medium memory models, a null pointer points to DS:0000. Thus assigning a value to the memory referenced by this pointer will overwrite the first zero byte in the data segment. At program termination, the four zeros and the copyright banner are checked. If either has been modified, then the Null Pointer Assignment error is generated. Note that the pointer may not truly be null, but may be a wild pointer that references these key areas in the data segment. Data Structures How to build an expression trees ? Ans: An expression tree is a binary tree which is built from simple operands and operators of an (arithmetic or logical ) expression by placing simple operands as the leaves of a binary tree and the operators as the interior nodes. If an operator is binary , then it has two nonempty subtrees, that are its left and right operands (either simple operands or sub expressions). If an operator is unary, then only one of its subtrees is nonempty, the one on the left or right according as the operator is written on the right or left of its operand. We traditionally write some unary operators to the left of their operands, such as "-" ( unary negation) or the standard functions like log( ), sin( ) etc. Others are written on the right, such as the factorial function ()!. If the operator is written on the left, then in the expression tree we take its left subtree as empty. If it appears on the right, then its right subtree will be empty. An example of an expression tree is shown below for the expression ( -a < b ) or ( c + d ) . -----------------------------------------------------------------------------------------------92. Can we get the remainder of a floating point division ?

Ans : Yes. Although the % operator fails to work on float numbers we can still get the remainder of floating point division by using a function fmod( ). The fmod( ) function divides the two float numbers passed to it as parameters and returns the remainder as a floating-point value. Following program shows fmod( ) function at work. #include <math.h> main( ) { printf ( "%f", fmod ( 5.15, 3.0 ) ) ; } The above code snippet would give the output as 2.150000. -----------------------------------------------------------------------------------------------93. How to extract the integer part and a fractional part of a floating point number? Ans: C function modf( ) can be used to get the integer and fractional part of a floating point. #include "math.h" main( ) { double val, i, f ; val = 5.15 ; f = modf ( val, &i ) ; printf ( "\nFor the value %f integer part = %f and fractional part = %f", val, i, f ) ; } The output of the above program will be: For the value 5.150000 integer part = 5.000000 and fractional part = 0.150000 94. How do I define a pointer to a function which returns a char pointer? Ans: char * ( *p )( ) ; or typedef char * ( * ptrtofun )( ) ; ptrtofun p ; Here is a sample program which uses this definition. main( ) { typedef char * ( * ptrtofun ) ( ) ; char * fun( ) ;

ptrtofun fptr ; char *cptr ; fptr = fun ; cptr = (*fptr) ( ) ; printf ( "\nReturned string is \"%s\"", cptr ) ; } char * fun( ) { static char s[ ] = "Hello!" ; printf ( "\n%s", s ) ; return s ; } -----------------------------------------------------------------------------------------------95. What's wrong with the following declaration: char* ptr1, ptr2 ; get errors when I try to use ptr2 as a pointer. Ans: char * applies only to ptr1 and not to ptr2. Hence ptr1 is getting declared as a char pointer, whereas, ptr2 is being declared merely as a char. This can be rectified in two ways : char *ptr1, *ptr2 ; typedef char* CHARPTR ; CHARPTR ptr1, ptr2 ; -----------------------------------------------------------------------------------------------96. How to use scanf( ) to read the date in the form of dd-mm-yy? Ans: To read the date in the form of dd-mm-yy one possible way is, int dd, mm, yy ; char ch ; /* for char '-' */ printf ( "\nEnter the date in the form of dd-mm-yy : " ) ; scanf( "%d%c%d%c%d", &dd, &ch, &mm, &ch, &yy ) ; Another way is to use suppression character * is as follows: int dd, mm, yy ; scanf( "%d%*c%d%*c%d", &dd, &mm, &yy ) ; The suppression character '*' suppresses the input read from the standard input buffer for the assigned control character. -----------------------------------------------------------------------------------------------97. Why the output of sizeof ( 'a' ) is 2 and not 1 ? Ans: Character constants in C are of type int, hence sizeof ( 'a' ) is equivalent to sizeof ( int ), i.e. 2. Hence the output comes out to be 2 bytes. -----------------------------------------------------------------------------------------------98.

Can we use scanf( ) function to scan a multiple words string through keyboard? Ans: Yes. Although we usually use scanf( ) function to receive a single word string and gets( ) to receive a multi-word string from keyboard we can also use scanf( ) function for scanning a multi-word string from keyboard. Following program shows how to achieve this. main( ) { char buff[15] ; scanf ( "%[^\n]s", buff ) ; puts ( buff ) ; } In the scanf( ) function we can specify the delimiter in brackets after the ^ character. We have specified '\n' as the delimiter. Hence scanf( ) terminates only when the user hits Enter key. -----------------------------------------------------------------------------------------------99. How to set the system date through a C program ? Ans: We can set the system date using the setdate( ) function as shown in the following program. The function assigns the current time to a structure date. #include "stdio.h" #include "dos.h" main( ) { struct date new_date ; new_date.da_mon = 10 ; new_date.da_day = 14 ; new_date.da_year = 1993 ; setdate ( &new_date ) ; } -----------------------------------------------------------------------------------------------100. How can I write a general-purpose swap without using templates? Ans: Given below is the program which uses the stringizing preprocessor directive ## for building a general purpose swap macro which can swap two integers, two floats, two chars, etc. #define swap( a, b, t ) ( g ## t = ( a ), ( a ) = ( b ), ( b ) = g ## t ) int gint; char gchar;

float gfloat ; main( ) { int a = 10, b = 20 ; char ch1 = 'a' , ch2 = 'b' ; float f1 = 1.12, f2 = 3.14 ; swap ( a, b, int ) ; printf ( "\na = %d b = %d", a, b ) ; swap ( ch1, ch2, char ) ; printf ( "\nch1 = %c ch2 = %c", ch1, ch2 ) ; swap ( f1, f2, float ) ; printf ( "\nf1 = %4.2f f2 = %4.2f", f1, f2 ) ; } swap ( a, b, int ) would expand to, ( gint = ( a ), ( a ) = ( b ), ( b ) = gint ) -----------------------------------------------------------------------------------------------101. What is a heap ? Ans : Heap is a chunk of memory. When in a program memory is allocated dynamically, the C run-time library gets the memory from a collection of unused memory called the heap. The heap resides in a program's data segment. Therefore, the amount of heap space available to the program is fixed, and can vary from one program to another.

102. How to obtain a path of the given file? Ans: The function searchpath( ) searches for the specified file in the subdirectories of the current path. Following program shows how to make use of the searchpath( ) function. #include "dir.h" void main ( int argc, char *argv[] ) { char *path ; if ( path = searchpath ( argv[ 1 ] ) ) printf ( "Pathname : %s\n", path ) ; else printf ( "File not found\n" ) ; } -----------------------------------------------------------------------------------------------103. Can we get the process identification number of the current program?

Ans: Yes! The macro getpid( ) gives us the process identification number of the program currently running. The process id. uniquely identifies a program. Under DOS, the getpid( ) returns the Program Segment Prefix as the process id. Following program illustrates the use of this macro. #include <stdio.h> #include <process.h> void main( ) { printf ( "The process identification number of this program is %X\n", getpid( ) ) ; } ------------------------------------------------------------------------------------------------

104. How do I write a function that takes variable number of arguments? Ans: The following program demonstrates this. #include <stdio.h> #include <stdarg.h> void main( ) { int i = 10 ; float f = 2.5 ; char *str = "Hello!" ; vfpf ( "%d %f %s\n", i, f, str ) ; vfpf ( "%s %s", str, "Hi!" ) ; } void vfpf ( char *fmt, ... ) { va_list argptr ; va_start ( argptr, fmt ) ; vfprintf ( stdout, fmt, argptr ) ; va_end ( argptr ) ; } Here, the function vfpf( ) has called vfprintf( ) that take variable argument lists. va_list is an array that holds information required for the macros va_start and va_end. The macros va_start and va_end provide a portable way to access the variable argument lists. va_start would set up a pointer argptr to point to the first of the variable arguments being passed to the function. The macro va_end helps the called function to perform a normal return. -----------------------------------------------------------------------------------------------

-105. Can we change the system date to some other date? Ans: Yes, We can! The function stime( ) sets the system date to the specified date. It also sets the system time. The time and date is measured in seconds from the 00:00:00 GMT, January 1, 1970. The following program shows how to use this function. #include <stdio.h> #include <time.h> void main( ) { time_t tm ; int d ; tm = time ( NULL ) ; printf ( "The System Date : %s", ctime ( &tm ) ) ; printf ( "\nHow many days ahead you want to set the date : " ) ; scanf ( "%d", &d ) ; tm += ( 24L * d ) * 60L * 60L ; stime ( &tm ) ; printf ( "\nNow the new date is : %s", ctime ( &tm ) ) ; } In this program we have used function ctime( ) in addition to function stime( ). The ctime( ) function converts time value to a 26-character long string that contains date and time. -----------------------------------------------------------------------------------------------106. How to use function strdup( ) in a program? Ans : The string function strdup( ) copies the given string to a new location. The function uses malloc( ) function to allocate space required for the duplicated string. It takes one argument a pointer to the string to be duplicated. The total number of characters present in the given string plus one bytes get allocated for the new string. As this function uses malloc( ) to allocate memory, it is the programmers responsibility to deallocate the memory using free( ). #include <stdio.h> #include <string.h> #include <alloc.h> void main( ) { char *str1, *str2 = "double";

str1 = strdup ( str2 ) ; printf ( "%s\n", str1 ) ; free ( str1 ) ; } -----------------------------------------------------------------------------------------------107. On including a file twice I get errors reporting redefinition of function. How can I avoid duplicate inclusion? Ans: Redefinition errors can be avoided by using the following macro definition. Include this definition in the header file. #if !defined filename_h #define filename_h /* function definitions */ #endif Replace filename_h with the actual header file name. For example, if name of file to be included is 'goto.h' then replace filename_h with 'goto_h'. -----------------------------------------------------------------------------------------------108. How to write a swap( ) function which swaps the values of the variables using bitwise operators. Ans: Here is the swap( ) function. swap ( int *x, int *y ) { *x ^= *y ; *y ^= *x ; *x ^= *y ; } The swap( ) function uses the bitwise XOR operator and does not require any temporary variable for swapping.

First Job. Dream Job. Freshersworld.com

C Questions
Note : All the programs are tested under Turbo C/C++ compilers. It is assumed that, Programs run under DOS environment, The underlying machine is an x86 system, Program is compiled using Turbo C/C++ compiler. The program output may depend on the information based on this assumptions (for example sizeof(int) == 2 may be assumed). Predict the output or error(s) for the following: 1. void main() { int const * p=5; printf("%d",++(*p)); } Answer: Compiler error: Cannot modify a constant value. Explanation: p is a pointer to a "constant integer". But we tried to change the value of the "constant integer". 2. main() { char s[ ]="man"; int i; for(i=0;s[ i ];i++) printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]); } Answer: mmmm aaaa nnnn Explanation: s[i], *(i+s), *(s+i), i[s] are all different ways of expressing the same idea. Generally array name is the base address for that array. Here s is the base address. i is the index number/displacement from the base address. So, indirecting it with * is same as s[i]. i[s] may be surprising. But in the case of C it is same as s[i]. 3. main() { float me = 1.1; double you = 1.1; if(me==you) printf("I love U");
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com else printf("I hate U"); } Answer: I hate U Explanation: For floating point numbers (float, double, long double) the values cannot be predicted exactly. Depending on the number of bytes, the precession with of the value represented varies. Float takes 4 bytes and long double takes 10 bytes. So float stores 0.9 with less precision than long double. Rule of Thumb: Never compare or at-least be cautious when using floating point numbers with relational operators (== , >, <, <=, >=,!= ) . 4. main() { static int var = 5; printf("%d ",var--); if(var) main(); } Answer: 54321 Explanation: When static storage class is given, it is initialized once. The change in the value of a static variable is retained even between the function calls. Main is also treated like any other ordinary function, which can be called recursively. 5. main() { int c[ ]={2.8,3.4,4,6.7,5}; int j,*p=c,*q=c; for(j=0;j<5;j++) { printf(" %d ",*c); ++q; } for(j=0;j<5;j++){ printf(" %d ",*p); ++p; } } Answer: 2222223465 Explanation: Initially pointer c is assigned to both p and q. In the first loop, since only q is incremented and not c , the value 2 will be printed 5 times. In second loop p itself is incremented. So the values 2 3 4 6 5 will be printed.
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com 6. main() { extern int i; i=20; printf("%d",i); } Answer: Linker Error : Undefined symbol '_i' Explanation: extern storage class in the following declaration, extern int i; specifies to the compiler that the memory for i is allocated in some other program and that address will be given to the current program at the time of linking. But linker finds that no other variable of name i is available in any other program with memory space allocated for it. Hence a linker error has occurred . 7. main() { int i=-1,j=-1,k=0,l=2,m; m=i++&&j++&&k++||l++; printf("%d %d %d %d %d",i,j,k,l,m); } Answer: 00131 Explanation : Logical operations always give a result of 1 or 0 . And also the logical AND (&&) operator has higher priority over the logical OR (||) operator. So the expression i++ && j++ && k++ is executed first. The result of this expression is 0 (-1 && -1 && 0 = 0). Now the expression is 0 || 2 which evaluates to 1 (because OR operator always gives 1 except for 0 || 0 combination- for which it gives 0). So the value of m is 1. The values of other variables are also incremented by 1. 8. main() { char *p; printf("%d %d ",sizeof(*p),sizeof(p)); } Answer: 12 Explanation: The sizeof() operator gives the number of bytes taken by its operand. P is a character pointer, which needs one byte for storing its value (a character). Hence sizeof(*p) gives a value of 1. Since it needs two bytes to store the address of the character pointer sizeof(p) gives 2.
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com

9. main() { int i=3; switch(i) { default:printf("zero"); case 1: printf("one"); break; case 2:printf("two"); break; case 3: printf("three"); break; } } Answer : three Explanation : The default case can be placed anywhere inside the loop. It is executed only when all other cases doesn't match. 10. main() { printf("%x",-1<<4); } Answer: fff0 Explanation : -1 is internally represented as all 1's. When left shifted four times the least significant 4 bits are filled with 0's.The %x format specifier specifies that the integer value be printed as a hexadecimal value. 11. main() { char string[]="Hello World"; display(string); } void display(char *string) { printf("%s",string); } Answer: Compiler Error : Type mismatch in redeclaration of function display Explanation : In third line, when the function display is encountered, the compiler doesn't know anything about the function display. It assumes the arguments and
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com return types to be integers, (which is the default type). When it sees the actual function display, the arguments and type contradicts with what it has assumed previously. Hence a compile time error occurs. 12. main() { int c=- -2; printf("c=%d",c); } Answer: c=2; Explanation: Here unary minus (or negation) operator is used twice. Same maths rules applies, ie. minus * minus= plus. Note: However you cannot give like --2. Because -- operator can only be applied to variables as a decrement operator (eg., i--). 2 is a constant and not a variable. 13. #define int char main() { int i=65; printf("sizeof(i)=%d",sizeof(i)); } Answer: sizeof(i)=1 Explanation: Since the #define replaces the string int by the macro char 14. main() { int i=10; i=!i>14; Printf ("i=%d",i); } Answer: i=0

Explanation: In the expression !i>14 , NOT (!) operator has more precedence than > symbol. ! is a unary logical operator. !i (!10) is 0 (not of true is false). 0>14 is false (zero). 15. #include<stdio.h>
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com main() { char s[]={'a','b','c','\n','c','\0'}; char *p,*str,*str1; p=&s[3]; str=p; str1=s; printf("%d",++*p + ++*str1-32); } Answer: 77 Explanation: p is pointing to character '\n'. str1 is pointing to character 'a' ++*p. "p is pointing to '\n' and that is incremented by one." the ASCII value of '\n' is 10, which is then incremented to 11. The value of ++*p is 11. ++*str1, str1 is pointing to 'a' that is incremented by 1 and it becomes 'b'. ASCII value of 'b' is 98. Now performing (11 + 98 32), we get 77("M"); So we get the output 77 :: "M" (Ascii is 77). 16. #include<stdio.h> main() { int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} }; int *p,*q; p=&a[2][2][2]; *q=***a; printf("%d----%d",*p,*q); } Answer: SomeGarbageValue---1 Explanation: p=&a[2][2][2] you declare only two 2D arrays, but you are trying to access the third 2D(which you are not declared) it will print garbage values. *q=***a starting address of a is assigned integer pointer. Now q is pointing to starting address of a. If you print *q, it will print first element of 3D array. 17. #include<stdio.h> main() { struct xx { int x=3; char name[]="hello"; }; struct xx *s; printf("%d",s->x);
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com printf("%s",s->name); } Answer: Compiler Error Explanation: You should not initialize variables in declaration 18. #include<stdio.h> main() { struct xx { int x; struct yy { char s; struct xx *p; }; struct yy *q; }; } Answer: Compiler Error Explanation: The structure yy is nested within structure xx. Hence, the elements are of yy are to be accessed through the instance of structure xx, which needs an instance of yy to be known. If the instance is created after defining the structure the compiler will not know about the instance relative to xx. Hence for nested structure yy you have to declare member. 19. main() { printf("\nab"); printf("\bsi"); printf("\rha"); } Answer: hai Explanation: \n - newline \b - backspace \r - linefeed 20. main() { int i=5;
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com printf("%d%d%d%d%d%d",i++,i--,++i,--i,i); } Answer: 45545 Explanation: The arguments in a function call are pushed into the stack from left to right. The evaluation is by popping out from the stack. and the evaluation is from right to left, hence the result. 21. #define square(x) x*x main() { int i; i = 64/square(4); printf("%d",i); } Answer: 64 Explanation: the macro call square(4) will substituted by 4*4 so the expression becomes i = 64/4*4 . Since / and * has equal priority the expression will be evaluated as (64/4)*4 i.e. 16*4 = 64 22. main() { char *p="hai friends",*p1; p1=p; while(*p!='\0') ++*p++; printf("%s %s",p,p1); } Answer: ibj!gsjfoet Explanation: ++*p++ will be parse in the given order *p that is value at the location currently pointed by p will be taken ++*p the retrieved value will be incremented when ; is encountered the location will be incremented that is p++ will be executed Hence, in the while loop initial value pointed by p is h, which is changed to i by executing ++*p and pointer moves to point, a which is similarly changed to b and so on. Similarly blank space is converted to !. Thus, we obtain value in p becomes ibj!gsjfoet and since p reaches \0 and p1 points to p thus p1doesnot print anything. 23. #include <stdio.h> #define a 10 main()
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com { #define a 50 printf("%d",a); } Answer: 50 Explanation: The preprocessor directives can be redefined anywhere in the program. So the most recently assigned value will be taken. 24. #define clrscr() 100 main() { clrscr(); printf("%d\n",clrscr()); } Answer: 100 Explanation: Preprocessor executes as a seperate pass before the execution of the compiler. So textual replacement of clrscr() to 100 occurs.The input program to compiler looks like this : main() { 100; printf("%d\n",100); } Note: 100; is an executable statement but with no action. So it doesn't give any problem 25. main() { printf("%p",main); } Answer: Some address will be printed. Explanation: Function names are just addresses (just like array names are addresses). main() is also a function. So the address of function main will be printed. %p in printf specifies that the argument is an address. They are printed as hexadecimal numbers. 27) main() { clrscr();
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com } clrscr(); Answer: No output/error Explanation: The first clrscr() occurs inside a function. So it becomes a function call. In the second clrscr(); is a function declaration (because it is not inside any function). 28) enum colors {BLACK,BLUE,GREEN} main() { printf("%d..%d..%d",BLACK,BLUE,GREEN); return(1); } Answer: 0..1..2 Explanation: enum assigns numbers starting from 0, if not explicitly defined. 29) void main() { char far *farther,*farthest; printf("%d..%d",sizeof(farther),sizeof(farthest)); } Answer: 4..2 Explanation: the second pointer is of char type and not a far pointer 30) main() { int i=400,j=300; printf("%d..%d"); } Answer: 400..300 Explanation: printf takes the values of the first two assignments of the program. Any number of printf's may be given. All of them take only the first two

Freshersworld.com Resource Center

10

First Job. Dream Job. Freshersworld.com values. If more number of assignments given in the program,then printf will take garbage values. 31) main() { char *p; p="Hello"; printf("%c\n",*&*p); } Answer: H Explanation: * is a dereference operator & is a reference operator. They can be applied any number of times provided it is meaningful. Here p points to the first character in the string "Hello". *p dereferences it and so its value is H. Again & references it to an address and * dereferences it to the value H. main() { int i=1; while (i<=5) { printf("%d",i); if (i>2) goto here; i++; } } fun() { here: printf("PP"); } Answer: Compiler error: Undefined label 'here' in function main Explanation: Labels have functions scope, in other words The scope of the labels is limited to functions . The label 'here' is available in function fun() Hence it is not visible in function main. main() { static char names[5][20]={"pascal","ada","cobol","fortran","perl"}; int i; char *t;
Freshersworld.com Resource Center

32)

33)

11

First Job. Dream Job. Freshersworld.com t=names[3]; names[3]=names[4]; names[4]=t; for (i=0;i<=4;i++) printf("%s",names[i]); } Answer: Compiler error: Lvalue required in function main Explanation: Array names are pointer constants. So it cannot be modified. 34) void main() { int i=5; printf("%d",i++ + ++i); } Answer: Output Cannot be predicted exactly. Explanation: Side effects are involved in the evaluation of i void main() { int i=5; printf("%d",i+++++i); } Answer: Compiler Error Explanation: The expression i+++++i is parsed as i ++ ++ + i which is an illegal combination of operators. #include<stdio.h> main() { int i=1,j=2; switch(i) { case 1: printf("GOOD"); break; case j: printf("BAD"); break; } } Answer: Compiler Error: Constant expression required in function main.
Freshersworld.com Resource Center

35)

36)

12

First Job. Dream Job. Freshersworld.com Explanation: The case statement can have only constant expressions (this implies that we cannot use variable names directly so an error). Note: Enumerated types can be used in case statements. 37) main() { int i; printf("%d",scanf("%d",&i)); // value 10 is given as input here } Answer: 1 Explanation: Scanf returns number of items successfully read and not 1/0. Here 10 is given as input which should have been scanned successfully. So number of items read is 1. #define f(g,g2) g##g2 main() { int var12=100; printf("%d",f(var,12)); } Answer: 100 main() { int i=0; for(;i++;printf("%d",i)) ; printf("%d",i); } Answer: 1 Explanation: before entering into the for loop the checking condition is "evaluated". Here it evaluates to 0 (false) and comes out of the loop, and i is incremented (note the semicolon after the for loop). 40) #include<stdio.h> main() { char s[]={'a','b','c','\n','c','\0'}; char *p,*str,*str1;
Freshersworld.com Resource Center

38)

39)

13

First Job. Dream Job. Freshersworld.com p=&s[3]; str=p; str1=s; printf("%d",++*p + ++*str1-32); } Answer: M Explanation: p is pointing to character '\n'.str1 is pointing to character 'a' ++*p meAnswer:"p is pointing to '\n' and that is incremented by one." the ASCII value of '\n' is 10. then it is incremented to 11. the value of ++*p is 11. ++*str1 meAnswer:"str1 is pointing to 'a' that is incremented by 1 and it becomes 'b'. ASCII value of 'b' is 98. both 11 and 98 is added and result is subtracted from 32. i.e. (11+98-32)=77("M"); 41) #include<stdio.h> main() { struct xx { int x=3; char name[]="hello"; }; struct xx *s=malloc(sizeof(struct xx)); printf("%d",s->x); printf("%s",s->name); } Answer: Compiler Error Explanation: Initialization should not be done for structure members inside the structure declaration #include<stdio.h> main() { struct xx { int x; struct yy { char s; struct xx *p; }; struct yy *q;
Freshersworld.com Resource Center

42)

14

First Job. Dream Job. Freshersworld.com }; } Answer: Compiler Error Explanation: in the end of nested structure yy a member have to be declared. 43) main() { extern int i; i=20; printf("%d",sizeof(i)); } Answer: Linker error: undefined symbol '_i'. Explanation: extern declaration specifies that the variable i is defined somewhere else. The compiler passes the external variable to be resolved by the linker. So compiler doesn't find an error. During linking the linker searches for the definition of i. Since it is not found the linker flags an error. main() { printf("%d", out); } int out=100; Answer: Compiler error: undefined symbol out in function main. Explanation: The rule is that a variable is available for use from the point of declaration. Even though a is a global variable, it is not available for main. Hence an error. main() { extern out; printf("%d", out); } int out=100; Answer: 100 Explanation: This is the correct way of writing the previous program. main()
Freshersworld.com Resource Center

44)

45)

46)

15

First Job. Dream Job. Freshersworld.com { show(); } void show() { printf("I'm the greatest"); } Answer: Compier error: Type mismatch in redeclaration of show. Explanation: When the compiler sees the function show it doesn't know anything about it. So the default return type (ie, int) is assumed. But when compiler sees the actual definition of show mismatch occurs since it is declared as void. Hence the error. The solutions are as follows: 1. declare void show() in main() . 2. define show() before main(). 3. declare extern void show() before the use of show(). 47) main( ) { int a[2][3][2] = {{{2,4},{7,8},{3,4}},{{2,2},{2,3},{3,4}}}; printf(%u %u %u %d \n,a,*a,**a,***a); printf(%u %u %u %d \n,a+1,*a+1,**a+1,***a+1); } Answer: 100, 100, 100, 2 114, 104, 102, 3 Explanation: The given array is a 3-D one. It can also be viewed as a 1-D array. 2 4 7 8 3 4 2 2 2 3 3 4 100 102 104 106 108 110 112 114 116 118 120 122 thus, for the first printf statement a, *a, **a give address of first element . since the indirection ***a gives the value. Hence, the first line of the output. for the second printf a+1 increases in the third dimension thus points to value at 114, *a+1 increments in second dimension thus points to 104, **a +1 increments the first dimension thus points to 102 and ***a+1 first gets the value at first location and then increments it by 1. Hence, the output. 48) main( ) {
Freshersworld.com Resource Center

16

First Job. Dream Job. Freshersworld.com int a[ ] = {10,20,30,40,50},j,*p; for(j=0; j<5; j++) { printf(%d ,*a); a++; } p = a; for(j=0; j<5; j++) { printf(%d ,*p); p++; } } Answer: Compiler error: lvalue required. Explanation: Error is in line with statement a++. The operand must be an lvalue and may be of any of scalar type for the any operator, array name only when subscripted is an lvalue. Simply array name is a non-modifiable lvalue. 49) main( ) { static int a[ ] = {0,1,2,3,4}; int *p[ ] = {a,a+1,a+2,a+3,a+4}; int **ptr = p; ptr++; printf(\n %d %d %d, ptr-p, *ptr-a, **ptr); *ptr++; printf(\n %d %d %d, ptr-p, *ptr-a, **ptr); *++ptr; printf(\n %d %d %d, ptr-p, *ptr-a, **ptr); ++*ptr; printf(\n %d %d %d, ptr-p, *ptr-a, **ptr); } Answer: 111 222 333 344 Explanation: Let us consider the array and the two pointers with some address a 0 1 2 3 4 100 102 104 106 108
Freshersworld.com Resource Center

17

First Job. Dream Job. Freshersworld.com p 100 102 104 106 108 1000 1002 1004 1006 1008 ptr 1000 2000 After execution of the instruction ptr++ value in ptr becomes 1002, if scaling factor for integer is 2 bytes. Now ptr p is value in ptr starting location of array p, (1002 1000) / (scaling factor) = 1, *ptr a = value at address pointed by ptr starting value of array a, 1002 has a value 102 so the value is (102 100)/(scaling factor) = 1, **ptr is the value stored in the location pointed by the pointer of ptr = value pointed by value pointed by 1002 = value pointed by 102 = 1. Hence the output of the firs printf is 1, 1, 1. After execution of *ptr++ increments value of the value in ptr by scaling factor, so it becomes1004. Hence, the outputs for the second printf are ptr p = 2, *ptr a = 2, **ptr = 2. After execution of *++ptr increments value of the value in ptr by scaling factor, so it becomes1004. Hence, the outputs for the third printf are ptr p = 3, *ptr a = 3, **ptr = 3. After execution of ++*ptr value in ptr remains the same, the value pointed by the value is incremented by the scaling factor. So the value in array p at location 1006 changes from 106 10 108,. Hence, the outputs for the fourth printf are ptr p = 1006 1000 = 3, *ptr a = 108 100 = 4, **ptr = 4. 50) main( ) { char *q; int j; for (j=0; j<3; j++) scanf(%s ,(q+j)); for (j=0; j<3; j++) printf(%c ,*(q+j)); for (j=0; j<3; j++) printf(%s ,(q+j)); } Explanation: Here we have only one pointer to type char and since we take input in the same pointer thus we keep writing over in the same location, each time shifting the pointer value by 1. Suppose the inputs are MOUSE, TRACK and VIRTUAL. Then for the first input suppose the pointer starts at location 100 then the input one is stored as M O U S E \0 When the second input is given the pointer is incremented as j value becomes 1, so the input is filled in memory starting from 101. M T R A C K \0 The third input starts filling from the location 102

Freshersworld.com Resource Center

18

First Job. Dream Job. Freshersworld.com M T V I R T U A L \0 This is the final value stored . The first printf prints the values at the position q, q+1 and q+2 = M T V The second printf prints three strings starting from locations q, q+1, q+2 i.e MTVIRTUAL, TVIRTUAL and VIRTUAL. 51) main( ) { void *vp; char ch = g, *cp = goofy; int j = 20; vp = &ch; printf(%c, *(char *)vp); vp = &j; printf(%d,*(int *)vp); vp = cp; printf(%s,(char *)vp + 3); } Answer: g20fy Explanation: Since a void pointer is used it can be type casted to any other type pointer. vp = &ch stores address of char ch and the next statement prints the value stored in vp after type casting it to the proper data type pointer. the output is g. Similarly the output from second printf is 20. The third printf statement type casts it to print the string from the 4th value hence the output is fy. main ( ) { static char *s[ ] = {black, white, yellow, violet}; char **ptr[ ] = {s+3, s+2, s+1, s}, ***p; p = ptr; **++p; printf(%s,*--*++p + 3); } Answer: ck Explanation: In this problem we have an array of char pointers pointing to start of 4 strings. Then we have ptr which is a pointer to a pointer of type char and a variable p which is a pointer to a pointer to a pointer of type char. p hold the initial value of ptr, i.e. p = s+3. The next statement increment value in p by 1 , thus now value of p = s+2. In the printf
Freshersworld.com Resource Center

52)

19

First Job. Dream Job. Freshersworld.com statement the expression is evaluated *++p causes gets value s+1 then the pre decrement is executed and we get s+1 1 = s . the indirection operator now gets the value from the array of s and adds 3 to the starting address. The string is printed starting from this position. Thus, the output is ck. 53) main() { int i, n; char *x = girl; n = strlen(x); *x = x[n]; for(i=0; i<n; ++i) { printf(%s\n,x); x++; } } Answer: (blank space) irl rl l Explanation: Here a string (a pointer to char) is initialized with a value girl. The strlen function returns the length of the string, thus n has a value 4. The next statement assigns value at the nth location (\0) to the first location. Now the string becomes \0irl . Now the printf statement prints the string after each iteration it increments it starting position. Loop starts from 0 to 4. The first time x[0] = \0 hence it prints nothing and pointer value is incremented. The second time it prints from x[1] i.e irl and the third time it prints rl and the last time it prints l and the loop terminates. int i,j; for(i=0;i<=10;i++) { j+=5; assert(i<5); } Answer: Runtime error: Abnormal program termination. assert failed (i<5), <file name>,<line number> Explanation:

54)

Freshersworld.com Resource Center

20

First Job. Dream Job. Freshersworld.com asserts are used during debugging to make sure that certain conditions are satisfied. If assertion fails, the program will terminate reporting the same. After debugging use, #undef NDEBUG and this will disable all the assertions from the source code. Assertion is a good debugging tool to make use of. 55) main() { int i=-1; +i; printf("i = %d, +i = %d \n",i,+i); } Answer: i = -1, +i = -1 Explanation: Unary + is the only dummy operator in C. Where-ever it comes you can just ignore it just because it has no effect in the expressions (hence the name dummy operator). What are the files which are automatically opened when a C file is executed? Answer: stdin, stdout, stderr (standard input,standard output,standard error).

56)

57) what will be the position of the file marker? a: fseek(ptr,0,SEEK_SET); b: fseek(ptr,0,SEEK_CUR); Answer : a: The SEEK_SET sets the file position marker to the starting of the file. b: The SEEK_CUR sets the file position marker to the current position of the file. 58) main() { char name[10],s[12]; scanf(" \"%[^\"]\"",s); } How scanf will execute? Answer: First it checks for the leading white space and discards it.Then it matches with a quotation mark and then it reads all character upto another quotation mark. What is the problem with the following code segment?
Freshersworld.com Resource Center

59)

21

First Job. Dream Job. Freshersworld.com while ((fgets(receiving array,50,file_ptr)) != EOF) ; Answer & Explanation: fgets returns a pointer. So the correct end of file check is checking for != NULL. 60) main() { main(); } Answer: Runtime error : Stack overflow. Explanation: main function calls itself again and again. Each time the function is called its return address is stored in the call stack. Since there is no condition to terminate the function call, the call stack overflows at runtime. So it terminates the program and results in an error. main() { char *cptr,c; void *vptr,v; c=10; v=0; cptr=&c; vptr=&v; printf("%c%v",c,v); } Answer: Compiler error (at line number 4): size of v is Unknown. Explanation: You can create a variable of type void * but not of type void, since void is an empty type. In the second line you are creating variable vptr of type void * and v of type void hence an error. main() { char *str1="abcd"; char str2[]="abcd"; printf("%d %d %d",sizeof(str1),sizeof(str2),sizeof("abcd")); } Answer: 255 Explanation: In first sizeof, str1 is a character pointer so it gives you the size of the pointer variable. In second sizeof the name str2 indicates the name of the array whose size is 5 (including the '\0' termination character). The third sizeof is similar to the second one.
Freshersworld.com Resource Center

61)

62)

22

First Job. Dream Job. Freshersworld.com

63)

main() { char not; not=!2; printf("%d",not); } Answer: 0 Explanation: ! is a logical operator. In C the value 0 is considered to be the boolean value FALSE, and any non-zero value is considered to be the boolean value TRUE. Here 2 is a non-zero value so TRUE. !TRUE is FALSE (0) so it prints 0. #define FALSE -1 #define TRUE 1 #define NULL 0 main() { if(NULL) puts("NULL"); else if(FALSE) puts("TRUE"); else puts("FALSE"); } Answer: TRUE Explanation: The input program to the compiler after processing by the preprocessor is, main(){ if(0) puts("NULL"); else if(-1) puts("TRUE"); else puts("FALSE"); } Preprocessor doesn't replace the values given inside the double quotes. The check by if condition is boolean value false so it goes to else. In second if -1 is boolean value true hence "TRUE" is printed. main() { int k=1;
Freshersworld.com Resource Center

64)

65)

23

First Job. Dream Job. Freshersworld.com printf("%d==1 is ""%s",k,k==1?"TRUE":"FALSE"); } Answer: 1==1 is TRUE Explanation: When two strings are placed together (or separated by white-space) they are concatenated (this is called as "stringization" operation). So the string is as if it is given as "%d==1 is %s". The conditional operator( ?: ) evaluates to "TRUE". 66) main() { int y; scanf("%d",&y); // input given is 2000 if( (y%4==0 && y%100 != 0) || y%100 == 0 ) printf("%d is a leap year"); else printf("%d is not a leap year"); } Answer: 2000 is a leap year Explanation: An ordinary program to check if leap year or not. #define max 5 #define int arr1[max] main() { typedef char arr2[max]; arr1 list={0,1,2,3,4}; arr2 name="name"; printf("%d %s",list[0],name); } Answer: Compiler error (in the line arr1 list = {0,1,2,3,4}) Explanation: arr2 is declared of type array of size 5 of characters. So it can be used to declare the variable name of the type arr2. But it is not the case of arr1. Hence an error. Rule of Thumb: #defines are used for textual replacement whereas typedefs are used for declaring new types. int i=10; main() {
Freshersworld.com Resource Center

67)

68)

24

First Job. Dream Job. Freshersworld.com extern int i; { int i=20; { const volatile unsigned i=30; printf("%d",i); } printf("%d",i); } printf("%d",i); } Answer: 30,20,10 Explanation: '{' introduces new block and thus new scope. In the innermost block i is declared as, const volatile unsigned which is a valid declaration. i is assumed of type int. So printf prints 30. In the next block, i has value 20 and so printf prints 20. In the outermost block, i is declared as extern, so no storage space is allocated for it. After compilation is over the linker resolves it to global variable i (since it is the only variable visible there). So it prints i's value as 10. 69) main() { int *j; { int i=10; j=&i; } printf("%d",*j); } Answer: 10 Explanation: The variable i is a block level variable and the visibility is inside that block only. But the lifetime of i is lifetime of the function so it lives upto the exit of main function. Since the i is still allocated space, *j prints the value stored in i since j points i. main() { int i=-1; -i; printf("i = %d, -i = %d \n",i,-i);
Freshersworld.com Resource Center

70)

25

First Job. Dream Job. Freshersworld.com } Answer: i = -1, -i = 1 Explanation: -i is executed and this execution doesn't affect the value of i. In printf first you just print the value of i. After that the value of the expression -i = -(-1) is printed. 71) #include<stdio.h> main() { const int i=4; float j; j = ++i; printf("%d %f", i,++j); } Answer: Compiler error Explanation: i is a constant. you cannot change the value of constant #include<stdio.h> main() { int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} }; int *p,*q; p=&a[2][2][2]; *q=***a; printf("%d..%d",*p,*q); } Answer: garbagevalue..1 Explanation: p=&a[2][2][2] you declare only two 2D arrays. but you are trying to access the third 2D(which you are not declared) it will print garbage values. *q=***a starting address of a is assigned integer pointer. now q is pointing to starting address of a.if you print *q meAnswer:it will print first element of 3D array. #include<stdio.h> main() { register i=5; char j[]= "hello"; printf("%s %d",j,i); }
Freshersworld.com Resource Center

72)

73)

26

First Job. Dream Job. Freshersworld.com Answer: hello 5 Explanation: if you declare i as register compiler will treat it as ordinary integer and it will take integer value. i value may be stored either in register or in memory. 74) main() { int i=5,j=6,z; printf("%d",i+++j); } Answer: 11 Explanation: the expression i+++j is treated as (i++ + j) struct aaa{ struct aaa *prev; int i; struct aaa *next; }; main() { struct aaa abc,def,ghi,jkl; int x=100; abc.i=0;abc.prev=&jkl; abc.next=&def; def.i=1;def.prev=&abc;def.next=&ghi; ghi.i=2;ghi.prev=&def; ghi.next=&jkl; jkl.i=3;jkl.prev=&ghi;jkl.next=&abc; x=abc.next->next->prev->next->i; printf("%d",x); } Answer: 2 Explanation: above all statements form a double circular linked list; abc.next->next->prev->next->i this one points to "ghi" node the value of at particular node is 2. struct point { int x; int y;
Freshersworld.com Resource Center

76)

77)

27

First Job. Dream Job. Freshersworld.com }; struct point origin,*pp; main() { pp=&origin; printf("origin is(%d%d)\n",(*pp).x,(*pp).y); printf("origin is (%d%d)\n",pp->x,pp->y); } Answer: origin is(0,0) origin is(0,0) Explanation: pp is a pointer to structure. we can access the elements of the structure either with arrow mark or with indirection operator. Note: Since structure point is globally declared x & y are initialized as zeroes 78) main() { int i=_l_abc(10); printf("%d\n",--i); } int _l_abc(int i) { return(i++); } Answer: 9 Explanation: return(i++) it will first return i and then increments. i.e. 10 will be returned. main() { char *p; int *q; long *r; p=q=r=0; p++; q++; r++; printf("%p...%p...%p",p,q,r); } Answer:
Freshersworld.com Resource Center

79)

28

First Job. Dream Job. Freshersworld.com 0001...0002...0004 Explanation: ++ operator when applied to pointers increments address according to their corresponding data-types. 80) main() { char c=' ',x,convert(z); getc(c); if((c>='a') && (c<='z')) x=convert(c); printf("%c",x); } convert(z) { return z-32; } Answer: Compiler error Explanation: declaration of convert and format of getc() are wrong. main(int argc, char **argv) { printf("enter the character"); getchar(); sum(argv[1],argv[2]); } sum(num1,num2) int num1,num2; { return num1+num2; } Answer: Compiler error. Explanation: argv[1] & argv[2] are strings. They are passed to the function sum without converting it to integer values. # include <stdio.h> int one_d[]={1,2,3}; main() { int *ptr; ptr=one_d; ptr+=3;
Freshersworld.com Resource Center

81)

82)

29

First Job. Dream Job. Freshersworld.com printf("%d",*ptr); } Answer: garbage value Explanation: ptr pointer is pointing to out of the array range of one_d. 83) # include<stdio.h> aaa() { printf("hi"); } bbb(){ printf("hello"); } ccc(){ printf("bye"); } main() { int (*ptr[3])(); ptr[0]=aaa; ptr[1]=bbb; ptr[2]=ccc; ptr[2](); } Answer: bye Explanation: ptr is array of pointers to functions of return type int.ptr[0] is assigned to address of the function aaa. Similarly ptr[1] and ptr[2] for bbb and ccc respectively. ptr[2]() is in effect of writing ccc(), since ptr[2] points to ccc. #include<stdio.h> main() { FILE *ptr; char i; ptr=fopen("zzz.c","r"); while((i=fgetch(ptr))!=EOF) printf("%c",i); } Answer: contents of zzz.c followed by an infinite loop Explanation:

85)

Freshersworld.com Resource Center

30

First Job. Dream Job. Freshersworld.com The condition is checked against EOF, it should be checked against NULL. 86) main() { int i =0;j=0; if(i && j++) printf("%d..%d",i++,j); printf("%d..%d,i,j); } Answer: 0..0 Explanation: The value of i is 0. Since this information is enough to determine the truth value of the boolean expression. So the statement following the if statement is not executed. The values of i and j remain unchanged and get printed. main() { int i; i = abc(); printf("%d",i); } abc() { _AX = 1000; } Answer: 1000 Explanation: Normally the return value from the function is through the information from the accumulator. Here _AH is the pseudo global variable denoting the accumulator. Hence, the value of the accumulator is set 1000 so the function returns value 1000. int i; main(){ int t; for ( t=4;scanf("%d",&i)-t;printf("%d\n",i)) printf("%d--",t--); } // If the inputs are 0,1,2,3 find the o/p Answer: 4--0 3--1
Freshersworld.com Resource Center

87)

88)

31

First Job. Dream Job. Freshersworld.com 2--2 Explanation: Let us assume some x= scanf("%d",&i)-t the values during execution will be, t i x 4 0 -4 3 1 -2 2 2 0 89) main(){ int a= 0;int b = 20;char x =1;char y =10; if(a,b,x,y) printf("hello"); } Answer: hello Explanation: The comma operator has associativity from left to right. Only the rightmost value is returned and the other values are evaluated and ignored. Thus the value of last variable y is returned to check in if. Since it is a non zero value if becomes true so, "hello" will be printed. main(){ unsigned int i; for(i=1;i>-2;i--) printf("c aptitude"); } Explanation: i is an unsigned integer. It is compared with a signed value. Since the both types doesn't match, signed is promoted to unsigned value. The unsigned equivalent of -2 is a huge value so condition becomes false and control comes out of the loop. In the following pgm add a stmt in the function fun such that the address of 'a' gets stored in 'j'. main(){ int * j; void fun(int **); fun(&j); } void fun(int **k) { int a =0; /* add a stmt here*/ } Answer: *k = &a
Freshersworld.com Resource Center

90)

91)

32

First Job. Dream Job. Freshersworld.com Explanation: The argument of the function is a pointer to a pointer. 92) What are the following notations of defining functions known as? i. int abc(int a,float b) { /* some code */ } ii. int abc(a,b) int a; float b; { /* some code*/ } Answer: i. ANSI C notation ii. Kernighan & Ritche notation main() { char *p; p="%d\n"; p++; p++; printf(p-2,300); } Answer: 300 Explanation: The pointer points to % since it is incremented twice and again decremented by 2, it points to '%d\n' and 300 is printed. main(){ char a[100]; a[0]='a';a[1]]='b';a[2]='c';a[4]='d'; abc(a); } abc(char a[]){ a++; printf("%c",*a); a++; printf("%c",*a); } Explanation: The base address is modified only in function and as a result a points to 'b' then after incrementing to 'c' so bc will be printed.

93)

94)

Freshersworld.com Resource Center

33

First Job. Dream Job. Freshersworld.com 95) func(a,b) int a,b; { return( a= (a==b) ); } main() { int process(),func(); printf("The value of process is %d !\n ",process(func,3,6)); } process(pf,val1,val2) int (*pf) (); int val1,val2; { return((*pf) (val1,val2)); } Answer: The value if process is 0 ! Explanation: The function 'process' has 3 parameters - 1, a pointer to another function 2 and 3, integers. When this function is invoked from main, the following substitutions for formal parameters take place: func for pf, 3 for val1 and 6 for val2. This function returns the result of the operation performed by the function 'func'. The function func has two integer parameters. The formal parameters are substituted as 3 for a and 6 for b. since 3 is not equal to 6, a==b returns 0. therefore the function returns 0 which in turn is returned by the function 'process'. void main() { static int i=5; if(--i){ main(); printf("%d ",i); } } Answer: 0000 Explanation: The variable "I" is declared as static, hence memory for I will be allocated for only once, as it encounters the statement. The function main() will be called recursively unless I becomes equal to 0, and since main() is recursively called, so the value of static I ie., 0 will be printed every time the control is returned. void main()
Freshersworld.com Resource Center

96)

97)

34

First Job. Dream Job. Freshersworld.com { int k=ret(sizeof(float)); printf("\n here value is %d",++k); } int ret(int ret) { ret += 2.5; return(ret); } Answer: Here value is 7 Explanation: The int ret(int ret), ie., the function name and the argument name can be the same. Firstly, the function ret() is called in which the sizeof(float) ie., 4 is passed, after the first expression the value in ret will be 6, as ret is integer hence the value stored in ret will have implicit type conversion from float to int. The ret is returned in main() it is printed after and preincrement. 98) void main() { char a[]="12345\0"; int i=strlen(a); printf("here in 3 %d\n",++i); } Answer: here in 3 6 Explanation: The char array 'a' will hold the initialized string, whose length will be counted from 0 till the null character. Hence the 'I' will hold the value equal to 5, after the pre-increment in the printf statement, the 6 will be printed. void main() { unsigned giveit=-1; int gotit; printf("%u ",++giveit); printf("%u \n",gotit=--giveit); } Answer: 0 65535 Explanation: void main() { int i;
Freshersworld.com Resource Center

99)

100)

35

First Job. Dream Job. Freshersworld.com char a[]="\0"; if(printf("%s\n",a)) printf("Ok here \n"); else printf("Forget it\n"); } Answer: Ok here Explanation: Printf will return how many characters does it print. Hence printing a null character returns 1 which makes the if statement true, thus "Ok here" is printed. 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. 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).

102)

Freshersworld.com Resource Center

36

First Job. Dream Job. Freshersworld.com

103)

void main() { static int i=i++, j=j++, k=k++; printf(i = %d j = %d k = %d, i, j, k); } Answer: i=1j=1k=1 Explanation: Since static variables are initialized to zero by default. 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. main() { unsigned int i=10; while(i-->=0) printf("%u ",i); } Answer: 10 9 8 7 6 5 4 3 2 1 0 65535 65534.. Explanation: Since i is an unsigned integer it can never become negative. So the expression i-- >=0 will always be true, leading to an infinite loop.

104)

104)

105)

#include<conio.h> main() { int x,y=2,z,a;


Freshersworld.com Resource Center

37

First Job. Dream Job. Freshersworld.com 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 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.

108)

Freshersworld.com Resource Center

38

First Job. Dream Job. Freshersworld.com 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. 113) main() { float f=5,g=10; enum{i=10,j=20,k=50}; printf("%d\n",++k); printf("%f\n",f<<2); printf("%lf\n",f%g); printf("%lf\n",fmod(f,g)); } Answer: Line no 5: Error: Lvalue required Line no 6: Cannot apply leftshift to float Line no 7: Cannot apply mod to float Explanation: Enumeration constants cannot be modified, so you cannot apply ++. Bit-wise operators and % operators cannot be applied on float values. fmod() is to find the modulus values for floats as % operator is for ints. 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
Freshersworld.com Resource Center

39

First Job. Dream Job. Freshersworld.com Compiler error: undeclared function write Explanation: Pascal keyword doesnt 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
Freshersworld.com Resource Center

40

First Job. Dream Job. Freshersworld.com 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


Freshersworld.com Resource Center

41

First Job. Dream Job. Freshersworld.com

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 programmers 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;

Freshersworld.com Resource Center

42

First Job. Dream Job. Freshersworld.com 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 dont use such overloading of names. It reduces the readability of the code. Possible doesnt 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
Freshersworld.com Resource Center

43

First Job. Dream Job. Freshersworld.com 00 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 . arr2D arr2D[1] arr2D[2] arr2D[3]

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 doesnt 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); }
Freshersworld.com Resource Center

44

First Job. Dream Job. Freshersworld.com 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 1s 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 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;
Freshersworld.com Resource Center

124)

45

First Job. Dream Job. Freshersworld.com 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. 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:
Freshersworld.com Resource Center

46

First Job. Dream Job. Freshersworld.com 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. main() { char str1[] = {s,o,m,e}; char str2[] = {s,o,m,e,\0}; while (strcmp(str1,str2)) printf(Strings are not equal\n); }
Freshersworld.com Resource Center

131)

47

First Job. Dream Job. Freshersworld.com 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 doesnt 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. void main() { static int i; while(i<=10) (i>2)?i++:i--; printf(%d, i); } Answer:
Freshersworld.com Resource Center

134)

48

First Job. Dream Job. Freshersworld.com 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' a="Hi" : legal : illegal

Freshersworld.com Resource Center

49

First Job. Dream Job. Freshersworld.com 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: 41 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 expressions 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 expressions 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
Freshersworld.com Resource Center

50

First Job. Dream Job. Freshersworld.com 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.

Freshersworld.com Resource Center

51

First Job. Dream Job. Freshersworld.com 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. 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
Freshersworld.com Resource Center

145)

52

First Job. Dream Job. Freshersworld.com 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 2 3 4 5 6 7 8 9 1 4 7 2 5 8 3 6 9 1 2 3 4 5 6 7 8 9 1 4 7 2 5 8 3 6 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:
Freshersworld.com Resource Center

53

First Job. Dream Job. Freshersworld.com 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 doesnt 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: 11 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: 21 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.

Freshersworld.com Resource Center

54

First Job. Dream Job. Freshersworld.com 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. 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. Declare an array of N pointers to functions returning pointers to functions returning pointers to characters? Answer: (char*(*)( )) (*ptr[N])( ); main() { struct student { char name[30]; struct date dob; }stud; struct date
Freshersworld.com Resource Center

152)

153)

55

First Job. Dream Job. Freshersworld.com { int day,month,year; }; scanf("%s%d%d%d", stud.rollno, &student.dob.month, &student.dob.year);

&student.dob.day,

} Answer: Compiler Error: Undefined structure date Explanation: Inside the struct definition of student the member of type struct date is given. The compiler doesnt 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.month, &student.dob.year);

&student.dob.day,

} 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))
Freshersworld.com Resource Center

56

First Job. Dream Job. Freshersworld.com { 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). What is wrong with the following code? int *foo() { int *s = malloc(sizeof(int)100); assert(s != NULL); return s; } Answer & Explanation:
Freshersworld.com Resource Center

158)

57

First Job. Dream Job. Freshersworld.com assert macro should be used for debugging and finding out bugs. The check s != NULL is for error/exception handling and for that assert shouldnt 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: Dont use expressions that have side-effects in assert statements. 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'. #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.
Freshersworld.com Resource Center

160)

161)

58

First Job. Dream Job. Freshersworld.com 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. 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. Is the following code legal? typedef struct a { int x; aType *b;
Freshersworld.com Resource Center

163)

164)

59

First Job. Dream Job. Freshersworld.com }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. 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. 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 *)); }
Freshersworld.com Resource Center

166)

167)

60

First Job. Dream Job. Freshersworld.com 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. 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. 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.

169)

170)

Freshersworld.com Resource Center

61

First Job. Dream Job. Freshersworld.com 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. 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. 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()
Freshersworld.com Resource Center

172)

173)

62

First Job. Dream Job. Freshersworld.com { 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() { { { } 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: extern int i; int i=20; const volatile unsigned i=30; printf("%d",i);

Freshersworld.com Resource Center

63

First Job. Dream Job. Freshersworld.com 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 doesnt 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.

Freshersworld.com Resource Center

64

Best & TOP c++ Interview questions.... Q1: Tell how to check whether a linked list is circular. A: Create two pointers, each set to the start of the list. Update each as follows: while (pointer1) { pointer1 = pointer1->next; pointer2 = pointer2->next; if (pointer2) pointer2=pointer2->next; if (pointer1 == pointer2) { print (\"circular\n\"); } } Q2: OK, why does this work? If a list is circular, at some point pointer2 will wrap around and be either at the item just before pointer1, or the item before that. Either way, its either 1 or 2 jumps until they meet. How can you quickly find the number of elements stored in a a) static array b) dynamic array ? Why is it difficult to store linked list in an array? How can you find the nodes with repetetive data in a linked list? Write a prog to accept a given string in any order and flash error if any of the character is different. For example : If abc is the input then abc, bca, cba, cab bac are acceptable but aac or bcd are unacceptable. This is a C question that I had for an intern position at Microsoft: Write out a function that prints out all the permutations of a string. For example, abc would give you abc, acb, bac, bca, cab, cba. You can assume that all the characters will be unique. After I wrote out my function, he asked me to figure out from the code how many times the printf statement is run, and also questions on optimizing my algorithm. 1. i think this will work for while(node) { If(node==start) printf(circular); node=node->next; }

2. How about those codes: node = start->next; while(node) { if(node == start) { printf(circular); return; }

node = node->next; } 3. The posted solution is flawed in that it can (and usually will) seg-fault on non-circular lists. A correct solution should have a not circular result as well. 4. how can u find no of elements in an array quickly? if it is a dynamic array(linked list) the tradition is to keep the count variable in the head and incrementing it everytime an insertion is performed and decrementing whenever a deletion is performed.so by seeing that count vaiable we can easily tell no. of elements. 5. Write a prog to accept a given string in any order and flash error if any of the character is different. For example : If abc is the input then abc, bca, cba, cab bac are acceptable but aac or bcd are unacceptable. program ************************************************** #define true 1 #define false 0 int* isalreadyread; /* this array is used to make sure that int main(void) the characters in the original,which r matched with a char { in the dup is marked as already read*/ char* original; /* this string holds the original string like..abc*/ char* dup; /* this string is used to hold the duplicates like acb bac cab cba*/ int isokay(char* ,char* ); /* this is the function(which intern calls many) which checks whether the string is okay*/ int origlength; int flag; void initilaizing_isalreadyread(); printf(\n enter the original string); scanf(%s,original); origlength=strlen(original); isalreadyread=(int*) calloc(origlength,sizeof(int)); flag=true; while(flag) { printf(enter the duplicate string);scanf(%s,dup); initializing_isread(origlength); flag=isokay(original,dup); if(flag) printf(%s,dup); } } /* end of main*/ int isokay(char* original,char* dup) { int reflength=strlen(original); int duplength=strlen(dup); int found(char c,char* str); if(reflength!=duplength) return false; /* this is obvious*/ for(int i=0;i

6. Write out a function that prints out all the permutations of a string. For example, abc would give you abc, acb, bac, bca, cab, cba. It can be observed that the number of combinations of string, of length N, is N!. Consider an example: string: 123 Length: 3 Combination: 3! = 6 Output: 123 132 321 312 231 213 Following is a program to print all the combination a string: 1 /* 2 * str_combi.c - Print all the combinations of a string 3 * Author - Vijay Kumar R Zanvar 4 * Date - Feb 16, 2004 5 */ 6 7 #include 8 #include 9 #include 10 11 void 12 string_combi ( char * s, int len ) 13 { 14 int i; 15 char tmp; 16 static int j; 17 static char *p; 18 19 if ( !p ) 20 p = s; 21 22 for ( i = 1; i 2 ) 25 string_combi ( s+1, len-1 ); 26 else 27 { 28 j++; 29 printf ( %d: %s\t, j, p ); 30 if ( !( j%10 ) ) 31 puts ( ); 32 } 33 if ( i

7. Got a question that extends on the detecting circular linked list question: Given the constraints that you cannot modify the struct (or class) of the elements, and that you have to remove the loop in the cyclic linked list in O(n) time and O(1) space, how would you do it? By removing the loop, I mean something like: _______________________________ __ __ __ _| __ __ __ _| | | -> | | -> | | -> | | -> | | -> | | -> | | -> | | Given this linked list, how do you make the last element in the list to point to NULL in O(n) time and O(1) space? I couldnt think of a solution that uses O(1) space without modifying

the structure. If I was allowed, I could just have a visited flag inside the struct. Ill then have 2 pointers, a current and a previous. For every node traversed by the current, I will set the flag to true, and each traversal, I will check whether that flag is set to true. If it is, then the previous pointer is the last element of the list, and I can just set the next to NULL. This will also be in O(n) time. Any insights on this? 8. The picture of the linked list was kinda screwed up Anyway, that picture has 8 elements, with the last element pointing to the 4th element, thus making a loop in the list. 9. answer for finding that link list is circular is int count=0; while (node) { if(node == start && count != 0) { printf(Circular); exit(0); } p = node->next; q = node->next; if(node == start) node->next = null; 10. answer for finding that link list is circular is int count=0; while (node) { if(node == start && count != 0) { printf(Circular); exit(0); } p = node->next; q = node->next; if(node == start) node->next = null; else node->next = r; p->next = node; node = q; r = p; count = count + 3; } 11. iscircular(Node* head) /* check whether a link list is circular */ { /* assume that linklist has a header which keeps a count of no. of nodes in the list */ Node* temp=head; while(head->data) temp=temp->next; if(temp->next=head->next)/*1st node actually is next node to head*/ return TRUE; return FALSE;

} 12. constructor can be static or not?and why? in c++

13. Not to mention the glaring access-violation once pointer2 becomes NULL(though this error indicates not circular), the unnecessity of traversing pointer1(though doing so does not impact numof iterations), and the lack of terminating conditions(though still technically within the guidlines by only checking for circular), the solution is FLAWED in that it will print Circular for non-circular lists with 1 node!!! (when Pointer1 and Pointer2 are both NULL) I did think it was a kinda cool idea to weed out the noncircular lists in (num of Nodes)/2 iterations, but the extra traversal code i think outweighs any benefit. My elegant solution, if i do say so myself: //assert: list is not empty for(node=head->next; node!=NULL && node!=head; node=node->next); if(node==NULL) cout 14. oops, that last statement should read: if(node==NULL) printf(Non-circular); else printf(Circular); 15. dawid, i dont think my code is lack of terminating condition. i have put while(head->data) but i should have copied that head->data into a temporary variable. it should look like int temp1=head->data while(temp1) i dont think it will print circular for all single node lists. if thenext of the single node is the address of the nodeit will print circular. otherwise it will print not circular. the idea is to get the address in the next field of the last node (node which was inserted latest) i dont think there is a better way than traversing to reach last node. Andin ur code u assumed that the last nodes next point to the Head. i think its not a good design. it ruins the whole list then. 16. Sorry karthikeyan, I should have been more clear: I was referring to the original solution (by default). It seems to have been torn up enough already, but i wanted to show off my fancy 1 line traversal. However, in rebuttal: -Youre fired! Mistaking an equality operator(==) with an assignment (=) is an offense punishable by death. -Your solution is unintelligible with that mangled loop condition. However relying on a count of num of nodes makes your algorithm possibly unscalable to lists with dummy nodes, for example. -A chain of pointers will either end in a NULL pointer(if programmed responsibly), or youll eventually be back where you started again. I dont see how this testing ruins a list. Your point is noted, though, about a list with a dummy head that is bypassed around the circle (Like this: -0 ); but that doesnt look like a circle to me, and I feel that head should point to the first node and any extra

information should be stored in a wrapping class (because starting at the front of the list would mean dereferencing twice; silly if traversed many times each game loop, for example). However, to address that issue for those small standalone-pointers-as-lists, you would send the first real node ( head->next ) to this function. It is not completely efficient in that there is no specific head to terminate at - you must traverse all the way back around to the given node, but it works for any list. My beautiful(concise) function, if i do say so myself: bool isCircular(Node* node1) { if(node1==NULL) return false; for(Node* node2=node1->next; node2!=NULL && node2!=node1; node2=node2->next); return (node2!=NULL); } Regards, Dawid. 17. dawid, ur code looks efficient 18. 19. David, your code does not work in case the loop does not begin with the first element. For example: A->B->C->D->C I agree though that the question was check that a linked list is circular and not check that a linked list contains a circle. 20. int main(int argc, char* argv[]) { //Write a prog to accept a given string in any order and flash error if any of //the character is different. For example : If abc is the input then abc, //bca, cba, cab bac are acceptable but aac or bcd are unacceptable. //program char code[100]; char ip[100]; int i,count,flag=0; puts(Enter the string:); scanf(%s,ip); puts(Enter the comparision string:); scanf(%s,code); for(i=0;i For more tutorials & very gud stuff visit www.sureshkumar.net

IMPORTANT: Do you know that more than 20,000 CHETANA members got jobs ? It's very simple to subscribe to "CHETANA-JOBS".

To directly subscribe through e-mail, just send a blank mail to : CHETANA-JOBS-subscribe@yahoogroups.com

C/C++ Interview Questions


The following article is taken from the Dr. Dobb's Journal, September 1996. It recommends suitable methods for interviewing C++ job applicants.

Wanted: Senior C++ Programmer


by Al Stevens
The questions are in three categories: * The first category probes whether applicants have a rudimentary understanding of the differences between C and C++. * The second category examines their grasp of class design. * The third determines how well they have kept abreast of language changes that.

Questions to Qualify an Applicant


Q: Do you have a basic understanding of C and C++ and their similarities and differences? A: Yes. If the answer is "yes," proceed and plan to ask all the questions in the first group. If not, the interview for a C++ programmer's job should be over, and you should be talking about other employment opportunities. Q: Have you participated in the design of C++ classes to support an application's problem domain? A: Yes or No. If the answer is "yes," plan to include the questions in the second group. Applicants usually want to describe the details of the systems they have designed. Pay attention if you understand the nature of the application. If not, pretend to pay attention. If they have not actually done any class design, ask if they think they understand it. If so, include the second set of questions. Q: Do you keep up with what the ANSI C++ Standards committee is doing? A: Yes or No.

Most people do not. Few people have the time. But occasionally there is that rare soul who reads all the magazines and books, owns a copy of the draft standard, and regularly tracks the C++ news groups on the net. If an applicant claims to be one of them, include the third group of questions in your interrogation. Questions for All Applicants Here's the first group of questions and my opinions about what some acceptable answers would be. These questions do not cover C++ wall-to-wall, of course. I selected them as typical of the kind of knowledge that all C++ programmers should be expected to possess. There are five questions. Three correct answers is a good score. Q: How do you link a C++ program to C functions? A: By using the extern "C" linkage specification around the C function declarations. Programmers should know about mangled function names and type-safe linkages. Then they should explain how the extern "C" linkage specification statement turns that feature off during compilation so that the linker properly links function calls to C functions. Another acceptable answer is "I don't know. We never had to do that." Merely describing what a linker does indicates that the programmer does not understand the issue that underlies the question. Q: Explain the scope resolution operator. A: It permits a program to reference an identifier in the global scope that has been hidden by another identifier with the same name in the local scope. The answer can get complicated. However, it should start with "::". If the programmer is well into the design or use of classes that employ inheritance you might hear a lot about overriding member function overrides to explicitly call a function higher in the hierarchy. That's good to know, but ask specifically about global scope resolution. You're looking for a description of C++'s ability to override the particular C behavior where identifiers in the global scope are always hidden by like identifiers in a local scope. Q: What are the differences between a C++ struct and C++ class? A: The default member and base-class access specifiers are different. This is one of the commonly misunderstood aspects of C++. Believe it or not, many programmers think that a C++ struct is just like a C struct, while a C++ class has inheritance, access specifiers, member functions, overloaded operators, and so on. Some of them have even written books about C++. Actually, the C++ struct has all the features of the class. The only differences are that a struct defaults to public member access and public base-class inheritance, and a class defaults to the private access specifier and private base-class inheritance. Getting this question wrong does not necessarily disqualify an applicant. Getting it right is a definite plus.

Saying, "I don't know" is definitely the wrong answer. I advance an unusual position about this. C++ programmers should at least believe that they know the differences, even when they are wrong about them. Getting it wrong is, therefore, right. You can explain the true difference in the interview and advance the programmer's knowledge. If they disagree vociferously, you have an opportunity to observe how they handle contentious debate when they are wrong and don't know it yet. Q: How many ways are there to initialize an int with a constant? A: Two. There are two formats for initializers in C++ as shown in the example that follows. The first format uses the traditional C notation. The second format uses constructor notation. int foo = 123; int bar (123); It's acceptable when a programmer does not know about the second notation, although they should certainly know about the first one. Many old-timer C programmers who made the switch to C++ never use the second idiom, although some wise heads of C++ profess to prefer it. If your applicant is quick with the right answer, that's a good sign. Q: How does throwing and catching exceptions differ from using setjmp and longjmp? A: The throw operation calls the destructors for automatic objects instantiated since entry to the try block. Exceptions are in the mainstream of C++ now, so most programmers, if they are familiar with setjmp and longjmp, should know the difference. Both idioms return a program from the nested depths of multiple function calls to a defined position higher in the program. The program stack is "unwound" so that the state of the program, with respect to function calls and pushed arguments, is restored as if the calls had not been made. C++ exception handling adds to that behavior the orderly calls to the destructors of automatic objects that were instantiated as the program proceeded from within the try block toward where the throw expression is evaluated. Applicants might think you want to hear about the notational differences between the two idioms. Let them proceed to explain the syntax of try blocks, catch exception handlers, and throw expressions. Then ask them specifically what happens in a throw that does not happen in a longjmp. Their answer should reflect an understanding of the behavior described in the previous answer. One valid reason for not knowing about exception handling is that the applicant's experience is exclusively with older C++ compilers that do not implement exception handling. I would prefer that they have at least heard of exception handling, though. Another marginally acceptable reason is that their former supervisors and designers did not mandate and specify the use of exception handling in programs. In that case

get the names of those supervisors and designers so that you can decline their applications if they should come a'knocking. It is not unusual for C and C++ programmers to be unfamiliar with setjmp/ longjmp. Those constructs are not particularly intuitive. A C programmer who has written recursive descent parsing algorithms will certainly be familiar with setjmp/longjmp. Others might not, and that's acceptable. In that case, they won't be able to discuss how setjmp/longjmp differs from C++ exception handling, but let the interview turn into a discussion of C++ exception handling in general. That conversation will reveal a lot about a programmer's understanding of C++.

Questions for Class Designers


The second group of questions explores the applicant's knowledge of class design. There are eight questions. Five out of eight is a good score. Q: What is your reaction to this line of code? delete this; A: It's not a good practice. Many applicants will look at you like you are nuts. They've never heard of this usage, and it's never occurred to them. That's a very good answer. Perhaps they will try to explain the behavior of the statement. Ask them to contemplate its consequences. Two quite acceptable reactions are, "Don't do it," and "Don't do it unless you really know what you are doing and you are a masochist." A good programmer will insist that you should absolutely never use the statement if the class is to be used by other programmers and instantiated as static, extern, or automatic objects. That much should be obvious. The code has two built-in pitfalls. First, if it executes in a member function for an extern, static, or automatic object, the program will probably crash as soon as the delete statement executes. There is no portable way for an object to tell that it was instantiated on the heap, so the class cannot assert that its object is properly instantiated. Second, when an object commits suicide this way, the using program might not know about its demise. As far as the instantiating program is concerned, the object remains in scope and continues to exist even though the object did itself in. Subsequent dereferencing of the pointer can and usually does lead to disaster. I think that the language rules should disallow the idiom, but that's another matter. In More Effective C++ (Addison-Wesley, 1996), Scott Meyers devotes one of his items to "delete this," implying that there are valid applications for the idiom and advancing contrived code kludges to make it seem to work better. A programmer who has read this otherwise very good book might think that the practice is acceptable. Experience leads me to disagree. Q: What is a default constructor?

A: A constructor that has no arguments. If you don't code one, the compiler provides one if there are no other constructors. If you are going to instantiate an array of objects of the class, the class must have a default constructor. Q: What is a conversion constructor? A: A constructor that accepts one argument of a different type. The compiler uses this idiom as one way to infer conversion rules for your class. A constructor with more than one argument and with default argument values can be interpreted by the compiler as a conversion constructor when the compiler is looking for an object of your constructor's type and sees an object of the type of the constructor's first argument. Q: What is the difference between a copy constructor and an overloaded assignment operator? A: A copy constructor constructs a new object by using the content of the argument object. An overloaded assignment operator assigns the contents of an existing object to another existing object of the same class. First, the applicant must know that a copy constructor is one that has only one argument of the same type as the constructor. The compiler invokes a copy constructor wherever it needs to make a copy of the object, for example to pass an argument by value. If you do not provide a copy constructor, the compiler creates a member- by-member copy constructor for you. You can write overloaded assignment operators that take arguments of other classes, but that behavior is usually implemented with implicit conversion constructors. If you do not provide an overloaded assignment operator for the class, the compiler creates a default member- by-member assignment operator. This discussion is a good place to get into why classes need copy constructors and overloaded assignment operators. If the applicant discusses these with respect to data member pointers that point to dynamically allocated resources, the applicant probably has a good grasp of the problem. Q: When should you use multiple inheritance? A: There are three acceptable answers: "Never," "Rarely," and "When the problem domain cannot be accurately modeled any other way." There are some famous C++ pundits and luminaries who disagree with that third answer, but I will accept it. Let's digress to consider this issue lest your interview turn into a religious debate. Consider an Asset class, Building class, Vehicle class, and CompanyCar class. All company cars are vehicles. Some company cars are assets because the organizations own them. Others might be leased. Not all assets are vehicles. Money accounts are

assets. Real estate holdings are assets. Some real estate holdings are buildings. Not all buildings are assets. Ad infinitum. When you diagram these relationships, it becomes apparent that multiple inheritance is a likely and intuitive way to model this common problem domain. The applicant should understand, however, that multiple inheritance, like a chainsaw, is a useful tool that has its perils, needs respect, and is best avoided except when nothing else will do. Q: What is a virtual destructor? A: The simple answer is that a virtual destructor is one that is declared with the virtual attribute. The behavior of a virtual destructor is what is important. If you destroy an object through a pointer or reference to a base class, and the base-class destructor is not virtual, the derived-class destructors are not executed, and the destruction might not be complete. Q: Explain the ISA and HASA class relationships. How would you implement each in a class design? A: A specialized class "is" a specialization of another class and, therefore, has the ISA relationship with the other class. An Employee ISA Person. This relationship is best implemented with inheritance. Employee is derived from Person. A class may have an instance of another class. For example, an employee "has" a salary, therefore the Employee class has the HASA relationship with the Salary class. This relationship is best implemented by embedding an object of the Salary class in the Employee class. The answer to this question reveals whether the applicant has an understanding of the fundamentals of object- oriented design, which is important to reliable class design. There are other relationships. The USESA relationship is when one class uses the services of another. The Employee class uses an object (cout) of the ostream class to display the employee's name on the screen, for example. But if the applicant gets ISA and HASA right, you don't need to go any further. Q: When is a template a better solution than a base class? A: When you are designing a generic class to contain or otherwise manage objects of other types, when the format and behavior of those other types are unimportant to their containment or management, and particularly when those other types are unknown (thus, the genericity) to the designer of the container or manager class. Prior to templates, you had to use inheritance; your design might include a generic List container class and an application-specific Employee class. To put employees in a list, a ListedEmployee class is multiply derived (contrived) from the Employee and List classes. These solutions were unwieldy and error-prone. Templates solved that problem.

Questions for ANSI-Knowledgeable Applicants

There are six questions for those who profess knowledge of the progress of the ANSI committee. If you claim to have that much interest in the language, you should know the answers to all these questions. Q: What is a mutable member? A: One that can be modified by the class even when the object of the class or the member function doing the modification is const. Understanding this requirement implies an understanding of C++ const, which many programmers do not have. I have seen large class designs that do not employ the const qualifier anywhere. Some of those designs are my own early C++ efforts. One author suggests that some programmers find const to be such a bother that it is easier to ignore const than to try to use it meaningfully. No wonder many programmers don't understand the power and implications of const. Someone who claims to have enough interest in the language and its evolution to keep pace with the ANSI deliberations should not be ignorant of const, however. Q: What is an explicit constructor? A: A conversion constructor declared with the explicit keyword. The compiler does not use an explicit constructor to implement an implied conversion of types. It's purpose is reserved explicitly for construction. Q: What is the Standard Template Library? A: A library of container templates approved by the ANSI committee for inclusion in the standard C++ specification. A programmer who then launches into a discussion of the generic programming model, iterators, allocators, algorithms, and such, has a higher than average understanding of the new technology that STL brings to C++ programming. Q: Describe run-time type identification. A: The ability to determine at run time the type of an object by using the typeid operator or the dynamic_cast operator. Q: What problem does the namespace feature solve? A: Multiple providers of libraries might use common global identifiers causing a name collision when an application tries to link with two or more such libraries. The namespace feature surrounds a library's external declarations with a unique namespace that eliminates the potential for those collisions. This solution assumes that two library vendors don't use the same namespace identifier, of course. Q: Are there any new intrinsic (built-in) data types?

A: Yes. The ANSI committee added the bool intrinsic type and its true and false value keywords. Other apparent new types (string, complex, and so on) are implemented as classes in the Standard C++ Library rather than as intrinsic types.

C/C++ Questions
These are sample questions. Personally I hate asking questions related to code. If you want some old question papers of some Indian IT industries , You many find it here

1. What is the output of printf("%d") 2. What will happen if I say delete this 3. Difference between "C structure" and "C++ structure". 4. Diffrence between a "assignment operator" and a "copy constructor" 5. What is the difference between "overloading" and "overridding"? 6. Explain the need for "Virtual Destructor". 7. Can we have "Virtual Constructors"? 8. What are the different types of polymorphism? 9. What are Virtual Functions? How to implement virtual functions in "C" 10. What are the different types of Storage classes? 11. What is Namespace? 12. What are the types of STL containers?. 13. Difference between "vector" and "array"? 14. How to write a program such that it will delete itself after exectution? 15. Can we generate a C++ source code from the binary file? 16. What are inline functions? 17. Talk sometiming about profiling? 18. How many lines of code you have written for a single program? 19. What is "strstream" ? 20. How to write Multithreaded applications using C++? 21. Explain "passing by value", "passing by pointer" and "passing by reference" 22. Write any small program that will compile in "C" but not in "C++" 23. Have you heard of "mutable" keyword? 24. What is a "RTTI"? 25. Is there something that I can do in C and not in C++? 26. Why preincrement operator is faster than postincrement? 27. What is the difference between "calloc" and "malloc"? 28. What will happen if I allocate memory using "new" and free it using "free" or allocate sing "calloc" and free it using "delete"? 29. What is Memory Alignment? 30. Explain working of printf. 31. Difference between "printf" and "sprintf". 32. What is "map" in STL? 33. When shall I use Multiple Inheritance? 34. What are the techniques you use for debugging?

35. How to reduce a final size of executable? 36. Give 2 examples of a code optimization.

Java Interview Questions


1. Meaning - Abstract classes, abstract methods 2. Difference - Java,C++ 3. Difference between == and equals method 4. Explain Java security model 5. Explain working of Java Virtual Machine (JVM) 6. Difference : Java Beans, Servlets 7. Difference : AWT, Swing 8. Disadvantages of Java 9. What is BYTE Code ? 10. What gives java it's "write once and run anywhere" nature? 11. Does Java have "goto"? 12. What is the meaning of "final" keyword? 13. Can I create final executable from Java? 14. Explain Garbage collection mechanism in Java 15. Why Java is not 100% pure object oriented language? 16. What are interfaces? or How to support multiple inhertance in Java? 17. How to use C++ code in Java Program? 18. Difference between "APPLET" and "APPLICATION"

||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| Q: How do you link a C++ program to C functions? A: By using the extern "C" linkage specification around the C function declarations. Q: Explain the scope resolution operator. A: It permits a program to reference an identifier in the global scope that has been hidden by another identifier with the same name in the local scope. Q: What are the differences between a C++ struct and C++ class? A: The default member and base-class access specifiers are different. Q: How many ways are there to initialize an int with a constant? A: Two.

There are two formats for initializers in C++ as shown in the example that follows. The first format uses the traditional C notation. The second format uses constructor notation. int foo = 123; int bar (123); Q: How does throwing and catching exceptions differ from using setjmp and longjmp? A: The throw operation calls the destructors for automatic objects instantiated since entry to the try block. Q: What is your reaction to this line of code? delete this; A: It's not a good practice. Q: What is a default constructor? A: A constructor that has no arguments. Q: What is a conversion constructor? A: A constructor that accepts one argument of a different type. Q: What is the difference between a copy constructor and an overloaded assignment operator? A: A copy constructor constructs a new object by using the content of the argument object. An overloaded assignment operator assigns the contents of an existing object to another existing object of the same class. Q: When should you use multiple inheritance? A: There are three acceptable answers: "Never," "Rarely," and "When the problem domain cannot be accurately modeled any other way." Q: What is a virtual destructor? A: The simple answer is that a virtual destructor is one that is declared with the virtual attribute. Q: Explain the ISA and HASA class relationships. How would you implement each in a class design?

A: A specialized class "is" a specialization of another class and, therefore, has the ISA relationship with the other class. An Employee ISA Person. This relationship is best implemented with inheritance. Employee is derived from Person. A class may have an instance of another class. For example, an employee "has" a salary, therefore the Employee class has the HASA relationship with the Salary class. This relationship is best implemented by embedding an object of the Salary class in the Employee class. Q: When is a template a better solution than a base class? A: When you are designing a generic class to contain or otherwise manage objects of other types, when the format and behavior of those other types are unimportant to their containment or management, and particularly when those other types are unknown (thus, the genericity) to the designer of the container or manager class. Q: What is a mutable member? A: One that can be modified by the class even when the object of the class or the member function doing the modification is const. Q: What is an explicit constructor? A: A conversion constructor declared with the explicit keyword. The compiler does not use an explicit constructor to implement an implied conversion of types. It's purpose is reserved explicitly for construction. Q: What is the Standard Template Library? A: A library of container templates approved by the ANSI committee for inclusion in the standard C++ specification. A programmer who then launches into a discussion of the generic programming model, iterators, allocators, algorithms, and such, has a higher than average understanding of the new technology that STL brings to C++ programming. Q: Describe run-time type identification. A: The ability to determine at run time the type of an object by using the typeid operator or the dynamic_cast operator. Q: What problem does the namespace feature solve? A: Multiple providers of libraries might use common global identifiers causing a name collision when an application tries to link with two or more such libraries. The namespace feature surrounds a library's external declarations with a unique namespace that eliminates the potential for those collisions.

This solution assumes that two library vendors don't use the same namespace identifier, of course. Q: Are there any new intrinsic (built-in) data types? A: Yes. The ANSI committee added the bool intrinsic type and its true and false value keywords. |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| Q1: What are the advantages of OOPL? Ans: Object oriented programming languages directly represent the real life objects. The features of OOPL as inhreitance, polymorphism, encapsulation makes it powerful. Q2: What do mean by polymorphisum, inheritance, encapsulation? Ans: Polymorhisum: is a feature of OOPl that at run time depending upon the type of object the appropriate method is called. Inheritance: is a feature of OOPL that represents the "is a" relationship between different objects(classes). Say in real life a manager is a employee. So in OOPL manger class is inherited from the employee class. Encapsulation: is a feature of OOPL that is used to hide the information. Q3: What do you mean by static methods? Ans: By using the static method there is no need creating an object of that class to use that method. We can directly call that method on that class. For example, say class A has static function f(), then we can call f() function as A.f(). There is no need of creating an object of class A. Q4: What do you mean by virtual methods? Ans: virtual methods are used to use the polymorhism feature in C++. Say class A is inherited from class B. If we declare say fuction f() as virtual in class B and override the same function in class A then at runtime appropriate method of the class will be called depending upon the type of the object. Q5: Given two tables Student(SID, Name, Course) and Level(SID, level) write the SQL statement to get the name and SID of the student who are taking course = 3 and at freshman level. Ans: SELECT Student.name, Student.SID FROM Student, Level WHERE Student.SID = Level.SID

AND Level.Level = "freshman" AND Student.Course = 3; Q6: What are the disadvantages of using threads? Ans: DeadLock. Q1: Write the Java code to declare any constant (say gravitational constant) and to get its value Ans: Class ABC { static final float GRAVITATIONAL_CONSTANT = 9.8; public void getConstant() { system.out.println("Gravitational_Constant: " + GRAVITATIONAL_CONSTANT); } } Q2: What do you mean by multiple inheritance in C++ ?

Ans: Multiple inheritance is a feature in C++ by which one class can be of different types. Say class teachingAssistant is inherited from two classes say teacher and Student. Q3: Can you write Java code for declaration of multiple inheritance in Java ? Ans: Class C extends A implements B { } |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

C++ interview questions


1. Design and implement a String class that satisfies the following:

Supports embedded nulls Provide the following methods (at least) o Constructor o Destructor o Copy constructor o Assignment operator o Addition operator (concatenation) o Return character at location o Return substring at location o Find substring

Provide versions of methods for String and for char* arguments

2. Given the following classes class Fruit { // ... } class Apple : public Fruit { // ... } class Peach : public Fruit { // ... } // Container of fruit class BasketOfFruit { BasketOfFruit() ; void insert( Fruit & f ) ; // ... } // Container of apples class BasketOfApples /* ??? */ { // ... } Should BasketOfApples derive from BasketOfFruit? Why or why not? What is the general principle that determines the answer? 3. Describe briefly what the following function does. What standard function is it most like ? int f( char *p ) { int n = 0 ; while ( *p != 0 ) n = 10*n + *p++ - '0' ; return n ; } 4. Describe briefly what function 'a' does in the following code fragment. struct s { struct s *next ; }

a( struct s *p, struct s *x ) { while ( p-next != 0 ) p = p-next ; p-next = x ; x-next = 0 ; } 5. What default methods are declared implicitly by the C++ compiler for the class below: class Empty { }; 6. Given a system with a hard realtime priority, multithreaded architecture, with priorities from 1 (least) to 5 (most), explain the major flaw in the design below: The following objects are shared between the threads: Disk : This class is a singleton. The read() and write() methods both block on a simple atomic lock()/unlock() shared between the two. (ie, only one thread can access the disk, thru either read or write, at any given time). It also has a waitForData() method, which blocks (without claiming the lock) until either a timeout elapses, or data is ready. It returns true upon returning due to new data, false upon returning due to the timeout. Network : This class is a singleton. The read() and write() methods both block on a simple atomic lock()/unlock() shared between the two. (ie, only one thread can access the disk, thru either read or write, at any given time). Sensor: The Sensor class accesses a number of physical sensors. The first method, 'waitForData()', blocks until data has been collected from the sensors. The second method, 'processData()', does a series of long and cpu-intensive calculations on the data. These calculations often take several minutes. It then returns the processed data. Each of the following threads is running concurrently. Assume that the psuedocode in each thread is looped infinitely (ie, encased in a while(true) { }. It is extremely important that information buffered to the disk be sent to the network as quickly as possible, this is why Thread 1 runs at priority 5. The system conditions checked in thread 3 are not particularly important events (not as important as the calculations done in thread 2). If the events aren't transmitted over the network for several minutes, it's not a problem at all. They do, however, contain a large amount of system information. Thread 4 watches for serious system alarms, indicating serious problems. These are a serious concern and if not quickly buffered to the disk and sent to the network, can cause serious revenue loss. Thread 1: (priority: 5) while(!Disk.waitForData()) { yield(); } /* Wait until someone has written data to the disk */ Network.write(Disk.read()); /* Write the data buffered on

the disk to the network */ Thread 2: (priority: 2) while(!Sensor.waitForData()) { yield(); } /* Wait until the sensors have picked up data */ Disk.write(Sensor.processData()); /* process the data and write it to the disk. */ Thread 3: (priority: 1) if (checkSystemCondition1()) /* true.. */ Disk.write(SystemCond1Data); /* condition and buffer it to disk if (checkSystemCondition2()) /* Disk.write(SystemCond2Data); if (checkSystemCondition3()) /* Disk.write(SystemCond3Data); yield(); If system condition 1 is Grab the data on the system */ see above*/ see above */

Thread 4: (priority: 4) if (checkAlarms()) /* If any serious alarms exist */ Disk.write(AlarmData); /* Buffer that data to disk for immediate network transmit */ yield(); 1. In C++, what is the difference between method overloading and method overwriting? Overloading a method (or function) in C++ is the ability for functions of the same name to be defined as long as these methods have different signatures (different set of parameters). Method overwriting is the ability of the inherited class rewriting the virtual method of the base class. 2. What methods can be overwritten in Java? In C++ terminalogy, all public methods in Java are virtual. Therefore, all Java methods can be overwritten in subclasses except those that are declared final, static, and private. 3. In C, What is the difference between a static variable and global variable?

A static variable declared outside of any function is accessible only to all the functions defined in the same file (as the static variable). However, a global variable can be accessed by any function (including the ones from different files). 4. In C, why is the void pointer useful? The void pointer is useful becuase it is a generic pointer that any pointer can be cast into and back again without loss of information. 5. What are the defining traits of an object-oriented language? The defining traits of an object-oriented langauge are:

encapsulation inheritance polymorphism

Q: What is the difference between Stack and Queue? A: Stack is a Last In First Out (LIFO) data structure. Queue is a First In First Out (FIFO) data structure Q: Write a fucntion that will reverse a string. (Microsoft) A: char *strrev(char *s) { int i = 0, len = strlen(s); char *str; if ((str = (char *)malloc(len+1)) == NULL) /*cannot allocate memory */ err_num = 2; return (str); } while(len) str[i++]=s[--len]; str[i] = NULL;

return (str); } Q: What is the software Life-Cycle? A: The software Life-Cycle are 1) Analysis and specification of the task 2) Design of the algorithms and data structures 3) Implementation (coding) 4) Testing 5) Maintenance and evolution of the system 6) Obsolescence Q: What is the difference between a Java application and a Java applet? A: The difference between a Java application and a Java applet is that a Java application is a program that can be executed using the Java interpeter, and a JAVA applet can be transfered to different networks and executed by using a web browser (transferable to the WWW). Q: Name 7 layers of the OSI Reference Model? (from Cisco) A: -Application layer -Presentation layer -Session layer -Transport layer -Network layer -Data Link layer -Physical layer

1.Question: Suppose that data is an array of 1000 integers. Write a single function call that will sort the 100 elements data [222] through data [321]. Answer: quicksort ((data + 222), 100); 2.Question: Which recursive sorting technique always makes recursive calls to sort subarrays that are about half size of the original array? Answer: Mergesort always makes recursive calls to sort subarrays that are about half size of the original array, resulting in O(n log n) time. 3.Question: What is the difference between an external iterator and an internal iterator? Describe an advantage of an external iterator. Answer: .An internal iterator is implemented with member functions of the class that has items to step through. .An external iterator is implemented as a separate class that can be "attach" to the object that has items to step through. .An external iterator has the advantage that many difference iterators can be active simultaneously on the same object. 4.Question: Why are arrays usually processed with for loop? Answer: The real power of arrays comes from their facility of using an index variable to traverse the array, accessing each element with the same expression a[i]. All the is needed to make this work is a iterated statement in which the variable i serves as a counter, incrementing from 0 to a.length -1. That is exactly what a loop does.

5.Question: What is an HTML tag? Answer: An HTML tag is a syntactical construct in the HTML language that abbreviates specific instructions to be executed when the HTML script is loaded into a Web browser. It is like a method in Java, a function in C++, a procedure in Pascal, or a subroutine in FORTRAN. 1. How do you write a function that can reverse a linked-list? (Cisco System) void reverselist(void) { if(head==0) return; if(head->next==0) return; if(head->next==tail) {

head->next = 0; tail->next = head; } else { node* pre = head; node* cur = head->next; node* curnext = cur->next; head->next = 0; cur->next = head; for(; curnext!=0; ) { cur->next = pre; pre = cur; cur = curnext; curnext = curnext->next; } curnext->next = cur; } } 2. What is polymorphism? Polymorphism is the idea that a base class can be inherited by several classes. A base class pointer can point to its child class and a base class array can store different child class objects.

3. How do you find out if a linked-list has an end? (i.e. the list is not a cycle) You can find out by using 2 pointers. One of them goes 2 nodes each time. The second one goes at 1 nodes each time. If there is a cycle, the one that goes 2 nodes each time will eventually meet the one that goes slower. If that is the case, then you will know the linked-list is a cycle. 4. How can you tell what shell you are running on UNIX system? You can do the Echo $RANDOM. It will return a undefined variable if you are from the C-Shell, just a return prompt if you are from the Bourne shell, and a 5 digit random numbers if you are from the Korn shell. You could also do a ps -l and look for the shell with the highest PID. 5. What is Boyce Codd Normal form? A relation schema R is in BCNF with respect to a set F of functional dependencies if for all functional dependencies in F+ of the form a->b, where a and b is a subset of R, at least one of the following holds: a->b is a trivial functional dependency (b is a subset of a) a is a superkey for schema R What is a Make file?(Fujitsu) Ans: Make file is a utility in Unix to help compile large programs. It helps by only compiling the portion of the program that has been changed. 2. What is deadlock?(Novell) Deadlock is a situation when two or more processes prevent each other from running. Example: if T1 is holding x and waiting for y to be free and T2 holding y and waiting for x to be free deadlock happens. 3. What is a Semaphore?(Novell) Semaphore is a special variable, it has two methods: up and down. Semaphore performs atomic operations, which means ones a semaphore is called it can not be inturrupted. 4. Is C an Object Oriented language?(Microsoft) C is not an Object Oriented language, but limited Object Oriented programming can be done in C. 5. What is difference between C++ and Java? C++ has pointers Java does not. Java is platform independent C++ is not.

Java has garbage collection C++ does not. QUESTION: What is a JavaBean? (asked by Lifescan inc) ANSWER: JavaBeans are reusable software components written in the Java programming language, designed to be manipulated visually by a software develpoment environment, like JBuilder or VisualAge for Java. They are similar to Microsoft's ActiveX components, but designed to be platform-neutral, running anywhere there is a Java Virtual Machine (JVM). QUESTION: What are the seven layers(OSI model) of networking? (asked by Caspio.com) ANSWER: 1.Physical, 2.Data Link, 3.Network, 4.Transport, 5.Session, 6.Presentation and 7.Application Layers. QUESTION: What are some advantages and disadvantages of Java Sockets? (asked by Arashsoft.com) ANSWER: Advantages of Java Sockets: Sockets are flexible and sufficient. Efficient socket based programming can be easily implemented for general communications. Sockets cause low network traffic. Unlike HTML forms and CGI scripts that generate and transfer whole web pages for each new request, Java applets can send only necessary updated information. Disadvantages of Java Sockets: Security restrictions are sometimes overbearing because a Java applet running in a Web browser is only able to establish connections to the machine where it came from, and to nowhere else on the network Despite all of the useful and helpful Java features, Socket based communications allows only to send packets of raw data between applications. Both the client-side and serverside have to provide mechanisms to make the data useful in any way. Since the data formats and protocols remain application specific, the re-use of socket based implementations is limited. QUESTION: What is the difference between a NULL pointer and a void pointer? (asked by Lifescan inc)

ANSWER: A NULL pointer is a pointer of any type whose value is zero. A void pointer is a pointer to an object of an unknown type, and is guaranteed to have enough bits to hold a pointer to any object. A void pointer is not guaranteed to have enough bits to point to a function (though in general practice it does). QUESTION: What is encapsulation technique? (asked by Microsoft) ANSWER: Hiding data within the class and making it available only through the methods. This technique is used to protect your class against accidental changes to fields, which might leave the class in an inconsistent state.

Questions
L1.Q1 : Write the output of the following program
#include #define ABC #define XYZ #define XXX void main() { int 20 10 ABC - XYZ

a;

a = XXX * 10; printf("%d\n", a); }

Solution for L1.Q1

L1.Q2 : Write the output of this program


#include #define calc(a, b) (a * b) / (a - b)

void main() { int a = 20, b = 10; printf("%d\n", calc(a + 4, b -2)); }

Solution for L1.Q2

L1.Q3 : What will be output of the following program ?


#include void main() { int cnt = 5, a; do { a /= cnt; } while (cnt --); printf ("%d\n", a); }

Solution for L1.Q3

L1.Q4 : Print the output of this program


#include void main() { int a, b, c, abc = 0; a = b = c = 40; if (c) { int abc; abc = a*b+c; } printf ("c = %d, abc = %d\n", c, abc); }

Solution for L1.Q4

L1.Q5 : Print the output of this program


#include main() { int k = 5; if (++k < 5 && k++/5 || ++k <= 8); printf("%d\n", k);

Solution for L1.Q5

L1.Q6 : What is the output of this program ?


#include void fn(int, int); main() { int a = 5; %d %d\n", a++, ++a);

printf("Main : fn(a, a++); }

void fn(int a, int b) { printf("Fn : a = %d \t b = %d\n", a, b); }

Solution for L1.Q6

Answers
L1.A1 Solution for L1.Q1
a = xxx * 10 which is => a => a => a => a = = = = ABC - XYZ * 10 20 - 10 * 10 20 - 100 -80

L1.A2 Solution for L1.Q2


Actual substitution is like this : calc(20+4, 10 -2) is calculated as follows (20+4 * 10-2) / (20+4 - 10-2)

since

(20+40-2) / 12 58 / 12 = 4.8 it is printed in %d the ans is 4

L1.A3 Solution for L1.Q3


This problem will compile properly, but it will give run time error. It will give divide-by-zero error. Look in to the do loop portion do { a /= cnt; } while (cnt --); when the 'cnt' value is 1, it is decremented in 'while ( cnt --)' and on next reference of 'cnt' it becomes zero. a /= cnt; /* ie. a /= 0 */ which leads to divide-by-zero error.

L1.A4 Solution for L1.Q4


the result will be c = 40 and abc = 0; because the scope of the variable 'abc' inside if(c) {.. is not valid out side that if (.) { .. }. }

L1.A5 Solution for L1.Q5


The answer is 7. it is false (Now (or condition ++k point k value is becomes 7. The first condition ++k < 5 k = 6). So, it checks the <= 8) and (now k = 7) it is incremented by twice, hence is checked and 3rd condition true. At this the value of k

L1.A6 Solution for L1.Q6


The solution depends on the implementation of stack. (Depends on OS) In some machines the arguments are passed from left to right to the stack. In this case the result will be Main : 5 7 Fn : 7 7

Other machines the arguments may be passed from right to left to the stack. In that case the result will be

Main : 6 6 Fn : 8 7

C Puzzles : Questions and Answers - Level 2

Questions
L2.Q1 : Write the output of this program
#include main() { int *a, *s, i; s = a = (int *) malloc( 4 * sizeof(int)); for (i=0; i<4; i++) *(a+i) = i * 10; printf("%d\n", printf("%d\n", printf("%d\n", printf("%d\n", printf("%d\n", } *s++); (*s)++); *s); *++s); ++*s);

Solution for L2.Q1

L2.Q2 : Checkout this program result


#include void fn(int); static int main() { while (val --) fn(val); printf("%d\n", val); } void fn(int val) { static int val = 0; for (; val < 5; val ++) printf("%d\n", val); val = 5;

Solution for L2.Q2

L2.Q3 : Can you predict the output of this program ?


#include main() { typedef union { int a; char b[10]; float c; } Union; Union x, y = { 100 };

x.a = 50; strcpy (x.b, "hello"); x.c = 21.50; printf ("Union 2 : %d %s %f\n", x.a, x.b, x.c); printf ("Union Y : %d %s %f\n", y.a, y.b, y.c); }

Solution for L2.Q3

L2.Q4 : Print the output of the program


#include main() { struct Data { int a; int b; } y[4] = { 1, 10, 3, 30, 2, 20, 4, 40}; struct Data *x = y; int i; for(i=0; i<4; i++) { x->a = x->b, ++x++->b; printf("%d %d\t", y[i].a, y[i].b); } }

Solution for L2.Q4

L2.Q5 : Write the output of this program


#include main() { typedef struct int int int char int }xyz; { a; b; c; ch; d;

typedef union { xyz X; char y[100]; }abc; printf("sizeof xyz = %d sizeof abc = %d\n", sizeof(xyz), sizeof(abc)); }

Solution for L2.Q5

L2.Q6 : Find out the error in this code


#include #include #define Error(str) main() { int fd; char str[20] = "Hello! Test me"; if ((fd = open("xx", O_CREAT | O_RDWR)) < 0) Error("open failed"); if (write(fd, str, strlen(str)) < 0) Error("Write failed"); if (read(fd, str, strlen(str)) < 0) Error("read failed"); printf("File read : %s\n", str); close(fd); } printf("Error : %s\n", str); exit(1);

Solution for L2.Q6

L2.Q7 : What will be the output of this program ?


#include main() { int *a, i;

a = (int *) malloc(10*sizeof(int)); for (i=0; i<10; i++) *(a + i) = i * i; for (i=0; i<10; i++) printf("%d\t", *a++); free(a); }

Solution for L2.Q7

L2.Q8 :
Write a program to calculate number of 1's (bit) in a given integer number i.e) Number of 1's in the given integer's equivalent binary representation.

Solution for L2.Q8

Answers
L2.A1 Solution for L2.Q1
The output will be : 0 10 11 20 21 *s++ *++s ++*s => *(s++) => *(++s) => ++(*s)

L2.A2 Solution for L2.Q2

Some compiler (ansi) may give warning message, but it will compile without errors. The output will be : 0 1 2 3 4 and -1

L2.A3 Solution for L2.Q3


This is the problem about Unions. Unions are similar to structures but it differs in some ways. Unions can be assigned only with one field at any time. In this case, unions x and y can be assigned with any of the one field a or b or c at one time. During initialisation of unions it takes the value (whatever assigned ) only for the first field. So, The statement y = {100} intialises the union y with field a = 100. In this example, all fields of union x are assigned with some values. But at any time only one of the union field can be assigned. So, for the union x the field c is assigned as 21.50. Thus, The output will be Union 2 : 22 22 21.50 Union Y : 100 22 22 ( 22 refers unpredictable results )

L2.A4 Solution for L2.Q4


The pointer x points to the same location where y is stored. So, The changes in y reflects in x. The output will be : 10 11 30 31

20 21

40 41

L2.A5 Solution for L2.Q5


The output of this program is purely depends on the processor architecuture. If the sizeof integer is 4 bytes and the size of character is 1 byte (In some computers), the output will be sizeof xyz = 20 sizeof abc = 100

The output can be generalized to some extent as follows, sizeof xyz = 4 * sizeof(int) + 1 * sizeof(char) + padding bytes sizeof abc = 100 * sizeof(char) + padding bytes

To keep the structures/unions byte aligned, some padding bytes are added in between the sturcture fields. In this example 3 bytes are padded between ' char ch' and 'int d' fields. The unused bytes are called holes. To understand more about padding bytes (holes) try varing the field types of the structures and see the output.

L2.A6 Solution for L2.Q6


Just try to execute this file as such. You can find out that it will exit immediately. Do you know why? With this hint, we can trace out the error. If you look into the macro 'Error', you can easily identify that there are two separete statements without brases '{ ..}'. That is the problem. So, it exits after the calling open(). The macro should be put inside the brases like this. #define Error(str) { printf("Error : %s\n", str); exit(1); }

L2.A7 Solution for L2.Q7


This program will fault (Memory Can you predict Why? fault/segmentation fault).

Remove the statment 'free(a);' from the program, then execute the program. It will run. It gives the results correctly. What causes 'free(a)' to generate fault? Just trace the address location of pointer variable 'a'. The variable 'a' is incremented inside the 'for loop'. Out side the 'for loop' the variable 'a' will point to 'null'. When the free() call is made, it will free the data area from the base_address (which is passed as the argument of the free call) upto the length of the data allocated previously. In this case, free() tries to free the length of 10 *sizeof(int) from the base pointer location passed as the argument to the free call, which is 'null' in this case. Thus, it generates memory fault.

L2.A8 Solution for L2.Q8

#include main(argc, argv) int argc; char *argv[]; { int count = 0, i; int v = atoi(argv[1]); for(i=0; i<8*sizeof(int); i++) if(v &(1<< } count); v, %d='%d\n",' in 1?s of printf(?No count++;>

C Puzzles : Questions and Answers - Level 1

Questions
L1.Q1 : Write the output of the following program
#include #define ABC #define XYZ #define XXX void main() { int 20 10 ABC - XYZ

a;

a = XXX * 10; printf("%d\n", a); }

Solution for L1.Q1

L1.Q2 : Write the output of this program


#include #define calc(a, b) void main() { (a * b) / (a - b)

int a = 20, b = 10; printf("%d\n", calc(a + 4, b -2)); }

Solution for L1.Q2

L1.Q3 : What will be output of the following program ?


#include void main() { int cnt = 5, a; do { a /= cnt; } while (cnt --); printf ("%d\n", a); }

Solution for L1.Q3

L1.Q4 : Print the output of this program


#include void main() { int a, b, c, abc = 0; a = b = c = 40; if (c) { int abc; abc = a*b+c; } printf ("c = %d, abc = %d\n", c, abc); }

Solution for L1.Q4

L1.Q5 : Print the output of this program

#include main() { int k = 5; if (++k < 5 && k++/5 || ++k <= 8); printf("%d\n", k); }

Solution for L1.Q5

L1.Q6 : What is the output of this program ?


#include void fn(int, int); main() { int a = 5; %d %d\n", a++, ++a);

printf("Main : fn(a, a++); }

void fn(int a, int b) { printf("Fn : a = %d \t b = %d\n", a, b); }

Solution for L1.Q6

Answers
L1.A1 Solution for L1.Q1
a = xxx * 10 which is => a => a => a => a = = = = ABC - XYZ * 10 20 - 10 * 10 20 - 100 -80

L1.A2 Solution for L1.Q2


Actual substitution is like this : calc(20+4, 10 -2) is calculated as follows (20+4 * 10-2) / (20+4 - 10-2) (20+40-2) / 12 58 / 12 = 4.8 it is printed in %d the ans is 4

since

L1.A3 Solution for L1.Q3


This problem will compile properly, but it will give run time error. It will give divide-by-zero error. Look in to the do loop portion do { a /= cnt; } while (cnt --); when the 'cnt' value is 1, it is decremented in 'while ( cnt --)' and on next reference of 'cnt' it becomes zero. a /= cnt; /* ie. a /= 0 */ which leads to divide-by-zero error.

L1.A4 Solution for L1.Q4


the result will be c = 40 and abc = 0; because the scope of the variable 'abc' inside if(c) {.. is not valid out side that if (.) { .. }. }

L1.A5 Solution for L1.Q5


The answer is 7. it is false (Now (or condition ++k point k value is becomes 7. The first condition ++k < 5 k = 6). So, it checks the <= 8) and (now k = 7) it is incremented by twice, hence is checked and 3rd condition true. At this the value of k

L1.A6 Solution for L1.Q6


The solution depends on the implementation of stack.

(Depends on OS) In some machines the arguments are passed from left to right to the stack. In this case the result will be Main : 5 7 Fn : 7 7

Other machines the arguments may be passed from right to left to the stack. In that case the result will be Main : 6 6 Fn : 8 7

Essential C
By Nick Parlante
Copyright 1996-2003, Nick Parlante

This Stanford CS Education document tries to summarize all the basic features of the C language. The coverage is pretty quick, so it is most appropriate as review or for someone with some programming background in another language. Topics include variables, int types, floating point types, promotion, truncation, operators, control structures (if, while, for), functions, value parameters, reference parameters, structs, pointers, arrays, the preprocessor, and the standard C library functions. The most recent version is always maintained at its Stanford CS Education Library URL http://cslibrary.stanford.edu/101/. Please send your comments to nick.parlante@cs.stanford.edu. I hope you can share and enjoy this document in the spirit of goodwill in which it is given away -- Nick Parlante, 4/2003, Stanford California. Stanford CS Education Library This is document #101, Essential C, in the Stanford CS Education Library. This and other educational materials are available for free at http://cslibrary.stanford.edu/. This article is free to be used, reproduced, excerpted, retransmitted, or sold so long as this notice is clearly reproduced at its beginning. Table of Contents Introduction .........................................................................................pg. 2 Where C came from, what is it like, what other resources might you look at. Section 1 Basic Types and Operators ..........................................pg. 3 Integer types, floating point types, assignment operator, comparison operators, arithmetic operators, truncation, promotion. Section 2 Control Structures ........................................................pg. 11 If statement, conditional operator, switch, while, for, do-while, break, continue. Section 3 Complex Data Types .....................................................pg. 15 Structs, arrays, pointers, ampersand operator (&), NULL, C strings, typedef. Section 4 Functions ........................................................................pg. 24 Functions, void, value and reference parameters, const. Section 5 Odds and Ends ..............................................................pg. 29 Main(), the .h/.c file convention, pre-processor, assert. Section 6 Advanced Arrays and Pointers ....................................pg. 33 How arrays and pointers interact. The [ ] and + operators with pointers, base address/offset arithmetic, heap memory management, heap arrays. Section 7 Operators and Standard Library Reference ..............pg. 41 A summary reference of the most common operators and library functions. The C Language C is a professional programmer's language. It was designed to get in one's way as little as possible. Kernighan and Ritchie wrote the original language definition in their book, The C Programming Language (below), as part of their research at AT&T. Unix and C++ emerged from the same labs. For several years I used AT&T as my long distance carrier in appreciation of all that CS research, but hearing "thank you for using AT&T" for the millionth time has used up that good will.

2 Some languages are forgiving. The programmer needs only a basic sense of how things work. Errors in the code are flagged by the compile-time or run-time system, and the programmer can muddle through and eventually fix things up to work correctly. The C language is not like that. The C programming model is that the programmer knows exactly what they want to do and how to use the language constructs to achieve that goal. The language lets the expert programmer express what they want in the minimum time by staying out of their way. C is "simple" in that the number of components in the language is small-- If two language features accomplish more-or-less the same thing, C will include only one. C's syntax is terse and the language does not restrict what is "allowed" -- the programmer can pretty much do whatever they want. C's type system and error checks exist only at compile-time. The compiled code runs in a stripped down run-time model with no safety checks for bad type casts, bad array indices, or bad pointers. There is no garbage collector to manage memory. Instead the programmer mangages heap memory manually. All this makes C fast but fragile. Analysis -- Where C Fits Because of the above features, C is hard for beginners. A feature can work fine in one context, but crash in another. The programmer needs to understand how the features work and use them correctly. On the other hand, the number of features is pretty small. Like most programmers, I have had some moments of real loathing for the C language. It can be irritatingly obedient -- you type something incorrectly, and it has a way of compiling fine and just doing something you don't expect at run-time. However, as I have become a more experienced C programmer, I have grown to appreciate C's straight-to-the point style. I have learned not to fall into its little traps, and I appreciate its simplicity. Perhaps the best advice is just to be careful. Don't type things in you don't understand. Debugging takes too much time. Have a mental picture (or a real drawing) of how your C code is using memory. That's good advice in any language, but in C it's critical. Perl and Java are more "portable" than C (you can run them on different computers without a recompile). Java and C++ are more structured than C. Structure is useful for large projects. C works best for small projects where performance is important and the progammers have the time and skill to make it work in C. In any case, C is a very popular and influential language. This is mainly because of C's clean (if minimal) style, it's lack of annoying or regrettable constructs, and the relative ease of writing a C compiler. Other Resources The C Programming Language, 2nd ed., by Kernighan and Ritchie. The thin book which for years was the bible for all C programmers. Written by the original designers of the language. The explanations are pretty short, so this book is better as a reference than for beginners. http://cslibrary.stanford.edu/102/ Pointers and Memory -- Much more detail about local memory, pointers, reference parameters, and heap memory than in this article, and memory is really the hardest part of C and C++. http://cslibrary.stanford.edu//103/ Linked List Basics -- Once you understand the basics of pointers and C, these problems are a good way to get more practice.

Section 1 Basic Types and Operators


C provides a standard, minimal set of basic data types. Sometimes these are called "primitive" types. More complex data structures can be built up from these basic types. Integer Types The "integral" types in C form a family of integer types. They all behave like integers and can be mixed together and used in similar ways. The differences are due to the different number of bits ("widths") used to implement each type -- the wider types can store a greater ranges of values. char ASCII character -- at least 8 bits. Pronounced "car". As a practical matter char is basically always a byte which is 8 bits which is enough to store a single ASCII character. 8 bits provides a signed range of -128..127 or an unsigned range is 0..255. char is also required to be the "smallest addressable unit" for the machine -each byte in memory has its own address. short Small integer -- at least 16 bits which provides a signed range of -32768..32767. Typical size is 16 bits. Not used so much. int Default integer -- at least 16 bits, with 32 bits being typical. Defined to be the "most comfortable" size for the computer. If you do not really care about the range for an integer variable, declare it int since that is likely to be an appropriate size (16 or 32 bit) which works well for that machine. long Large integer -- at least 32 bits. Typical size is 32 bits which gives a signed range of about -2 billion ..+2 billion. Some compilers support "long long" for 64 bit ints. The integer types can be preceded by the qualifier unsigned which disallows representing negative numbers, but doubles the largest positive number representable. For example, a 16 bit implementation of short can store numbers in the range -32768..32767, while unsigned short can store 0..65535. You can think of pointers as being a form of unsigned long on a machine with 4 byte pointers. In my opinion, it's best to avoid using unsigned unless you really need to. It tends to cause more misunderstandings and problems than it is worth. Extra: Portability Problems Instead of defining the exact sizes of the integer types, C defines lower bounds. This makes it easier to implement C compilers on a wide range of hardware. Unfortunately it occasionally leads to bugs where a program runs differently on a 16-bit-int machine than it runs on a 32-bit-int machine. In particular, if you are designing a function that will be implemented on several different machines, it is a good idea to use typedefs to set up types like Int32 for 32 bit int and Int16 for 16 bit int. That way you can prototype a function Foo(Int32) and be confident that the typedefs for each machine will be set so that the function really takes exactly a 32 bit int. That way the code will behave the same on all the different machines. char Constants A char constant is written with single quotes (') like 'A' or 'z'. The char constant 'A' is really just a synonym for the ordinary integer value 65 which is the ASCII value for

4 uppercase 'A'. There are special case char constants, such as '\t' for tab, for characters which are not convenient to type on a keyboard. 'A' '\n' '\t' '\0' uppercase 'A' character newline character tab character the "null" character -- integer value 0 (different from the char digit '0')

'\012' the character with value 12 in octal, which is decimal 10 int Constants Numbers in the source code such as 234 default to type int. They may be followed by an 'L' (upper or lower case) to designate that the constant should be a long such as 42L. An integer constant can be written with a leading 0x to indicate that it is expressed in hexadecimal -- 0x10 is way of expressing the number 16. Similarly, a constant may be written in octal by preceding it with "0" -- 012 is a way of expressing the number 10. Type Combination and Promotion The integral types may be mixed together in arithmetic expressions since they are all basically just integers with variation in their width. For example, char and int can be combined in arithmetic expressions such as ('b' + 5). How does the compiler deal with the different widths present in such an expression? In such a case, the compiler "promotes" the smaller type (char) to be the same size as the larger type (int) before combining the values. Promotions are determined at compile time based purely on the types of the values in the expressions. Promotions do not lose information -- they always convert from a type to compatible, larger type to avoid losing information. Pitfall -- int Overflow I once had a piece of code which tried to compute the number of bytes in a buffer with the expression (k * 1024) where k was an int representing the number of kilobytes I wanted. Unfortunately this was on a machine where int happened to be 16 bits. Since k and 1024 were both int, there was no promotion. For values of k >= 32, the product was too big to fit in the 16 bit int resulting in an overflow. The compiler can do whatever it wants in overflow situations -- typically the high order bits just vanish. One way to fix the code was to rewrite it as (k * 1024L) -- the long constant forced the promotion of the int. This was not a fun bug to track down -- the expression sure looked reasonable in the source code. Only stepping past the key line in the debugger showed the overflow problem. "Professional Programmer's Language." This example also demonstrates the way that C only promotes based on the types in an expression. The compiler does not consider the values 32 or 1024 to realize that the operation will overflow (in general, the values don't exist until run time anyway). The compiler just looks at the compile time types, int and int in this case, and thinks everything is fine. Floating point Types float Single precision floating point number typical size: 32 bits double Double precision floating point number typical size: 64 bits long double Possibly even bigger floating point number (somewhat obscure) Constants in the source code such as 3.14 default to type double unless the are suffixed with an 'f' (float) or 'l' (long double). Single precision equates to about 6 digits of

5 precision and double is about 15 digits of precision. Most C programs use double for their computations. The main reason to use float is to save memory if many numbers need to be stored. The main thing to remember about floating point numbers is that they are inexact. For example, what is the value of the following double expression?
(1.0/3.0 + 1.0/3.0 + 1.0/3.0) // is this equal to 1.0 exactly?

The sum may or may not be 1.0 exactly, and it may vary from one type of machine to another. For this reason, you should never compare floating numbers to eachother for equality (==) -- use inequality (<) comparisons instead. Realize that a correct C program run on different computers may produce slightly different outputs in the rightmost digits of its floating point computations. Comments Comments in C are enclosed by slash/star pairs: /* .. comments .. */ which may cross multiple lines. C++ introduced a form of comment started by two slashes and extending to the end of the line: // comment until the line end The // comment form is so handy that many C compilers now also support it, although it is not technically part of the C language. Along with well-chosen function names, comments are an important part of well written code. Comments should not just repeat what the code says. Comments should describe what the code accomplishes which is much more interesting than a translation of what each statement does. Comments should also narrate what is tricky or non-obvious about a section of code. Variables As in most languages, a variable declaration reserves and names an area in memory at run time to hold a value of particular type. Syntactically, C puts the type first followed by the name of the variable. The following declares an int variable named "num" and the 2nd line stores the value 42 into num.
int num; num = 42;

num

42

A variable corresponds to an area of memory which can store a value of the given type. Making a drawing is an excellent way to think about the variables in a program. Draw each variable as box with the current value inside the box. This may seem like a "beginner" technique, but when I'm buried in some horribly complex programming problem, I invariably resort to making a drawing to help think the problem through. Variables, such as num, do not have their memory cleared or set in any way when they are allocated at run time. Variables start with random values, and it is up to the program to set them to something sensible before depending on their values. Names in C are case sensitive so "x" and "X" refer to different variables. Names can contain digits and underscores (_), but may not begin with a digit. Multiple variables can be declared after the type by separating them with commas. C is a classical "compile time" language -- the names of the variables, their types, and their implementations are all flushed out by the compiler at compile time (as opposed to figuring such details out at run time like an interpreter).

6
float x, y, z, X;

Assignment Operator = The assignment operator is the single equals sign (=).
i = 6; i = i + 1;

The assignment operator copies the value from its right hand side to the variable on its left hand side. The assignment also acts as an expression which returns the newly assigned value. Some programmers will use that feature to write things like the following.
y = (x = 2 * x); // double x, and also put x's new value in y

Truncation The opposite of promotion, truncation moves a value from a type to a smaller type. In that case, the compiler just drops the extra bits. It may or may not generate a compile time warning of the loss of information. Assigning from an integer to a smaller integer (e.g.. long to int, or int to char) drops the most significant bits. Assigning from a floating point type to an integer drops the fractional part of the number.
char ch; int i; i = 321; ch = i; // truncation of an int value to fit in a char // ch is now 65

The assignment will drop the upper bits of the int 321. The lower 8 bits of the number 321 represents the number 65 (321 - 256). So the value of ch will be (char)65 which happens to be 'A'. The assignment of a floating point type to an integer type will drop the fractional part of the number. The following code will set i to the value 3. This happens when assigning a floating point number to an integer or passing a floating point number to a function which takes an integer.
double pi; int i; pi = 3.14159; i = pi; // truncation of a double to fit in an int // i is now 3

Pitfall -- int vs. float Arithmetic Here's an example of the sort of code where int vs. float arithmetic can cause problems. Suppose the following code is supposed to scale a homework score in the range 0..20 to be in the range 0..100.
{ int score; ...// suppose score gets set in the range 0..20 somehow

score = (score / 20) * 100; ...

// NO -- score/20 truncates to 0

Unfortunately, score will almost always be set to 0 for this code because the integer division in the expression (score/20) will be 0 for every value of score less than 20. The fix is to force the quotient to be computed as a floating point number...
score = ((double)score / 20) * 100; score = (score / 20.0) * 100; score = (int)(score / 20.0) * 100; // OK -- floating point division from cast // OK -- floating point division from 20.0 // NO -- the (int) truncates the floating // quotient back to 0

No Boolean -- Use int C does not have a distinct boolean type-- int is used instead. The language treats integer 0 as false and all non-zero values as true. So the statement...
i = 0; while (i - 10) { ...

will execute until the variable i takes on the value 10 at which time the expression (i 10) will become false (i.e. 0). (we'll see the while() statement a bit later) Mathematical Operators C includes the usual binary and unary arithmetic operators. See the appendix for the table of precedence. Personally, I just use parenthesis liberally to avoid any bugs due to a misunderstanding of precedence. The operators are sensitive to the type of the operands. So division (/) with two integer arguments will do integer division. If either argument is a float, it does floating point division. So (6/4) evaluates to 1 while (6/4.0) evaluates to 1.5 -- the 6 is promoted to 6.0 before the division. + Addition - Subtraction / Division * Multiplication % Remainder (mod) Unary Increment Operators: ++ -The unary ++ and -- operators increment or decrement the value in a variable. There are "pre" and "post" variants for both operators which do slightly different things (explained below) var++ ++var increment increment "post" variant "pre" variant

8 var---var decrement decrement "post" variant "pre" variant

int i = 42; i++; // increment on i // i is now 43 i--; // decrement on i // i is now 42

Pre and Post Variations The Pre/Post variation has to do with nesting a variable with the increment or decrement operator inside an expression -- should the entire expression represent the value of the variable before or after the change? I never use the operators in this way (see below), but an example looks like...
int i = 42; int j; j = (i++ + 10); // i is now 43 // j is now 52 (NOT 53) j = (++i + 10) // i is now 44 // j is now 54

C Programming Cleverness and Ego Issues Relying on the difference between the pre and post variations of these operators is a classic area of C programmer ego showmanship. The syntax is a little tricky. It makes the code a little shorter. These qualities drive some C programmers to show off how clever they are. C invites this sort of thing since the language has many areas (this is just one example) where the programmer can get a complex effect using a code which is short and dense. If I want j to depend on i's value before the increment, I write...
j = (i + 10); i++;

Or if I want to j to use the value after the increment, I write...


i++; j = (i + 10);

Now then, isn't that nicer? (editorial) Build programs that do something cool rather than programs which flex the language's syntax. Syntax -- who cares? Relational Operators These operate on integer or floating point values and return a 0 or 1 boolean value. == Equal

9 != > < >= <= Not Equal Greater Than Less Than Greater or Equal Less or Equal

To see if x equals three, write something like:


if (x == 3) ...

Pitfall An absolutely classic pitfall is to write assignment (=) when you mean comparison (==). This would not be such a problem, except the incorrect assignment version compiles fine because the compiler assumes you mean to use the value returned by the assignment. This is rarely what you want
if (x = 3) ...

==

This does not test if x is 3. This sets x to the value 3, and then returns the 3 to the if for testing. 3 is not 0, so it counts as "true" every time. This is probably the single most common error made by beginning C programmers. The problem is that the compiler is no help -- it thinks both forms are fine, so the only defense is extreme vigilance when coding. Or write "= ==" in big letters on the back of your hand before coding. This mistake is an absolute classic and it's a bear to debug. Watch Out! And need I say: "Professional Programmer's Language." Logical Operators The value 0 is false, anything else is true. The operators evaluate left to right and stop as soon as the truth or falsity of the expression can be deduced. (Such operators are called "short circuiting") In ANSI C, these are furthermore guaranteed to use 1 to represent true, and not just some random non-zero bit pattern. However, there are many C programs out there which use values other than 1 for true (non-zero pointers for example), so when programming, do not assume that a true boolean is necessarily 1 exactly. ! && || Boolean not (unary) Boolean and Boolean or

Bitwise Operators C includes operators to manipulate memory at the bit level. This is useful for writing lowlevel hardware or operating system code where the ordinary abstractions of numbers, characters, pointers, etc... are insufficient -- an increasingly rare need. Bit manipulation code tends to be less "portable". Code is "portable" if with no programmer intervention it compiles and runs correctly on different types of computers. The bitwise operations are

10 typically used with unsigned types. In particular, the shift operations are guaranteed to shift 0 bits into the newly vacated positions when used on unsigned values. ~ & | ^ >> << Bitwise Negation (unary) flip 0 to 1 and 1 to 0 throughout Bitwise And Bitwise Or Bitwise Exclusive Or Right Shift by right hand side (RHS) (divide by power of 2) Left Shift by RHS (multiply by power of 2)

Do not confuse the Bitwise operators with the logical operators. The bitwise connectives are one character wide (&, |) while the boolean connectives are two characters wide (&&, ||). The bitwise operators have higher precedence than the boolean operators. The compiler will never help you out with a type error if you use & when you meant &&. As far as the type checker is concerned, they are identical-- they both take and produce integers since there is no distinct boolean type. Other Assignment Operators In addition to the plain = operator, C includes many shorthand operators which represents variations on the basic =. For example "+=" adds the right hand side to the left hand side. x = x + 10; can be reduced to x += 10;. This is most useful if x is a long expression such as the following, and in some cases it may run a little faster.
person->relatives.mom.numChildren += 2; // increase children by 2

Here's the list of assignment shorthand operators... +=, -= Increment or decrement by RHS *=, /= Multiply or divide by RHS %= >>= <<= Mod by RHS Bitwise right shift by RHS (divide by power of 2) Bitwise left shift RHS (multiply by power of 2) Bitwise and, or, xor by RHS

&=, |=, ^=

11

Section 2 Control Structures


Curly Braces {} C uses curly braces ({}) to group multiple statements together. The statements execute in order. Some languages let you declare variables on any line (C++). Other languages insist that variables are declared only at the beginning of functions (Pascal). C takes the middle road -- variables may be declared within the body of a function, but they must follow a '{'. More modern languages like Java and C++ allow you to declare variables on any line, which is handy. If Statement Both an if and an if-else are available in C. The <expression> can be any valid expression. The parentheses around the expression are required, even if it is just a single variable.
if (<expression>) <statement> // simple form with no {}'s or else clause

if (<expression>) { <statement> <statement> }

// simple form with {}'s to group statements

if (<expression>) { <statement> } else { <statement> }

// full then/else form

Conditional Expression -or- The Ternary Operator The conditional expression can be used as a shorthand for some if-else statements. The general syntax of the conditional operator is:
<expression1> ? <expression2> : <expression3>

This is an expression, not a statement, so it represents a value. The operator works by evaluating expression1. If it is true (non-zero), it evaluates and returns expression2 . Otherwise, it evaluates and returns expression3. The classic example of the ternary operator is to return the smaller of two variables. Every once in a while, the following form is just what you needed. Instead of...
if (x < y) { min = x; } else { min = y; }

12 You just say...


min = (x < y) ? x : y;

Switch Statement The switch statement is a sort of specialized form of if used to efficiently separate different blocks of code based on the value of an integer. The switch expression is evaluated, and then the flow of control jumps to the matching const-expression case. The case expressions are typically int or char constants. The switch statement is probably the single most syntactically awkward and error-prone features of the C language.
switch (<expression>) { case <const-expression-1>: <statement> break; case <const-expression-2>: <statement> break; case <const-expression-3>: case <const-expression-4>: <statement> break; default: // optional <statement> } // here we combine case 3 and 4

Each constant needs its own case keyword and a trailing colon (:). Once execution has jumped to a particular case, the program will keep running through all the cases from that point down -- this so called "fall through" operation is used in the above example so that expression-3 and expression-4 run the same statements. The explicit break statements are necessary to exit the switch. Omitting the break statements is a common error -- it compiles, but leads to inadvertent fall-through behavior. Why does the switch statement fall-through behavior work the way it does? The best explanation I can think of is that originally C was developed for an audience of assembly language programmers. The assembly language programmers were used to the idea of a jump table with fall-through behavior, so that's the way C does it (it's also relatively easy to implement it this way.) Unfortunately, the audience for C is now quite different, and the fall-through behavior is widely regarded as a terrible part of the language. While Loop The while loop evaluates the test expression before every loop, so it can execute zero times if the condition is initially false. It requires the parenthesis like the if.
while (<expression>) { <statement> }

13 Do-While Loop Like a while, but with the test condition at the bottom of the loop. The loop body will always execute at least once. The do-while is an unpopular area of the language, most everyone tries to use the straight while if at all possible.
do { <statement> } while (<expression>)

For Loop The for loop in C is the most general looping construct. The loop header contains three parts: an initialization, a continuation condition, and an action.
for (<initialization>; <continuation>; <action>) { <statement> }

The initialization is executed once before the body of the loop is entered. The loop continues to run as long as the continuation condition remains true (like a while). After every execution of the loop, the action is executed. The following example executes 10 times by counting 0..9. Many loops look very much like the following...
for (i = 0; i < 10; i++) { <statement> }

C programs often have series of the form 0..(some_number-1). It's idiomatic in C for the above type loop to start at 0 and use < in the test so the series runs up to but not equal to the upper bound. In other languages you might start at 1 and use <= in the test. Each of the three parts of the for loop can be made up of multiple expressions separated by commas. Expressions separated by commas are executed in order, left to right, and represent the value of the last expression. (See the string-reverse example below for a demonstration of a complex for loop.) Break The break statement will move control outside a loop or switch statement. Stylistically speaking, break has the potential to be a bit vulgar. It's preferable to use a straight while with a single test at the top if possible. Sometimes you are forced to use a break because the test can occur only somewhere in the midst of the statements in the loop body. To keep the code readable, be sure to make the break obvious -- forgetting to account for the action of a break is a traditional source of bugs in loop behavior.
while (<expression>) { <statement> <statement> if (<condition which can only be evaluated here>) break; <statement> <statement> } // control jumps down here on the break

14

The break does not work with if. It only works in loops and switches. Thinking that a break refers to an if when it really refers to the enclosing while has created some high quality bugs. When using a break, it's nice to write the enclosing loop to iterate in the most straightforward, obvious, normal way, and then use the break to explicitly catch the exceptional, weird cases. Continue The continue statement causes control to jump to the bottom of the loop, effectively skipping over any code below the continue. As with break, this has a reputation as being vulgar, so use it sparingly. You can almost always get the effect more clearly using an if inside your loop.
while (<expression>) { ... if (<condition>) continue; ... ... // control jumps here on the continue }

15

Section 3 Complex Data Types


C has the usual facilities for grouping things together to form composite types-- arrays and records (which are called "structures"). The following definition declares a type called "struct fraction" that has two integer sub fields named "numerator" and "denominator". If you forget the semicolon it tends to produce a syntax error in whatever thing follows the struct declaration.
struct fraction { int numerator; int denominator; }; // Don't forget the semicolon!

This declaration introduces the type struct fraction (both words are required) as a new type. C uses the period (.) to access the fields in a record. You can copy two records of the same type using a single assignment statement, however == does not work on structs.
struct fraction f1, f2; f1.numerator = 22; f1.denominator = 7; f2 = f1; // this copies over the whole struct // declare two fractions

Arrays The simplest type of array in C is one which is declared and used in one place. There are more complex uses of arrays which I will address later along with pointers. The following declares an array called scores to hold 100 integers and sets the first and last elements. C arrays are always indexed from 0. So the first int in scores array is scores[0] and the last is scores[99].
int scores[100]; scores[0] = 13; scores[99] = 42; // set first element // set last element

16 The name of the array refers to the whole array. (implementation) it works by representing a pointer to the start of the array.

scores

13 Index 0 1

-5673 2

22541 99

42

There is space for each int element in the scores array this element is referred to as scores[0].

These elements have random values because the code has not yet initialized them to anything.

Someone elses memory off either end of the array do not read or write this memory.

It's a very common error to try to refer to non-existent scores[100] element. C does not do any run time or compile time bounds checking in arrays. At run time the code will just access or mangle whatever memory it happens to hit and crash or misbehave in some unpredictable way thereafter. "Professional programmer's language." The convention of numbering things 0..(number of things - 1) pervades the language. To best integrate with C and other C programmers, you should use that sort of numbering in your own data structures as well. Multidimensional Arrays The following declares a two-dimensional 10 by 10 array of integers and sets the first and last elements to be 13.
int board [10][10]; board[0][0] = 13; board[9][9] = 13;

The implementation of the array stores all the elements in a single contiguous block of memory. The other possible implementation would be a combination of several distinct one dimensional arrays -- that's not how C does it. In memory, the array is arranged with the elements of the rightmost index next to each other. In other words, board[1][8] comes right before board[1][9] in memory. (highly optional efficiency point) It's typically efficient to access memory which is near other recently accessed memory. This means that the most efficient way to read through a chunk of the array is to vary the rightmost index the most frequently since that will access elements that are near each other in memory.

17 Array of Structs The following declares an array named "numbers" which holds 1000 struct fraction's.
struct fraction numbers[1000]; numbers[0].numerator = 22; numbers[0].denominator = 7; /* set the 0th struct fraction */

Here's a general trick for unraveling C variable declarations: look at the right hand side and imagine that it is an expression. The type of that expression is the left hand side. For the above declarations, an expression which looks like the right hand side (numbers[1000], or really anything of the form numbers[...]) will be the type on the left hand side (struct fraction). Pointers A pointer is a value which represents a reference to another value sometimes known as the pointer's "pointee". Hopefully you have learned about pointers somewhere else, since the preceding sentence is probably inadequate explanation. This discussion will concentrate on the syntax of pointers in C -- for a much more complete discussion of pointers and their use see http://cslibrary.stanford.edu/102/, Pointers and Memory. Syntax Syntactically C uses the asterisk or "star" (*) to indicate a pointer. C defines pointer types based on the type pointee. A char* is type of pointer which refers to a single char. a struct fraction* is type of pointer which refers to a struct fraction.
int* intPtr; // declare an integer pointer variable intPtr

char* charPtr; // declares a character pointer -// a very common type of pointer

// Declare two struct fraction pointers // (when declaring multiple variables on one line, the * // should go on the right with the variable) struct fraction *f1, *f2;

The Floating "*" In the syntax, the star is allowed to be anywhere between the base type and the variable name. Programmer's have their own conventions-- I generally stick the * on the left with the type. So the above declaration of intPtr could be written equivalently...
int *intPtr; int * intPtr; int* intPtr; // these are all the same

Pointer Dereferencing We'll see shortly how a pointer is set to point to something -- for now just assume the pointer points to memory of the appropriate type. In an expression, the unary * to the left of a pointer dereferences it to retrieve the value it points to. The following drawing shows the types involved with a single pointer pointing to a struct fraction.

18
struct fraction* f1;

f1

7 22

denominator numerator

struct fraction* struct fraction (the whole block of memory)


Expression f1 *f1 (*f1).numerator Type struct fraction* struct fraction int

int (within block of memory)

There's an alternate, more readable syntax available for dereferencing a pointer to a struct. A "->" at the right of the pointer can access any of the fields in the struct. So the reference to the numerator field could be written f1->numerator. Here are some more complex declarations...
struct fraction** fp; // a pointer to a pointer to a struct fraction // an array of 20 struct fractions // an array of 20 pointers to // struct fractions

struct fraction fract_array[20]; struct fraction* fract_ptr_array[20];

One nice thing about the C type syntax is that it avoids the circular definition problems which come up when a pointer structure needs to refer to itself. The following definition defines a node in a linked list. Note that no preparatory declaration of the node pointer type is necessary.
struct node { int data; struct node* next; };

The & Operator The & operator is one of the ways that pointers are set to point to things. The & operator computes a pointer to the argument to its right. The argument can be any variable which takes up space in the stack or heap (known as an "LValue" technically). So &i and &(f1->numerator) are ok, but &6 is not. Use & when you have some memory, and you want a pointer to that memory.

19
void foo() { int* p; // p is a pointer to an integer int i; // i is an integer p = &i; // Set p to point to i *p = 13; // Change what p points to -- in this case i -- to 13 // At this point i is 13. So is *p. In fact *p is i. }

p i 13

When using a pointer to an object created with &, it is important to only use the pointer so long as the object exists. A local variable exists only as long as the function where it is declared is still executing (we'll see functions shortly). In the above example, i exists only as long as foo() is executing. Therefore any pointers which were initialized with &i are valid only as long as foo() is executing. This "lifetime" constraint of local memory is standard in many languages, and is something you need to take into account when using the & operator. NULL A pointer can be assigned the value 0 to explicitly represent that it does not currently have a pointee. Having a standard representation for "no current pointee" turns out to be very handy when using pointers. The constant NULL is defined to be 0 and is typically used when setting a pointer to NULL. Since it is just 0, a NULL pointer will behave like a boolean false when used in a boolean context. Dereferencing a NULL pointer is an error which, if you are lucky, the computer will detect at runtime -- whether the computer detects this depends on the operating system. Pitfall -- Uninitialized Pointers When using pointers, there are two entities to keep track of. The pointer and the memory it is pointing to, sometimes called the "pointee". There are three things which must be done for a pointer/pointee relationship to work... (1) The pointer must be declared and allocated (2) The pointee must be declared and allocated (3) The pointer (1) must be initialized so that it points to the pointee (2) The most common pointer related error of all time is the following: Declare and allocate the pointer (step 1). Forget step 2 and/or 3. Start using the pointer as if it has been setup to point to something. Code with this error frequently compiles fine, but the runtime results are disastrous. Unfortunately the pointer does not point anywhere good unless (2) and (3) are done, so the run time dereference operations on the pointer with * will misuse and trample memory leading to a random crash at some point.

20
{ int* p; *p = 13; } // NO NO NO p does not point to an int yet // this just overwrites a random area in memory

p i -14346

Of course your code won't be so trivial, but the bug has the same basic form: declare a pointer, but forget to set it up to point to a particular pointee. Using Pointers Declaring a pointer allocates space for the pointer itself, but it does not allocate space for the pointee. The pointer must be set to point to something before you can dereference it. Here's some code which doesn't do anything useful, but which does demonstrate (1) (2) (3) for pointer use correctly...
int* p; // (1) allocate the pointer int i; // (2) allocate pointee struct fraction f1; // (2) allocate pointee p = &i; *p = 42; // (3) setup p to point to i // ok to use p since it's setup // (3) setup p to point to a different int

p = &(f1.numerator); *p = 22; p = &(f1.denominator); *p = 7;

// (3)

So far we have just used the & operator to create pointers to simple variables such as i. Later, we'll see other ways of getting pointers with arrays and other techniques. C Strings C has minimal support of character strings. For the most part, strings operate as ordinary arrays of characters. Their maintenance is up to the programmer using the standard facilities available for arrays and pointers. C does include a standard library of functions which perform common string operations, but the programmer is responsible for the managing the string memory and calling the right functions. Unfortunately computations involving strings are very common, so becoming a good C programmer often requires becoming adept at writing code which manages strings which means managing pointers and arrays.

21 A C string is just an array of char with the one additional convention that a "null" character ('\0') is stored after the last real character in the array to mark the end of the string. The compiler represents string constants in the source code such as "binky" as arrays which follow this convention. The string library functions (see the appendix for a partial list) operate on strings stored in this way. The most useful library function is strcpy(char dest[], const char source[]); which copies the bytes of one string over to another. The order of the arguments to strcpy() mimics the arguments in of '=' -- the right is assigned to the left. Another useful string function is strlen(const char string[]); which returns the number of characters in C string not counting the trailing '\0'. Note that the regular assignment operator (=) does not do string copying which is why strcpy() is necessary. See Section 6, Advanced Pointers and Arrays, for more detail on how arrays and pointers work. The following code allocates a 10 char array and uses strcpy() to copy the bytes of the string constant "binky" into that local array.
{ char localString[10]; strcpy(localString, "binky"); }

localString

b 0

i 1

2 ...

The memory drawing shows the local variable localString with the string "binky" copied into it. The letters take up the first 5 characters and the '\0' char marks the end of the string after the 'y'. The x's represent characters which have not been set to any particular value. If the code instead tried to store the string "I enjoy languages which have good string support" into localString, the code would just crash at run time since the 10 character array can contain at most a 9 character string. The large string will be written passed the right hand side of localString, overwriting whatever was stored there. String Code Example Here's a moderately complex for loop which reverses a string stored in a local array. It demonstrates calling the standard library functions strcpy() and strlen() and demonstrates that a string really is just an array of characters with a '\0' to mark the effective end of the string. Test your C knowledge of arrays and for loops by making a drawing of the memory for this code and tracing through its execution to see how it works.

22
{ char string[1000]; int len; // string is a local 1000 char array

strcpy(string, "binky"); len = strlen(string); /* Reverse the chars in the string: i starts at the beginning and goes up j starts at the end and goes down i/j exchange their chars as they go until they meet */ int i, j; char temp; for (i = 0, j = len - 1; i < j; i++, j--) { temp = string[i]; string[i] = string[j]; string[j] = temp; } // at this point the local string should be "yknib" }

"Large Enough" Strings The convention with C strings is that the owner of the string is responsible for allocating array space which is "large enough" to store whatever the string will need to store. Most routines do not check that size of the string memory they operate on, they just assume its big enough and blast away. Many, many programs contain declarations like the following...
{ char localString[1000]; ... }

The program works fine so long as the strings stored are 999 characters or shorter. Someday when the program needs to store a string which is 1000 characters or longer, then it crashes. Such array-not-quite-big-enough problems are a common source of bugs, and are also the source of so called "buffer overflow" security problems. This scheme has the additional disadvantage that most of the time when the array is storing short strings, 95% of the memory reserved is actually being wasted. A better solution allocates the string dynamically in the heap, so it has just the right size. To avoid buffer overflow attacks, production code should check the size of the data first, to make sure it fits in the destination string. See the strlcpy() function in Appendix A. char* Because of the way C handles the types of arrays, the type of the variable localString above is essentially char*. C programs very often manipulate strings using variables of type char* which point to arrays of characters. Manipulating the actual chars in a string requires code which manipulates the underlying array, or the use

23 of library functions such as strcpy() which manipulate the array for you. See Section 6 for more detail on pointers and arrays. TypeDef A typedef statement introduces a shorthand name for a type. The syntax is...
typedef <type> <name>;

The following defines Fraction type to be the type (struct fraction). C is case sensitive, so fraction is different from Fraction. It's convenient to use typedef to create types with upper case names and use the lower-case version of the same word as a variable.
typedef struct fraction Fraction; Fraction fraction; // Declare the variable "fraction" of type "Fraction" // which is really just a synonym for "struct fraction".

The following typedef defines the name Tree as a standard pointer to a binary tree node where each node contains some data and "smaller" and "larger" subtree pointers.
typedef struct treenode* Tree; struct treenode { int data; Tree smaller, larger; // equivalently, this line could say }; // "struct treenode *smaller, *larger"

24

Section 4 Functions
All languages have a construct to separate and package blocks of code. C uses the "function" to package blocks of code. This article concentrates on the syntax and peculiarities of C functions. The motivation and design for dividing a computation into separate blocks is an entire discipline in its own. A function has a name, a list of arguments which it takes when called, and the block of code it executes when called. C functions are defined in a text file and the names of all the functions in a C program are lumped together in a single, flat namespace. The special function called "main" is where program execution begins. Some programmers like to begin their function names with Upper case, using lower case for variables and parameters, Here is a simple C function declaration. This declares a function named Twice which takes a single int argument named num. The body of the function computes the value which is twice the num argument and returns that value to the caller.
/* Computes double of a number. Works by tripling the number, and then subtracting to get back to double. */ static int Twice(int num) { int result = num * 3; result = result - num; return(result); }

Syntax The keyword "static" defines that the function will only be available to callers in the file where it is declared. If a function needs to be called from another file, the function cannot be static and will require a prototype -- see prototypes below. The static form is convenient for utility functions which will only be used in the file where they are declared. Next , the "int" in the function above is the type of its return value. Next comes name of the function and its list of parameters. When referring to a function by name in documentation or other prose, it's a convention to keep the parenthesis () suffix, so in this case I refer to the function as "Twice()". The parameters are listed with their types and names, just like variables. Inside the function, the parameter num and the local variable result are "local" to the function -- they get their own memory and exist only so long as the function is executing. This independence of "local" memory is a standard feature of most languages (See CSLibrary/102 for the detailed discussion of local memory). The "caller" code which calls Twice() looks like...
int num = 13; int a = 1; int b = 2; a = Twice(a); // call Twice() passing the value of a b = Twice(b + num); // call Twice() passing the value b+num // a == 2 // b == 30 // num == 13 (this num is totally independent of the "num" local to Twice()

25 Things to notice... (vocabulary) The expression passed to a function by its caller is called the "actual parameter" -- such as "a" and "b + num" above. The parameter storage local to the function is called the "formal parameter" such as the "num" in "static int Twice(int num)". Parameters are passed "by value" that means there is a single copying assignment operation (=) from each actual parameter to set each formal parameter. The actual parameter is evaluated in the caller's context, and then the value is copied into the function's formal parameter just before the function begins executing. The alternative parameter mechanism is "by reference" which C does not implement directly, but which the programmer can implement manually when needed (see below). When a parameter is a struct, it is copied. The variables local to Twice(), num and result, only exist temporarily while Twice() is executing. This is the standard definition for "local" storage for functions. The return at the end of Twice() computes the return value and exits the function. Execution resumes with the caller. There can be multiple return statements within a function, but it's good style to at least have one at the end if a return value needs to be specified. Forgetting to account of a return somewhere in the middle of a function is a traditional source of bugs. C-ing and Nothingness -- void void is a type formalized in ANSI C which means "nothing". To indicate that a function does not return anything, use void as the return type. Also, by convention, a pointer which does not point to any particular type is declared as void*. Sometimes void* is used to force two bodies of code to not depend on each other where void* translates roughly to "this points to something, but I'm not telling you (the client) the type of the pointee exactly because you do not really need to know." If a function does not take any parameters, its parameter list is empty, or it can contain the keyword void but that style is now out of favor.
void TakesAnIntAndReturnsNothing(int anInt); int TakesNothingAndReturnsAnInt(); int TakesNothingAndReturnsAnInt(void); // equivalent syntax for above

Call by Value vs. Call by Reference C passes parameters "by value" which means that the actual parameter values are copied into local storage. The caller and callee functions do not share any memory -- they each have their own copy. This scheme is fine for many purposes, but it has two disadvantages. 1) Because the callee has its own copy, modifications to that memory are not communicated back to the caller. Therefore, value parameters do not allow the callee to communicate back to the caller. The function's return value can communicate some information back to the caller, but not all problems can be solved with the single return value.

26 2) Sometimes it is undesirable to copy the value from the caller to the callee because the value is large and so copying it is expensive, or because at a conceptual level copying the value is undesirable. The alternative is to pass the arguments "by reference". Instead of passing a copy of a value from the caller to the callee, pass a pointer to the value. In this way there is only one copy of the value at any time, and the caller and callee both access that one value through pointers. Some languages support reference parameters automatically. C does not do this -- the programmer must implement reference parameters manually using the existing pointer constructs in the language. Swap Example The classic example of wanting to modify the caller's memory is a swap() function which exchanges two values. Because C uses call by value, the following version of Swap will not work...
void Swap(int x, int y) { int temp; temp = x; x = y; y = temp; } // NO does not work

// these operations just change the local x,y,temp // -- nothing connects them back to the caller's a,b

// Some int a = int b = Swap(a,

caller code which calls Swap()... 1; 2; b);

Swap() does not affect the arguments a and b in the caller. The function above only operates on the copies of a and b local to Swap() itself. This is a good example of how "local" memory such as ( x, y, temp) behaves -- it exists independent of everything else only while its owning function is running. When the owning function exits, its local memory disappears. Reference Parameter Technique To pass an object X as a reference parameter, the programmer must pass a pointer to X instead of X itself. The formal parameter will be a pointer to the value of interest. The caller will need to use & or other operators to compute the correct pointer actual parameter. The callee will need to dereference the pointer with * where appropriate to access the value of interest. Here is an example of a correct Swap() function.
static void Swap(int* x, int* y) { int temp; temp = *x; *x = *y; *y = temp; } // params are int* instead of int

// use * to follow the pointer back to the caller's memory

27
// Some caller code which calls Swap()... int a = 1; int b = 2; Swap(&a, &b);

Things to notice... The formal parameters are int* instead of int. The caller uses & to compute pointers to its local memory (a,b). The callee uses * to dereference the formal parameter pointers back to get the caller's memory. Since the operator & produces the address of a variable -- &a is a pointer to a. In Swap() itself, the formal parameters are declared to be pointers, and the values of interest (a,b) are accessed through them. There is no special relationship between the names used for the actual and formal parameters. The function call matches up the actual and formal parameters by their order -- the first actual parameter is assigned to the first formal parameter, and so on. I deliberately used different names (a,b vs x,y) to emphasize that the names do not matter. const The qualifier const can be added to the left of a variable or parameter type to declare that the code using the variable will not change the variable. As a practical matter, use of const is very sporadic in the C programming community. It does have one very handy use, which is to clarify the role of a parameter in a function prototype...
void foo(const struct fraction* fract);

In the foo() prototype, the const declares that foo() does not intend to change the struct fraction pointee which is passed to it. Since the fraction is passed by pointer, we could not know otherwise if foo() intended to change our memory or not. Using the const, foo() makes its intentions clear. Declaring this extra bit of information helps to clarify the role of the function to its implementor and caller.

28 Bigger Pointer Example The following code is a large example of using reference parameters. There are several common features of C programs in this example...Reference parameters are used to allow the functions Swap() and IncrementAndSwap() to affect the memory of their callers. There's a tricky case inside of IncrementAndSwap() where it calls Swap() -- no additional use of & is necessary in this case since the parameters x, y inside InrementAndSwap() are already pointers to the values of interest. The names of the variables through the program(a, b, x, y, alice, bob) do not need to match up in any particular way for the parameters to work. The parameter mechanism only depends on the types of the parameters and their order in the parameter list -- not their names. Finally this is an example of what multiple functions look like in a file and how they are called from the main() function.
static void Swap(int* a, int* b) { int temp; temp = *a; *a = *b; *b = temp; } static void IncrementAndSwap(int* x, int* y) { (*x)++; (*y)++; Swap(x, y); // don't need & here since a and b are already // int*'s. }

int main() { int alice = 10; int bob = 20; Swap(&alice, &bob); // at this point alice==20 and bob==10 IncrementAndSwap(&alice, &bob); // at this point alice==11 and bob==21 return 0; }

29

Section 5 Odds and Ends


main() The execution of a C program begins with function named main(). All of the files and libraries for the C program are compiled together to build a single program file. That file must contain exactly one main() function which the operating system uses as the starting point for the program. Main() returns an int which, by convention, is 0 if the program completed successfully and non-zero if the program exited due to some error condition. This is just a convention which makes sense in shell oriented environments such as Unix or DOS. Multiple Files For a program of any size, it's convenient to separate the functions into several separate files. To allow the functions in separate files to cooperate, and yet allow the compiler to work on the files independently, C programs typically depend on two features... Prototypes A "prototype" for a function gives its name and arguments but not its body. In order for a caller, in any file, to use a function, the caller must have seen the prototype for that function. For example, here's what the prototypes would look like for Twice() and Swap(). The function body is absent and there's a semicolon (;) to terminate the prototype...
int Twice(int num); void Swap(int* a, int* b);

In pre-ANSI C, the rules for prototypes where very sloppy -- callers were not required to see prototypes before calling functions, and as a result it was possible to get in situations where the compiler generated code which would crash horribly. In ANSI C, I'll oversimplify a little to say that... 1) a function may be declared static in which case it can only be used in the same file where it is used below the point of its declaration. Static functions do not require a separate prototype so long as they are defined before or above where they are called which saves some work. 2) A non-static function needs a prototype. When the compiler compiles a function definition, it must have previously seen a prototype so that it can verify that the two are in agreement ("prototype before definition" rule). The prototype must also be seen by any client code which wants to call the function ("clients must see prototypes" rule).(The require-prototypes behavior is actually somewhat of a compiler option, but it's smart to leave it on.) Preprocessor The preprocessing step happens to the C source before it is fed to the compiler. The two most common preprocessor directives are #define and #include...

30 #define The #define directive can be used to set up symbolic replacements in the source. As with all preprocessor operations, #define is extremely unintelligent -- it just does textual replacement without understanding. #define statements are used as a crude way of establishing symbolic constants.
#define MAX 100 #define SEVEN_WORDS that_symbol_expands_to_all_these_words

Later code can use the symbols MAX or SEVEN_WORDS which will be replaced by the text to the right of each symbol in its #define. #include The "#include" directive brings in text from different files during compilation. #include is a very unintelligent and unstructured -- it just pastes in the text from the given file and continues compiling. The #include directive is used in the .h/.c file convention below which is used to satisfy the various constraints necessary to get prototypes correct.
#include "foo.h" // refers to a "user" foo.h file -// in the originating directory for the compile // refers to a "system" foo.h file -// in the compiler's directory somewhere

#include <foo.h>

foo.h vs foo.c The universally followed convention for C is that for a file named "foo.c" containing a bunch of functions... A separate file named foo.h will contain the prototypes for the functions in foo.c which clients may want to call. Functions in foo.c which are for "internal use only" and should never be called by clients should be declared static. Near the top of foo.c will be the following line which ensures that the function definitions in foo.c see the prototypes in foo.h which ensures the "prototype before definition" rule above. #include "foo.h" // show the contents of "foo.h" // to the compiler at this point Any xxx.c file which wishes to call a function defined in foo.c must include the following line to see the prototypes, ensuring the "clients must see prototypes" rule above. #include "foo.h"

31 #if At compile time, there is some space of names defined by the #defines. The #if test can be used at compile-time to look at those symbols and turn on and off which lines the compiler uses. The following example depends on the value of the FOO #define symbol. If it is true, then the "aaa" lines (whatever they are) are compiled, and the "bbb" lines are ignored. If FOO were 0, then the reverse would be true.
#define FOO 1 ... #if FOO aaa aaa #else bbb bbb #endif

You can use #if 0 ...#endif to effectively comment out areas of code you don't want to compile, but which you want to keeep in the source file. Multiple #includes -- #pragma once There's a problem sometimes where a .h file is #included into a file more than one time resulting in compile errors. This can be a serious problem. Because of this, you want to avoid #including .h files in other .h files if at all possible. On the other hand, #including .h files in .c files is fine. If you are lucky, your compiler will support the #pragma once feature which automatically prevents a single file from being #included more than once in any one file. This largely solves multiple #include problems.
// foo.h // The following line prevents problems in files which #include "foo.h" #pragma once <rest of foo.h ...>

Assert Array out of bounds references are an extremely common form of C run-time error. You can use the assert() function to sprinkle your code with your own bounds checks. A few seconds putting in assert statements can save you hours of debugging. Getting out all the bugs is the hardest and scariest part of writing a large piece of software. Assert statements are one of the easiest and most effective helpers for that difficult phase.
#include <assert.h> #define MAX_INTS 100 { int ints[MAX_INTS]; i = foo(<something complicated>); assert(i>=0); assert(i<MAX_INTS); ints[i] = 0;

// i should be in bounds, // but is it really? // safety assertions

32 Depending on the options specified at compile time, the assert() expressions will be left in the code for testing, or may be ignored. For that reason, it is important to only put expressions in assert() tests which do not need to be evaluated for the proper functioning of the program...
int errCode = foo(); assert(errCode == 0); // yes

assert(foo() == 0);

// NO, foo() will not be called if // the compiler removes the assert()

33

Section 6 Advanced Arrays and Pointers


Advanced C Arrays In C, an array is formed by laying out all the elements contiguously in memory. The square bracket syntax can be used to refer to the elements in the array. The array as a whole is referred to by the address of the first element which is also known as the "base address" of the whole array.
{ int array[6]; int sum = 0; sum += array[0] + array[1]; }

// refer to elements using []

array The array name acts like a pointer to the first element- in this case an (int*).

array[0] array[1] array[2] ... Index 0 1 2 3 4 5

The programmer can refer to elements in the array with the simple [ ] syntax such as array[1]. This scheme works by combining the base address of the whole array with the index to compute the base address of the desired element in the array. It just requires a little arithmetic. Each element takes up a fixed number of bytes which is known at compile-time. So the address of element n in the array using 0 based indexing will be at an offset of (n * element_size) bytes from the base address of the whole array. address of nth element = address_of_0th_element + (n * element_size_in_bytes) The square bracket syntax [ ] deals with this address arithmetic for you, but it's useful to know what it's doing. The [ ] takes the integer index, multiplies by the element size, adds the resulting offset to the array base address, and finally dereferences the resulting pointer to get to the desired element.
{ int intArray[6]; intArray[3] = 13; }

34

intArray 12 bytes of offset

(intArray+3)

13 Index 0 1 4 2 8 3 12 4 16 5 20

0 Offset in bytes = n * elem_size

Assume sizeof(int) = 4i.e. Each array element takes up 4 bytes. '+' Syntax In a closely related piece of syntax, a + between a pointer and an integer does the same offset computation, but leaves the result as a pointer. The square bracket syntax gives the nth element while the + syntax gives a pointer to the nth element. So the expression (intArray + 3) is a pointer to the integer intArray[3]. (intArray + 3) is of type (int*) while intArray[3] is of type int. The two expressions only differ by whether the pointer is dereferenced or not. So the expression (intArray + 3) is exactly equivalent to the expression (&(intArray[3])). In fact those two probably compile to exactly the same code. They both represent a pointer to the element at index 3. Any [] expression can be written with the + syntax instead. We just need to add in the pointer dereference. So intArray[3] is exactly equivalent to *(intArray + 3). For most purposes, it's easiest and most readable to use the [] syntax. Every once in a while the + is convenient if you needed a pointer to the element instead of the element itself. Pointer++ Style -- strcpy() If p is a pointer to an element in an array, then (p+1) points to the next element in the array. Code can exploit this using the construct p++ to step a pointer over the elements in an array. It doesn't help readability any, so I can't recommend the technique, but you may see it in code written by others. (This example was originally inspired by Mike Cleron) There's a library function called strcpy(char* destination, char* source) which copies the bytes of a C string from one place to another. Below are four different implementations of strcpy() written in order: from most verbose to most cryptic. In the first one, the normally straightforward while loop is actually sortof tricky to ensure that the terminating null character is copied over. The second removes that trickiness by moving assignment into the test. The last two are cute (and they demonstrate using ++ on pointers), but not really the sort of code you want to maintain. Among the four, I think strcpy2() is the best stylistically. With a smart compiler, all four will compile to basically the same code with the same efficiency.

35
// Unfortunately, a straight while or for loop won't work. // The best we can do is use a while (1) with the test // in the middle of the loop. void strcpy1(char dest[], const char source[]) { int i = 0; while (1) { dest[i] = source[i]; if (dest[i] == '\0') break; i++; } }

// we're done

// Move the assignment into the test void strcpy2(char dest[], const char source[]) { int i = 0; while ((dest[i] = source[i]) != '\0') { i++; } }

// Get rid of i and just move the pointers. // Relies on the precedence of * and ++. void strcpy3(char dest[], const char source[]) { while ((*dest++ = *source++) != '\0') ; }

// Rely on the fact that '\0' is equivalent to FALSE void strcpy4(char dest[], const char source[]) { while (*dest++ = *source++) ; }

Pointer Type Effects Both [ ] and + implicitly use the compile time type of the pointer to compute the element_size which affects the offset arithmetic. When looking at code, it's easy to assume that everything is in the units of bytes.
int *p; p = p + 12; // at run-time, what does this add to p? 12?

The above code does not add the number 12 to the address in p-- that would increment p by 12 bytes. The code above increments p by 12 ints. Each int probably takes 4 bytes, so at run time the code will effectively increment the address in p by 48. The compiler figures all this out based on the type of the pointer. Using casts, the following code really does just add 12 to the address in the pointer p. It works by telling the compiler that the pointer points to char instead of int. The size of char is defined to be exactly 1 byte (or whatever the smallest addressable unit is on the computer). In other words, sizeof(char) is always 1. We then cast the resulting

36 (char*) back to an (int*). The programmer is allowed to cast any pointer type to any other pointer type like this to change the code the compiler generates.
p = (int*) ( ((char*)p) + 12);

Arrays and Pointers One effect of the C array scheme is that the compiler does not distinguish meaningfully between arrays and pointers-- they both just look like pointers. In the following example, the value of intArray is a pointer to the first element in the array so it's an (int*). The value of the variable intPtr is also (int*) and it is set to point to a single integer i. So what's the difference between intArray and intPtr? Not much as far as the compiler is concerned. They are both just (int*) pointers, and the compiler is perfectly happy to apply the [] or + syntax to either. It's the programmer's responsibility to ensure that the elements referred to by a [] or + operation really are there. Really its' just the same old rule that C doesn't do any bounds checking. C thinks of the single integer i as just a sort of degenerate array of size 1.
{ int intArray[6]; int *intPtr; int i; intPtr = &i; intArray[3] = 13; intPtr[0] = 12; intPtr[3] = 13; } // ok // odd, but ok. Changes i. // BAD! There is no integer reserved here!

37

intArray

(intArray+3)

13 Index 0 1 intPtr 2 3 4 5 (intPtr+3)

12 i

13

These bytes exist, but they have not been explicitly reserved. They are the bytes which happen to be adjacent to the memory for i. They are probably being used to store something already, such as a smashed looking smiley face. The 13 just gets blindly written over the smiley face. This error will only be apparent later when the program tries to read the smiley face data. Array Names Are Const One subtle distinction between an array and a pointer, is that the pointer which represents the base address of an array cannot be changed in the code. The array base address behaves like a const pointer. The constraint applies to the name of the array where it is declared in the code-- the variable ints in the example below.
{ int ints[100] int *p; int i; ints = NULL; ints = &i; ints = ints + 1; ints++; p = ints; // // // // NO, cannot change the base addr ptr NO NO NO

// OK, p is a regular pointer which can be changed // here it is getting a copy of the ints pointer // OK, p can still be changed (and ints cannot) // OK // OK // OK (possible foo definitions are below)

p++; p = NULL; p = &i; foo(ints); }

38

Array parameters are passed as pointers. The following two definitions of foo look different, but to the compiler they mean exactly the same thing. It's preferable to use whichever syntax is more accurate for readability. If the pointer coming in really is the base address of a whole array, then use [ ].
void foo(int arrayParam[]) { arrayParam = NULL; // Silly but valid. Just changes the local pointer } void foo(int *arrayParam) { arrayParam = NULL; // ditto }

Heap Memory C gives programmers the standard sort of facilities to allocate and deallocate dynamic heap memory. A word of warning: writing programs which manage their heap memory is notoriously difficult. This partly explains the great popularity of languages such as Java and Perl which handle heap management automatically. These languages take over a task which has proven to be extremely difficult for the programmer. As a result Perl and Java programs run a little more slowly, but they contain far fewer bugs. (For a detailed discussion of heap memory see http://cslibrary.stanford.edu/102/, Pointers and Memory.) C provides access to the heap features through library functions which any C code can call. The prototypes for these functions are in the file <stdlib.h>, so any code which wants to call these must #include that header file. The three functions of interest are... void* malloc(size_t size) Request a contiguous block of memory of the given size in the heap. malloc() returns a pointer to the heap block or NULL if the request could not be satisfied. The type size_t is essentially an unsigned long which indicates how large a block the caller would like measured in bytes. Because the block pointer returned by malloc() is a void* (i.e. it makes no claim about the type of its pointee), a cast will probably be required when storing the void* pointer into a regular typed pointer. void free(void* block) The mirror image of malloc() -- free takes a pointer to a heap block earlier allocated by malloc() and returns that block to the heap for re-use. After the free(), the client should not access any part of the block or assume that the block is valid memory. The block should not be freed a second time. void* realloc(void* block, size_t size); Take an existing heap block and try to relocate it to a heap block of the given size which may be larger or smaller than the original size of the block. Returns a pointer to the new block, or NULL if the relocation was unsuccessful. Remember to catch and examine the return value of realloc() -- it is a common error to continue to use the old block pointer. Realloc() takes care of moving the bytes from the old block to the new block. Realloc() exists because it can be implemented using low-level features which make it more efficient than C code the client could write. Memory Management All of a program's memory is deallocated automatically when the it exits, so a program only needs to use free() during execution if it is important for the program to recycle its memory while it runs -- typically because it uses a lot of memory or because it runs for a

39 long time. The pointer passed to free() must be exactly the pointer which was originally returned by malloc() or realloc(), not just a pointer into somewhere within the heap block. Dynamic Arrays Since arrays are just contiguous areas of bytes, you can allocate your own arrays in the heap using malloc(). The following code allocates two arrays of 1000 ints-- one in the stack the usual "local" way, and one in the heap using malloc(). Other than the different allocations, the two are syntactically similar in use.
{ int a[1000]; int *b; b = (int*) malloc( sizeof(int) * 1000); assert(b != NULL); // check that the allocation succeeded a[123] = 13; b[123] = 13; free(b); } // Just use good ol' [] to access elements // in both arrays.

Although both arrays can be accessed with [ ], the rules for their maintenance are very different.... Advantages of being in the heap Size (in this case 1000) can be defined at run time. Not so for an array like "a". The array will exist until it is explicitly deallocated with a call to free(). You can change the size of the array at will at run time using realloc(). The following changes the size of the array to 2000. Realloc() takes care of copying over the old elements.
... b = realloc(b, sizeof(int) * 2000); assert(b != NULL);

Disadvantages of being in the heap You have to remember to allocate the array, and you have to get it right. You have to remember to deallocate it exactly once when you are done with it, and you have to get that right. The above two disadvantages have the same basic profile: if you get them wrong, your code still looks right. It compiles fine. It even runs for small cases, but for some input cases it just crashes unexpectedly because random memory is getting overwritten somewhere like the smiley face. This sort of "random memory smasher" bug can be a real ordeal to track down.

40 Dynamic Strings The dynamic allocation of arrays works very well for allocating strings in the heap. The advantage of heap allocating a string is that the heap block can be just big enough to store the actual number of characters in the string. The common local variable technique such as char string[1000]; allocates way too much space most of the time, wasting the unused bytes, and yet fails if the string ever gets bigger than the variable's fixed size.
#include <string.h> /* Takes a c string as input, and makes a copy of that string in the heap. The caller takes over ownership of the new string and is responsible for freeing it. */ char* MakeStringInHeap(const char* source) { char* newString; newString = (char*) malloc(strlen(source) + 1); // +1 for the '\0' assert(newString != NULL); strcpy(newString, source); return(newString); }

41

Section 7 Details and Library Functions


Precedence and Associativity
function-call() [] -> . ! ~ ++ -- + - *(ptr deref) sizeof &(addr of) (all unary ops are the same) * / % (the top tier arithmetic binary ops) + (second tier arithmetic binary ops) < <= > >= == != in order: & ^ | && || (note that bitwise comes before boolean) = and all its variants , (comma) . L to R R to L

L to R

L to R

L to R L to R L to R

R to L L to R

A combinations which never works right without parens: *structptr.field You have to write it as (*structptr).field or structptr->field

Standard Library Functions Many basic housekeeping funcions are available to a C program in form of standard library functions. To call these, a program must #include the appropriate .h file. Most compilers link in the standard library code by default. The functions listed in the next section are the most commonly used ones, but there are many more which are not listed here. stdio.h ctype.h string.h math.h stdlib.h assert.h stdarg.h setjmp.h signal.h time.h file input and output character tests string operations mathematical functions such as sin() and cos() utility functions such as malloc() and rand() the assert() debugging macro support for functions with variable numbers of arguments support for non-local flow control jumps support for exceptional condition signals date and time

42 limits.h, float.h constants which define type range values such as INT_MAX

stdio.h Stdio.h is a very common file to #include -- it includes functions to print and read strings from files and to open and close files in the file system. FILE* fopen(const char* fname, const char* mode); Open a file named in the filesystem and return a FILE* for it. Mode = "r" read,"w" write,"a"append, returns NULL on error. The standard files stdout, stdin, stderr are automatically opened and closed for you by the system. int fclose(FILE* file); Close a previously opened file. Returns EOF on error. The operating system closes all of a program's files when it exits, but it's tidy to do it beforehand. Also, there is typically a limit to the number of files which a program may have open simultaneously. int fgetc(FILE* in); Read and return the next unsigned char out of a file, or EOF if the file has been exhausted. (detail) This and other file functions return ints instead of a chars because the EOF constant they potentially is not a char, but is an int. getc() is an alternate, faster version implemented as a macro which may evaluate the FILE* expression more than once. char* fgets(char* dest, int n, FILE* in) Reads the next line of text into a string supplied by the caller. Reads at most n-1 characters from the file, stopping at the first '\n' character. In any case, the string is '\0' terminated. The '\n' is included in the string. Returns NULL on EOF or error. int fputc(int ch, FILE* out); Write the char to the file as an unsigned char. Returns ch, or EOF on err. putc() is an alternate, faster version implemented as a macro which may evaluate the FILE* expression more than once. int ungetc(int ch, FILE* in); Push the most recent fgetc() char back onto the file. EOF may not be pushed back. Returns ch or EOF on error. int printf(const char* format_string, ...); Prints a string with values possibly inserted into it to standard output. Takes a variable number of arguments -- first a format string followed by a number of matching arguments. The format string contains text mixed with % directives which mark things to be inserted in the output. %d = int, %Ld=long int, %s=string, %f=double, %c=char. Every % directive must have a matching argument of the correct type after the format string. Returns the number of characters written, or negative on error. If the percent directives do not match the number and type of arguments, printf() tends to crash or otherwise do the wrong thing at run time. fprintf() is a variant which takes an additional FILE* argument which specifies the file to print to. Examples... printf("hello\n"); prints: hello printf("hello %d there %d\n", 13, 1+1); prints: hello 13 there 2 printf("hello %c there %d %s\n", 'A', 42, "ok"); prints: hello A there 42 ok

43 int scanf(const char* format, ...) Opposite of printf() -- reads characters from standard input trying to match elements in the format string. Each percent directive in the format string must have a matching pointer in the argument list which scanf() uses to store the values it finds. scanf() skips whitespace as it tries to read in each percent directive. Returns the number of percent directives processed successfully, or EOF on error. scanf() is famously sensitive to programmer errors. If scanf() is called with anything but the correct pointers after the format string, it tends to crash or otherwise do the wrong thing at run time. sscanf() is a variant which takes an additional initial string from which it does its reading. fscanf() is a variant which takes an additional initial FILE* from which it does its reading. Example...
{ int num; char s1[1000]; char s2[1000]; scanf("hello %d %s %s", &num, s1, s2); }

Looks for the word "hello" followed by a number and two words (all separated by whitespace). scanf() uses the pointers &num, s1, and s2 to store what it finds into the local variables. ctype.h ctype.h includes macros for doing simple tests and operations on characters isalpha(ch) // ch is an upper or lower case letter // same as above, but upper/lower specific

islower(ch), isupper(ch) isspace(ch) isdigit(ch)

// ch is a whitepace character such as tab, space, newline, etc. // digit such as '0'..'9'

toupper(ch), tolower(ch) // Return the lower or upper case version of a alphabetic character, otherwise pass it through unchanged.

44 string.h None of these string routines allocate memory or check that the passed in memory is the right size. The caller is responsible for making sure there is "enough" memory for the operation. The type size_t is an unsigned integer wide enough for the computer's address space -- most likely an unsigned long. size_t strlen(const char* string); Return the number of chars in a C string. EG strlen("abc")==3 char* strcpy(char* dest, const char* source); Copy the characters from the source string to the destination string. size_t strlcpy(char* dest, const char* source, size_t dest_size); Like strcpy(), but knows the size of the dest. Truncates if necessary. Use this to avoid memory errors and buffer-overflow security problems. This function is not as standard as strcpy(), but most sytems have it. Do not use the old strncpy() function -it is difficult to use correctly. char *strcat(char* dest, const char* source); Append the characters from the source string to the end of destination string. (There is a non-standard strlcat() variant that takes the size of the dest as third argument.) int strcmp(const char* a, const char* b); Compare two strings and return an int which encodes their ordering. zero:a==b, negative:a<b, positive:a>b. It is a common error to think of the result of strcmp() as being boolean true if the strings are equal which is, unfortunately, exactly backwards. char* strchr(const char* searchIn, char ch); Search the given string for the first occurence of the given character. Returns a pointer to the character, or NULL if none is found. char* strstr(const char* searchIn, const char* searchFor); Similar to strchr(), but searches for an entire string instead of a single character. The search is case sensitive. void* memcpy(void* dest, const void* source, size_t n); Copy the given number of bytes from the source to the destination. The source and destination must not overlap. This may be implemented in a specialized but highly optimized way for a particular computer. void* memmove(void* dest, const void* source, size_t n); Similar to memcpy() but allows the areas to overlap. This probably runs slightly slower than memcpy().

45 stdlib.h int rand(); Returns a pseudo random integer in the range 0..RAND_MAX (limits.h) which is at least 32767. void srand(unsigned int seed); The sequence of random numbers returned by rand() is initially controlled by a global "seed" variable. srand() sets this seed which, by default, starts with the value 1. Pass the expression time(NULL) (time.h) to set the seed to a value based on the current time to ensure that the random sequence is different from one run to the next. void* malloc(size_t size); Allocate a heap block of the given size in bytes. Returns a pointer to the block or NULL on failure. A cast may be required to store the void* pointer into a regular typed pointer. [ed: see the Heap Allocation section above for the longer discussion of malloc(), free(), and realloc()] void free(void* block); Opposite of malloc(). Returns a previous malloc block to the system for reuse void* realloc(void* block, size_t size); Resize an existing heap block to the new size. Takes care of copying bytes from the old block to the new. Returns the new base address of the heap block. It is a common error to forget to catch the return value from realloc(). Returns NULL if the resize operation was not possible. void exit(int status); Halt and exit the program and pass a condition int back to the operating sytem. Pass 0 to signal normal program termination, non-zero otherwise. void* bsearch(const void* key, const void* base, size_t len, size_t elem_size, <compare_function>); Do a binary search in an array of elements. The last argument is a function which takes pointers to the two elements to compare. Its prototype should be: int compare(const void* a, const void* b);, and it should return 0, -1, or 1 as strcmp() does. Returns a pointer to a found element, or NULL otherwise. Note that strcmp() itself cannot be used directly as a compare function for bsearch() on an array of char* strings because strcmp() takes char* arguments and bsearch() will need a comparator that takes pointers to the array elements -- char**. void qsort(void* base, size_t len, size_t elem_size, <compare_function>); Sort an array of elements. Takes a function pointer just like besearch(). Revision History 11/1998 -- original major version. Based on my old C handout for CS107. Thanks to Jon Becker for proofreading and Mike Cleron for the original inspiration. Revised 4/2003 with many helpful typo and other suggestions from Negar Shamma and A. P. Garcia

Pointers and Memory


By Nick Parlante
Copyright 1998-2000, Nick Parlante

Abstract This document explains how pointers and memory work and how to use themfrom the basic concepts through all the major programming techniques. For each topic there is a combination of discussion, sample C code, and drawings. Audience This document can be used as an introduction to pointers for someone with basic programming experience. Alternately, it can be used to review and to fill in gaps for someone with a partial understanding of pointers and memory. Many advanced programming and debugging problems only make sense with a complete understanding of pointers and memory this document tries to provide that understanding. This document concentrates on explaining how pointers work. For more advanced pointer applications and practice problems, see the other resources below. Pace Like most CS Education Library documents, the coverage here tries to be complete but fast. The document starts with the basics and advances through all the major topics. The pace is fairly quick each basic concept is covered once and usually there is some example code and a memory drawing. Then the text moves on to the next topic. For more practice, you can take the time to work through the examples and sample problems. Also, see the references below for more practice problems. Topics Topics include: pointers, local memory, allocation, deallocation, dereference operations, pointer assignment, deep vs. shallow copies, the ampersand operator (&), bad pointers, the NULL pointer, value parameters, reference parameters, heap allocation and deallocation, memory ownership models, and memory leaks. The text focuses on pointers and memory in compiled languages like C and C++. At the end of each section, there is some related but optional material, and in particular there are occasional notes on other languages, such as Java. Pointers and Memory document #102 in the Stanford CS Education Library. This and other free educational materials are available at http://cslibrary.stanford.edu/102/. This document is free to be used, reproduced, sold, or retransmitted so long as this notice is clearly reproduced at its beginning. Other CS Education Library Documents Point Fun With Binky Video (http://cslibrary.stanford.edu/104/) A silly video about pointer basics. Linked list Basics (http://cslibrary.stanford.edu/103/) Introduces the basic techniques for building linked lists in C.

2 Linked List Problems (http://cslibrary.stanford.edu/105/) 18 classic linked list problems with solutions a great way to practice with realistic, pointer intensive C code, and there's just no substitute for practice! Essential C (http://cslibrary.stanford.edu/101/) Complete coverage of the C language, including all of the syntax used in this document. Table of Contents Section 1 Basic Pointers.......................................................................... pg. 3 The basic rules and drawings for pointers: pointers, pointees, pointer assignment (=), pointer comparison (==), the ampersand operator (&), the NULL pointer, bad pointers, and bad dereferences. Section 2 Local Memory ......................................................................... pg. 11 How local variables and parameters work: local storage, allocation, deallocation, the ampersand bug. Understanding the separation of local memory between separate functions. Section 3 Reference Parameters.............................................................. pg. 17 Combines the previous two sections to show how a function can use "reference parameters" to communicate back to its caller. Section 4 Heap Memory ........................................................................ pg. 24 Builds on all the previous sections to explain dynamic heap memory: heap allocation, heap deallocation, array allocation, memory ownership models, and memory leaks. Edition The first edition of this document was on Jan 19, 1999. This Feb 21, 2000 edition represents only very minor changes. The author may be reached at nick.parlante@cs.stanford.edu. The CS Education Library may be reached at cslibrary@cs.stanford.edu. Dedication This document is distributed for the benefit and education of all. That someone seeking education should have the opportunity to find it. May you learn from it in the spirit in which it is given to make efficiency and beauty in your designs, peace and fairness in your actions. Preface To The First Edition This article has appeared to hover at around 80% done for 6 months! Every time I add one section, I think of two more which also need to be written. I was motivated to keep working on it since there are so many other articles which use memory, &, ... in passing where I wanted something to refer to. I hope you find it valuable in its current form. I'm going to ship it quickly before I accidentally start adding another section!

Section 1 Basic Pointers


Pointers Before and After There's a lot of nice, tidy code you can write without knowing about pointers. But once you learn to use the power of pointers, you can never go back. There are too many things that can only be done with pointers. But with increased power comes increased responsibility. Pointers allow new and more ugly types of bugs, and pointer bugs can crash in random ways which makes them more difficult to debug. Nonetheless, even with their problems, pointers are an irresistibly powerful programming construct. (The following explanation uses the C language syntax where a syntax is required; there is a discussion of Java at the section.) Why Have Pointers? Pointers solve two common software problems. First, pointers allow different sections of code to share information easily. You can get the same effect by copying information back and forth, but pointers solve the problem better. Second, pointers enable complex "linked" data structures like linked lists and binary trees. What Is A Pointer? Simple int and float variables operate pretty intuitively. An int variable is like a box which can store a single int value such as 42. In a drawing, a simple variable is a box with its current value drawn inside. num 42

A pointer works a little differently it does not store a simple value directly. Instead, a pointer stores a reference to another value. The variable the pointer refers to is sometimes known as its "pointee". In a drawing, a pointer is a box which contains the beginning of an arrow which leads to its pointee. (There is no single, official, word for the concept of a pointee pointee is just the word used in these explanations.) The following drawing shows two variables: num and numPtr. The simple variable num contains the value 42 in the usual way. The variable numPtr is a pointer which contains a reference to the variable num. The numPtr variable is the pointer and num is its pointee. What is stored inside of numPtr? Its value is not an int. Its value is a reference to an int. A simple int variable. The current value is the integer 42. This variable also plays the role of pointee for the pointer below. A pointer variable. The current value is a reference to the pointee num above.

num numPtr

42

4 Pointer Dereference The "dereference" operation follows a pointer's reference to get the value of its pointee. The value of the dereference of numPtr above is 42. When the dereference operation is used correctly, it's simple. It just accesses the value of the pointee. The only restriction is that the pointer must have a pointee for the dereference to access. Almost all bugs in pointer code involve violating that one restriction. A pointer must be assigned a pointee before dereference operations will work. The NULL Pointer The constant NULL is a special pointer value which encodes the idea of "points to nothing." It turns out to be convenient to have a well defined pointer value which represents the idea that a pointer does not have a pointee. It is a runtime error to dereference a NULL pointer. In drawings, the value NULL is usually drawn as a diagonal line between the corners of the pointer variable's box... numPtr The C language uses the symbol NULL for this purpose. NULL is equal to the integer constant 0, so NULL can play the role of a boolean false. Official C++ no longer uses the NULL symbolic constant use the integer constant 0 directly. Java uses the symbol null. Pointer Assignment The assignment operation (=) between two pointers makes them point to the same pointee. It's a simple rule for a potentially complex situation, so it is worth repeating: assigning one pointer to another makes them point to the same thing. The example below adds a second pointer, second, assigned with the statement second = numPtr;. The result is that second points to the same pointee as numPtr. In the drawing, this means that the second and numPtr boxes both contain arrows pointing to num. Assignment between pointers does not change or even touch the pointees. It just changes which pointee a pointer refers to. num numPtr second 42 A second pointer ptr initialized with the assignment second = numPtr;. This causes second to refer to the same pointeee as numPtr.

After assignment, the == test comparing the two pointers will return true. For example (second==numPtr) above is true. The assignment operation also works with the NULL value. An assignment operation with a NULL pointer copies the NULL value from one pointer to another. Make A Drawing Memory drawings are the key to thinking about pointer code. When you are looking at code, thinking about how it will use memory at run time....make a quick drawing to work out your ideas. This article certainly uses drawings to show how pointers work. That's the way to do it.

5 Sharing Two pointers which both refer to a single pointee are said to be "sharing". That two or more entities can cooperatively share a single memory structure is a key advantage of pointers in all computer languages. Pointer manipulation is just technique sharing is often the real goal. In Section 3 we will see how sharing can be used to provide efficient communication between parts of a program. Shallow and Deep Copying In particular, sharing can enable communication between two functions. One function passes a pointer to the value of interest to another function. Both functions can access the value of interest, but the value of interest itself is not copied. This communication is called "shallow" since instead of making and sending a (large) copy of the value of interest, a (small) pointer is sent and the value of interest is shared. The recipient needs to understand that they have a shallow copy, so they know not to change or delete it since it is shared. The alternative where a complete copy is made and sent is known as a "deep" copy. Deep copies are simpler in a way, since each function can change their copy without interfering with the other copy, but deep copies run slower because of all the copying. The drawing below shows shallow and deep copying between two functions, A() and B(). In the shallow case, the smiley face is shared by passing a pointer between the two. In the deep case, the smiley face is copied, and each function gets their own...

Shallow / Sharing
A() A()

Deep / Copying

B()

B()

Section 2 will explain the above sharing technique in detail. Bad Pointers When a pointer is first allocated, it does not have a pointee. The pointer is "uninitialized" or simply "bad". A dereference operation on a bad pointer is a serious runtime error. If you are lucky, the dereference operation will crash or halt immediately (Java behaves this way). If you are unlucky, the bad pointer dereference will corrupt a random area of memory, slightly altering the operation of the program so that it goes wrong some indefinite time later. Each pointer must be assigned a pointee before it can support dereference operations. Before that, the pointer is bad and must not be used. In our memory drawings, the bad pointer value is shown with an XXX value... numPtr Bad pointers are very common. In fact, every pointer starts out with a bad value. Correct code overwrites the bad value with a correct reference to a pointee, and thereafter the pointer works fine. There is nothing automatic that gives a pointer a valid pointee.

6 Quite the opposite most languages make it easy to omit this important step. You just have to program carefully. If your code is crashing, a bad pointer should be your first suspicion. Pointers in dynamic languages such as Perl, LISP, and Java work a little differently. The run-time system sets each pointer to NULL when it is allocated and checks it each time it is dereferenced. So code can still exhibit pointer bugs, but they will halt politely on the offending line instead of crashing haphazardly like C. As a result, it is much easier to locate and fix pointer bugs in dynamic languages. The run-time checks are also a reason why such languages always run at least a little slower than a compiled language like C or C++. Two Levels One way to think about pointer code is that operates at two levels pointer level and pointee level. The trick is that both levels need to be initialized and connected for things to work. (1) the pointer must be allocated, (1) the pointee must be allocated, and (3) the pointer must be assigned to point to the pointee. It's rare to forget step (1). But forget (2) or (3), and the whole thing will blow up at the first dereference. Remember to account for both levels make a memory drawing during your design to make sure it's right. Syntax The above basic features of pointers, pointees, dereferencing, and assigning are the only concepts you need to build pointer code. However, in order to talk about pointer code, we need to use a known syntax which is about as interesting as....a syntax. We will use the C language syntax which has the advantage that it has influenced the syntaxes of several languages. Pointer Type Syntax A pointer type in C is just the pointee type followed by a asterisk (*)... int* float* struct fraction* struct fraction** type: pointer to int type: pointer to float type: pointer to struct fraction type: pointer to struct fraction*

Pointer Variables Pointer variables are declared just like any other variable. The declaration gives the type and name of the new variable and reserves memory to hold its value. The declaration does not assign a pointee for the pointer the pointer starts out with a bad value.
int* numPtr; // Declare the int* (pointer to int) variable "numPtr". // This allocates space for the pointer, but not the pointee. // The pointer starts out "bad".

7 The & Operator Reference To There are several ways to compute a reference to a pointee suitable for storing in a pointer. The simplest way is the & operator. The & operator can go to the left of any variable, and it computes a reference to that variable. The code below uses a pointer and an & to produce the earlier num/numPtr example. num numPtr
void NumPtrExample() { int num; int* numPtr; num = 42; numPtr = &num; // Compute a reference to "num", and store it in numPtr // At this point, memory looks like drawing above }

42

It is possible to use & in a way which compiles fine but which creates problems at run time the full discussion of how to correctly use & is in Section 2. For now we will just use & in a simple way. The * Operator Dereference The star operator (*) dereferences a pointer. The * is a unary operator which goes to the left of the pointer it dereferences. The pointer must have a pointee, or it's a runtime error. Example Pointer Code With the syntax defined, we can now write some pointer code that demonstrates all the pointer rules...
void PointerTest() { // allocate three integers and two pointers int a = 1; int b = 2; int c = 3; int* p; int* q; // Here is the state of memory at this point. // T1 -- Notice that the pointers start out bad...

a b c

1 2 3

p q

p = &a;

// set p to refer to a

8
q = &b; // set q to refer to b // T2 -- The pointers now have pointees

a b c

1 2 3

p q

// Now we mix things up a bit... c = *p; // retrieve p's pointee value (1) and put it in c p = q; // change p to share with q (p's pointee is now b) *p = 13; // dereference p to set its pointee (b) to 13 (*q is now 13) // T3 -- Dereferences and assignments mix things up

a b c
}

1 13 1

p q

Bad Pointer Example Code with the most common sort of pointer bug will look like the above correct code, but without the middle step where the pointers are assigned pointees. The bad code will compile fine, but at run-time, each dereference with a bad pointer will corrupt memory in some way. The program will crash sooner or later. It is up to the programmer to ensure that each pointer is assigned a pointee before it is used. The following example shows a simple example of the bad code and a drawing of how memory is likely to react...
void BadPointer() { int* p; // allocate the pointer, but not the pointee *p = 42; // this dereference is a serious runtime error } // What happens at runtime when the bad pointer is dereferenced...

Pow!

9 Pointer Rules Summary No matter how complex a pointer structure gets, the list of rules remains short. A pointer stores a reference to its pointee. The pointee, in turn, stores something useful. The dereference operation on a pointer accesses its pointee. A pointer may only be dereferenced after it has been assigned to refer to a pointee. Most pointer bugs involve violating this one rule. Allocating a pointer does not automatically assign it to refer to a pointee. Assigning the pointer to refer to a specific pointee is a separate operation which is easy to forget. Assignment between two pointers makes them refer to the same pointee which introduces sharing.

Section 1 Extra Optional Material


Extra: How Do Pointers Work In Java Java has pointers, but they are not manipulated with explicit operators such as * and &. In Java, simple data types such as int and char operate just as in C. More complex types such as arrays and objects are automatically implemented using pointers. The language automatically uses pointers behind the scenes for such complex types, and no pointer specific syntax is required. The programmer just needs to realize that operations like a=b; will automatically be implemented with pointers if a and b are arrays or objects. Or put another way, the programmer needs to remember that assignments and parameters with arrays and objects are intrinsically shallow or shared see the Deep vs. Shallow material above. The following code shows some Java object references. Notice that there are no *'s or &'s in the code to create pointers. The code intrinsically uses pointers. Also, the garbage collector (Section 4), takes care of the deallocation automatically at the end of the function.
public void JavaShallow() { Foo a = new Foo(); // Create a Foo object (no * in the declaration) Foo b = new Foo(); // Create another Foo object b=a; // This is automatically a shallow assignment -// a and b now refer to the same object.

a.Bar(); // This could just as well be written b.Bar(); // There is no memory leak here -- the garbage collector // will automatically recycle the memory for the two objects. }

The Java approach has two main features... Fewer bugs. Because the language implements the pointer manipulation accurately and automatically, the most common pointer bug are no longer possible, Yay! Also, the Java runtime system checks each pointer value every time it is used, so NULL pointer dereferences are caught immediately on the line where they occur. This can make a programmer much more productive.

10 Slower. Because the language takes responsibility for implementing so much pointer machinery at runtime, Java code runs slower than the equivalent C code. (There are other reasons for Java to run slowly as well. There is active research in making Java faser in interesting ways the Sun "Hot Spot" project.) In any case, the appeal of increased programmer efficiency and fewer bugs makes the slowness worthwhile for some applications.

Extra: How Are Pointers Implemented In The Machine? How are pointers implemented? The short explanation is that every area of memory in the machine has a numeric address like 1000 or 20452. A pointer to an area of memory is really just an integer which is storing the address of that area of memory. The dereference operation looks at the address, and goes to that area of memory to retrieve the pointee stored there. Pointer assignment just copies the numeric address from one pointer to another. The NULL value is generally just the numeric address 0 the computer just never allocates a pointee at 0 so that address can be used to represent NULL. A bad pointer is really just a pointer which contains a random address just like an uninitialized int variable which starts out with a random int value. The pointer has not yet been assigned the specific address of a valid pointee. This is why dereference operations with bad pointers are so unpredictable. They operate on whatever random area of memory they happen to have the address of. Extra: The Term "Reference" The word "reference" means almost the same thing as the word "pointer". The difference is that "reference" tends to be used in a discussion of pointer issues which is not specific to any particular language or implementation. The word "pointer" connotes the common C/C++ implementation of pointers as addresses. The word "reference" is also used in the phrase "reference parameter" which is a technique which uses pointer parameters for twoway communication between functions this technique is the subject of Section 3. Extra: Why Are Bad Pointer Bugs So Common? Why is it so often the case that programmers will allocate a pointer, but forget to set it to refer to a pointee? The rules for pointers don't seem that complex, yet every programmer makes this error repeatedly. Why? The problem is that we are trained by the tools we use. Simple variables don't require any extra setup. You can allocate a simple variable, such as int, and use it immediately. All that int, char, struct fraction code you have written has trained you, quite reasonably, that a variable may be used once it is declared. Unfortunately, pointers look like simple variables but they require the extra initialization before use. It's unfortunate, in a way, that pointers happen look like other variables, since it makes it easy to forget that the rules for their use are very different. Oh well. Try to remember to assign your pointers to refer to pointees. Don't be surprised when you forget.

11

Section 2 Local Memory


Thanks For The Memory Local variables are the programming structure everyone uses but no one thinks about. You think about them a little when first mastering the syntax. But after a few weeks, the variables are so automatic that you soon forget to think about how they work. This situation is a credit to modern programming languages most of the time variables appear automatically when you need them, and they disappear automatically when you are finished. For basic programming, this is a fine situation. However, for advanced programming, it's going to be useful to have an idea of how variables work... Allocation And Deallocation Variables represent storage space in the computer's memory. Each variable presents a convenient names like length or sum in the source code. Behind the scenes at runtime, each variable uses an area of the computer's memory to store its value. It is not the case that every variable in a program has a permanently assigned area of memory. Instead, modern languages are smart about giving memory to a variable only when necessary. The terminology is that a variable is allocated when it is given an area of memory to store its value. While the variable is allocated, it can operate as a variable in the usual way to hold a value. A variable is deallocated when the system reclaims the memory from the variable, so it no longer has an area to store its value. For a variable, the period of time from its allocation until its deallocation is called its lifetime. The most common memory related error is using a deallocated variable. For local variables, modern languages automatically protect against this error. With pointers, as we will see however, the programmer must make sure that allocation is handled correctly.. Local Memory The most common variables you use are "local" variables within functions such as the variables num and result in the following function. All of the local variables and parameters taken together are called its "local storage" or just its "locals", such as num and result in the following code...
// Local storage example int Square(int num) { int result; result = num * num; return result; }

The variables are called "local" to capture the idea that their lifetime is tied to the function where they are declared. Whenever the function runs, its local variables are allocated. When the function exits, its locals are deallocated. For the above example, that means that when the Square() function is called, local storage is allocated for num and result. Statements like result = num * num; in the function use the local storage. When the function finally exits, its local storage is deallocated.

12 Here is a more detailed version of the rules of local storage... 1. When a function is called, memory is allocated for all of its locals. In other words, when the flow of control hits the starting '{' for the function, all of its locals are allocated memory. Parameters such as num and local variables such as result in the above example both count as locals. The only difference between parameters and local variables is that parameters start out with a value copied from the caller while local variables start with random initial values. This article mostly uses simple int variables for its examples, however local allocation works for any type: structs, arrays... these can all be allocated locally. 2. The memory for the locals continues to be allocated so long as the thread of control is within the owning function. Locals continue to exist even if the function temporarily passes off the thread of control by calling another function. The locals exist undisturbed through all of this. 3. Finally, when the function finishes and exits, its locals are deallocated. This makes sense in a way suppose the locals were somehow to continue to exist how could the code even refer to them? The names like num and result only make sense within the body of Square() anyway. Once the flow of control leaves that body, there is no way to refer to the locals even if they were allocated. That locals are available ("scoped") only within their owning function is known as "lexical scoping" and pretty much all languages do it that way now. Small Locals Example Here is a simple example of the lifetime of local storage...
void Foo(int a) { // (1) Locals (a, b, i, scores) allocated when Foo runs int i; float scores[100]; // This array of 100 floats is allocated locally. a = a + 1; // (2) Local storage is used by the computation for (i=0; i<a; i++) { Bar(i + a); // (3) Locals continue to exist undisturbed, } // even during calls to other functions.

// (4) The locals are all deallocated when the function exits.

Large Locals Example Here is a larger example which shows how the simple rule "the locals are allocated when their function begins running and are deallocated when it exits" can build more complex behavior. You will need a firm grasp of how local allocation works to understand the material in sections 3 and 4 later. The drawing shows the sequence of allocations and deallocations which result when the function X() calls the function Y() twice. The points in time T1, T2, etc. are marked in the code and the state of memory at that time is shown in the drawing.

13
void X() { int a = 1; int b = 2; // T1 Y(a); // T3 Y(b); // T5 } void Y(int p) { int q; q = p + 2; // T2 (first time through), T4 (second time through) }

T1 - X()'s locals have been allocated and given values..

T2 - Y() is called with p=1, and its locals are allocated. X()'s locals continue to be allocated. Y() p q a b 1 3 1 2

T3 - Y() exits and its locals are deallocated. We are left only with X()'s locals.

T4 - Y() is called again with p=2, and its locals are allocated a second time. p q a b 2 4 1 2

T5 - Y() exits and its locals are deallocated. X()'s locals will be deallocated when it exits.

Y()

X()

a b

1 2

X()

X()

a b

1 2

X()

X()

a b

1 2

(optional extra...) The drawing shows the sequence of the locals being allocated and deallocated in effect the drawing shows the operation over time of the "stack" which is the data structure which the system uses to implement local storage. Observations About Local Parameters Local variables are tightly associated with their function they are used there and nowhere else. Only the X() code can refer to its a and b. Only the Y() code can refer to its p and q. This independence of local storage is the root cause of both its advantages and disadvantages. Advantages Of Locals Locals are great for 90% of a program's memory needs.... Convenient. Locals satisfy a convenient need functions often need some temporary memory which exists only during the function's computation. Local variables conveniently provide this sort of temporary, independent memory. Efficient. Relative to other memory use techniques, locals are very efficient. Allocating and deallocating them is time efficient (fast) and they are space efficient in the way they use and recycle memory.

14 Local Copies. Local parameters are basically local copies of the information from the caller. This is also known as "pass by value." Parameters are local variables which are initialized with an assignment (=) operation from the caller. The caller is not "sharing" the parameter value with the callee in the pointer sense the callee is getting its own copy. This has the advantage that the callee can change its local copy without affecting the caller. (Such as with the "p" parameter in the above example.) This independence is good since it keeps the operation of the caller and callee functions separate which follows the rules of good software engineering keep separate components as independent as possible. Disadvantages Of Locals There are two disadvantages of Locals Short Lifetime. Their allocation and deallocation schedule (their "lifetime") is very strict. Sometimes a program needs memory which continues to be allocated even after the function which originally allocated it has exited. Local variables will not work since they are deallocated automatically when their owning function exits. This problem will be solved later in Section 4 with "heap" memory. Restricted Communication. Since locals are copies of the caller parameters, they do not provide a means of communication from the callee back to the caller. This is the downside of the "independence" advantage. Also, sometimes making copies of a value is undesirable for other reasons. We will see the solution to this problem below in Section 3 "Reference Parameters". Synonyms For "Local" Local variables are also known as "automatic" variables since their allocation and deallocation is done automatically as part of the function call mechanism. Local variables are also sometimes known as "stack" variables because, at a low level, languages almost always implement local variables using a stack structure in memory. The Ampersand (&) Bug TAB Now that you understand the allocation schedule of locals, you can appreciate one of the more ugly bugs possible in C and C++. What is wrong with the following code where the function Victim() calls the function TAB()? To see the problem, it may be useful to make a drawing to trace the local storage of the two functions...
// TAB -- The Ampersand Bug function // Returns a pointer to an int int* TAB() { int temp; return(&temp); // return a pointer to the local int } void Victim() { int* ptr; ptr = TAB(); *ptr = 42; }

// Runtime error! The pointee was local to TAB

15 TAB() is actually fine while it is running. The problem happens to its caller after TAB() exits. TAB() returns a pointer to an int, but where is that int allocated? The problem is that the local int, temp, is allocated only while TAB() is running. When TAB() exits, all of its locals are deallocated. So the caller is left with a pointer to a deallocated variable. TAB()'s locals are deallocated when it exits, just as happened to the locals for Y() in the previous example. It is incorrect (and useless) for TAB() to return a pointer to memory which is about to be deallocated. We are essentially running into the "lifetime" constraint of local variables. We want the int to exist, but it gets deallocated automatically. Not all uses of & between functions are incorrect only when used to pass a pointer back to the caller. The correct uses of & are discussed in section 3, and the way to pass a pointer back to the caller is shown in section 4. Local Memory Summary Locals are very convenient for what they do providing convenient and efficient memory for a function which exists only so long as the function is executing. Locals have two deficiencies which we will address in the following sections how a function can communicate back to its caller (Section 3), and how a function can allocate separate memory with a less constrained lifetime (section 4).

Section 2 Extra Optional Material


Extra: How Does The Function Call Stack Work? You do not need to know how local variables are implemented during a function call, but here is a rough outline of the steps if you are curious. The exact details of the implementation are language and compiler specific. However, the basic structure below is approximates the method used by many different systems and languages... To call a function such as foo(6, x+1)... 1. Evaluate the actual parameter expressions, such as the x+1, in the caller's context. 2. Allocate memory for foo()'s locals by pushing a suitable "local block" of memory onto a runtime "call stack" dedicated to this purpose. For parameters but not local variables, store the values from step (1) into the appropriate slot in foo()'s local block. 3. Store the caller's current address of execution (its "return address") and switch execution to foo(). 4. foo() executes with its local block conveniently available at the end of the call stack. 5. When foo() is finished, it exits by popping its locals off the stack and "returns" to the caller using the previously stored return address. Now the caller's locals are on the end of the stack and it can resume executing.

16 For the extremely curious, here are other miscellaneous notes on the function call process... This is why infinite recursion results in a "Stack Overflow Error" the code keeps calling and calling resulting in steps (1) (2) (3), (1) (2) (3), but never a step (4)....eventually the call stack runs out of memory. This is why local variables have random initial values step (2) just pushes the whole local block in one operation. Each local gets its own area of memory, but the memory will contain whatever the most recent tenant left there. To clear all of the local block for each function call would be too time expensive. The "local block" is also known as the function's "activation record" or "stack frame". The entire block can be pushed onto the stack (step 2), in a single CPU operation it is a very fast operation. For a multithreaded environment, each thread gets its own call stack instead of just having single, global call stack. For performance reasons, some languages pass some parameters through registers and others through the stack, so the overall process is complex. However, the apparent the lifetime of the variables will always follow the "stack" model presented here.

17

Section 3 Reference Parameters


In the simplest "pass by value" or "value parameter" scheme, each function has separate, local memory and parameters are copied from the caller to the callee at the moment of the function call. But what about the other direction? How can the callee communicate back to its caller? Using a "return" at the end of the callee to copy a result back to the caller works for simple cases, but does not work well for all situations. Also, sometimes copying values back and forth is undesirable. "Pass by reference" parameters solve all of these problems. For the following discussion, the term "value of interest" will be a value that the caller and callee wish to communicate between each other. A reference parameter passes a pointer to the value of interest instead of a copy of the value of interest. This technique uses the sharing property of pointers so that the caller and callee can share the value of interest. Bill Gates Example Suppose functions A() and B() both do computations involving Bill Gates' net worth measured in billions of dollars the value of interest for this problem. A() is the main function and its stores the initial value (about 55 as of 1998). A() calls B() which tries to add 1 to the value of interest. Bill Gates By Value Here is the code and memory drawing for a simple, but incorrect implementation where A() and B() use pass by value. Three points in time, T1, T2, and T3 are marked in the code and the state of memory is shown for each state...
void B(int worth) { worth = worth + 1; // T2 } void A() { int netWorth; netWorth = 55; // T1 B(netWorth); // T3 -- B() did not change netWorth }

T1 -- The value of interest netWorth is local to A().

T2 -- netWorth is copied to B()'s local worth. B() changes its local worth from 55 to 56. B() worth 55 56

T3 -- B() exits and its local worth is deallocated. The value of interest has not been changed.

A() netWorth 55

A() netWorth 55

A() netWorth 55

18 B() adds 1 to its local worth copy, but when B() exits, worth is deallocated, so changing it was useless. The value of interest, netWorth, rests unchanged the whole time in A()'s local storage. A function can change its local copy of the value of interest, but that change is not reflected back in the original value. This is really just the old "independence" property of local storage, but in this case it is not what is wanted. By Reference The reference solution to the Bill Gates problem is to use a single netWorth variable for the value of interest and never copy it. Instead, each function can receives a pointer to netWorth. Each function can see the current value of netWorth by dereferencing its pointer. More importantly, each function can change the net worth just dereference the pointer to the centralized netWorth and change it directly. Everyone agrees what the current value of netWorth because it exists in only one place everyone has a pointer to the one master copy. The following memory drawing shows A() and B() functions changed to use "reference" parameters. As before, T1, T2, and T3 correspond to points in the code (below), but you can study the memory structure without looking at the code yet. T1 -- The value of interest, T2 -- Instead of a copy, B() T3 -- B() exits, and netWorth, is local to A() receives a pointer to netWorth has been as before. netWorth. B() changed. dereferences its pointer to access and change the real netWorth. B() A() netWorth 55 worth A() netWorth 56

A() netWorth 55 56

The reference parameter strategy: B() receives a pointer to the value of interest instead of a copy. Passing By Reference Here are the steps to use in the code to use the pass-by-reference strategy... Have a single copy of the value of interest. The single "master" copy. Pass pointers to that value to any function which wants to see or change the value. Functions can dereference their pointer to see or change the value of interest. Functions must remember that they do not have their own local copies. If they dereference their pointer and change the value, they really are changing the master value. If a function wants a local copy to change safely, the function must explicitly allocate and initialize such a local copy.

19 Syntax The syntax for by reference parameters in the C language just uses pointer operations on the parameters... 1. Suppose a function wants to communicate about some value of interest int or float or struct fraction. 2. The function takes as its parameter a pointer to the value of interest an int* or float* or struct fraction*. Some programmers will add the word "ref" to the name of a reference parameter as a reminder that it is a reference to the value of interest instead of a copy. 3. At the time of the call, the caller computes a pointer to the value of interest and passes that pointer. The type of the pointer (pointer to the value of interest) will agree with the type in (2) above. If the value of interest is local to the caller, then this will often involve a use of the & operator (Section 1). 4. When the callee is running, if it wishes to access the value of interest, it must dereference its pointer to access the actual value of interest. Typically, this equates to use of the dereference operator (*) in the function to see the value of interest. Bill Gates By Reference Here is the Bill Gates example written to use reference parameters. This code now matches the by-reference memory drawing above.
// B() now uses a reference parameter -- a pointer to // the value of interest. B() uses a dereference (*) on the // reference parameter to get at the value of interest. void B(int* worthRef) { // reference parameter *worthRef = *worthRef + 1; // use * to get at value of interest // T2 } void A() { int netWorth; netWorth = 55; B(&netWorth);

// T1 -- the value of interest is local to A() // Pass a pointer to the value of interest. // In this case using &.

// T3 -- B() has used its pointer to change the value of interest }

Don't Make Copies Reference parameters enable communication between the callee and its caller. Another reason to use reference parameters is to avoid making copies. For efficiency, making copies may be undesirable if the value of interest is large, such as an array. Making the copy requires extra space for the copy itself and extra time to do the copying. From a design point of view, making copies may be undesirable because as soon as there are two copies, it is unclear which one is the "correct" one if either is changed. Proverb: "A person with one watch always knows what time it is. A person with two watches is never sure." Avoid making copies.

20 Simple Reference Parameter Example Swap() The standard example of reference parameters is a Swap() function which exchanges the values of two ints. It's a simple function, but it does need to change the caller's memory which is the key feature of pass by reference. Swap() Function The values of interest for Swap() are two ints. Therefore, Swap() does not take ints as its parameters. It takes a pointers to int (int*)'s. In the body of Swap() the parameters, a and b, are dereferenced with * to get at the actual (int) values of interest.
void Swap(int* a, int* b) { int temp; temp = *a; *a = *b; *b = temp; }

Swap() Caller To call Swap(), the caller must pass pointers to the values of interest...
void SwapCaller() { int x = 1; int y = 2; Swap(&x, &y); } // Use & to pass pointers to the int values of interest // (x and y).

Swap() a

temp 1

SwapCaller() x 1 2

y2 1

The parameters to Swap() are pointers to values of interest which are back in the caller's locals. The Swap() code can dereference the pointers to get back to the caller's memory to exchange the values. In this case, Swap() follows the pointers to exchange the values in the variables x and y back in SwapCaller(). Swap() will exchange any two ints given pointers to those two ints. Swap() With Arrays Just to demonstrate that the value of interest does not need to be a simple variable, here's a call to Swap() to exchange the first and last ints in an array. Swap() takes int*'s, but the ints can be anywhere. An int inside an array is still an int.
void SwapCaller2() { int scores[10]; scores[0] = 1; scores[9[ = 2; Swap(&(scores[0]), &(scores[9]));// the ints of interest do not need to be // simple variables -- they can be any int. The caller is responsible // for computing a pointer to the int.

21 The above call to Swap() can be written equivalently as Swap(scores, scores+9) due to the array syntax in C. You can ignore this case if it is not familiar to you it's not an important area of the language and both forms compile to the exact same thing anyway. Is The & Always Necessary? When passing by reference, the caller does not always need to use & to compute a new pointer to the value of interest. Sometimes the caller already has a pointer to the value of interest, and so no new pointer computation is required. The pointer to the value of interest can be passed through unchanged. For example, suppose B() is changed so it calls a C() function which adds 2 to the value of interest...
// Takes the value of interest by reference and adds 2. void C(int* worthRef) { *worthRef = *worthRef + 2; } // Adds 1 to the value of interest, and calls C(). void B(int* worthRef) { *worthRef = *worthRef + 1; // add 1 to value of interest as before C(worthRef); // NOTE no & required. We already have // a pointer to the value of interest, so // it can be passed through directly.

What About The & Bug TAB? All this use of & might make you nervous are we committing the & bug from Section 2? No, it turns out the above uses of & are fine. The & bug happens when an & passes a pointer to local storage from the callee back to its caller. When the callee exits, its local memory is deallocated and so the pointer no longer has a pointee. In the above, correct cases, we use & to pass a pointer from the caller to the callee. The pointer remains valid for the callee to use because the caller locals continue to exist while the callee is running. The pointees will remain valid due to the simple constraint that the caller can only exit sometime after its callee exits. Using & to pass a pointer to local storage from the caller to the callee is fine. The reverse case, from the callee to the caller, is the & bug. The ** Case What if the value of interest to be shared and changed between the caller and callee is already a pointer, such as an int* or a struct fraction*? Does that change the rules for setting up reference parameters? No. In that case, there is no change in the rules. They operate just as before. The reference parameter is still a pointer to the value of interest, even if the value of interest is itself a pointer. Suppose the value of interest is int*. This means there is an int* value which the caller and callee want to share and change. Then the reference parameter should be an int**. For a struct fraction* value of interest, the reference parameter is struct fraction**. A single dereference (*) operation on the reference parameter yields the value of interest as it did in the simple cases. Double pointer (**) parameters are common in linked list or other pointer manipulating code were the value of interest to share and change is itself a pointer, such as a linked list head pointer.

22 Reference Parameter Summary Passing by value (copying) does not allow the callee to communicate back to its caller and has also has the usual disadvantages of making copies. Pass by reference uses pointers to avoid copying the value of interest, and allow the callee to communicate back to the caller. For pass by reference, there is only one copy of the value of interest, and pointers to that one copy are passed. So if the value of interest is an int, its reference parameter is an int*. If the value of interest is a struct fraction*, its reference parameters is a struct fraction**. Functions use the dereference operator (*) on the reference parameter to see or change the value of interest.

Section 3 Extra Optional Material


Extra: Reference Parameters in Java Because Java has no */& operators, it is not possible to implement reference parameters in Java directly. Maybe this is ok in the OOP paradigm, you should change objects by sending them messages which makes the reference parameter concept unnecessary. The caller passes the callee a (shallow) reference to the value of interest (object of interest?), and the callee can send it a message to change it. Since all objects are intrinsically shallow, any change is communicated back to the caller automatically since the object of interest was never copied. Extra: Reference Parameters in C++ Reference parameters are such a common programming task that they have been added as an official feature to the C++ language. So programming reference parameters in C++ is simpler than in C. All the programmer needs to do is syntactically indicate that they wish for a particular parameter to be passed by reference, and the compiler takes care of it. The syntax is to append a single '&' to right hand side of the parameter type. So an int parameter passes an integer by value, but an int& parameter passes an integer value by reference. The key is that the compiler takes care of it. In the source code, there's no additional fiddling around with &'s or *'s. So Swap() and SwapCaller() written with C++ look simpler than in C, even though they accomplish the same thing...

23
void Swap(int& a, int& b) { int temp; temp = a; a = b; b = temp; } void SwapCaller() { int x = 1; int y = 2; Swap(x, y); // No &'s required -- the compiler takes care of it } // The & declares pass by reference

// No *'s required -- the compiler takes care of it

The types of the various variables and parameters operate simply as they are declared (int in this case). The complicating layer of pointers required to implement the reference parameters is hidden. The compiler takes care of it without allowing the complication to disturb the types in the source code.

24

Section 4 Heap Memory


"Heap" memory, also known as "dynamic" memory, is an alternative to local stack memory. Local memory (Section 2) is quite automatic it is allocated automatically on function call and it is deallocated automatically when a function exits. Heap memory is different in every way. The programmer explicitly requests the allocation of a memory "block" of a particular size, and the block continues to be allocated until the programmer explicitly requests that it be deallocated. Nothing happens automatically. So the programmer has much greater control of memory, but with greater responsibility since the memory must now be actively managed. The advantages of heap memory are... Lifetime. Because the programmer now controls exactly when memory is allocated and deallocated, it is possible to build a data structure in memory, and return that data structure to the caller. This was never possible with local memory which was automatically deallocated when the function exited. Size. The size of allocated memory can be controlled with more detail. For example, a string buffer can be allocated at run-time which is exactly the right size to hold a particular string. With local memory, the code is more likely to declare a buffer size 1000 and hope for the best. (See the StringCopy() example below.) The disadvantages of heap memory are... More Work. Heap allocation needs to arranged explicitly in the code which is just more work. More Bugs. Because it's now done explicitly in the code, realistically on occasion the allocation will be done incorrectly leading to memory bugs. Local memory is constrained, but at least it's never wrong. Nonetheless, there are many problems that can only be solved with heap memory, so that's that way it has to be. In languages with garbage collectors such as Perl, LISP, or Java, the above disadvantages are mostly eliminated. The garbage collector takes over most of the responsibility for heap management at the cost of a little extra time taken at run-time. What Does The Heap Look Like? Before seeing the exact details, let's look at a rough example of allocation and deallocation in the heap... Allocation The heap is a large area of memory available for use by the program. The program can request areas, or "blocks", of memory for its use within the heap. In order to allocate a block of some size, the program makes an explicit request by calling the heap allocation function. The allocation function reserves a block of memory of the requested size in the heap and returns a pointer to it. Suppose a program makes three allocation requests to

25 allocate memory to hold three separate GIF images in the heap each of which takes 1024 bytes of memory. After the three allocation requests, memory might look like...

Local

Heap
(Free) (Gif3) (Gif2) (Gif1) 3 separate heap blocks each 1024 bytes in size.

Each allocation request reserves a contiguous area of the requested size in the heap and returns a pointer to that new block to the program. Since each block is always referred to by a pointer, the block always plays the role of a "pointee" (Section 1) and the program always manipulates its heap blocks through pointers. The heap block pointers are sometimes known as "base address" pointers since by convention they point to the base (lowest address byte) of the block. In this example, the three blocks have been allocated contiguously starting at the bottom of the heap, and each block is 1024 bytes in size as requested. In reality, the heap manager can allocate the blocks wherever it wants in the heap so long as the blocks do not overlap and they are at least the requested size. At any particular moment, some areas in the heap have been allocated to the program, and so are "in use". Other areas have yet to be committed and so are "free" and are available to satisfy allocation requests. The heap manager has its own, private data structures to record what areas of the heap are committed to what purpose at any moment The heap manager satisfies each allocation request from the pool of free memory and updates its private data structures to record which areas of the heap are in use. Deallocation When the program is finished using a block of memory, it makes an explicit deallocation request to indicate to the heap manager that the program is now finished with that block. The heap manager updates its private data structures to show that the area of memory occupied by the block is free again and so may be re-used to satisfy future allocation requests. Here's what the heap would look like if the program deallocates the second of the three blocks...

26

Local

Heap
(Free) (Gif3) (Free) (Gif1)

After the deallocation, the pointer continues to point to the now deallocated block. The program must not access the deallocated pointee. This is why the pointer is drawn in gray the pointer is there, but it must not be used. Sometimes the code will set the pointer to NULL immediately after the deallocation to make explicit the fact that it is no longer valid. Programming The Heap Programming the heap looks pretty much the same in most languages. The basic features are.... The heap is an area of memory available to allocate areas ("blocks") of memory for the program. There is some "heap manager" library code which manages the heap for the program. The programmer makes requests to the heap manager, which in turn manages the internals of the heap. In C, the heap is managed by the ANSI library functions malloc(), free(), and realloc(). The heap manager uses its own private data structures to keep track of which blocks in the heap are "free" (available for use) and which blocks are currently in use by the program and how large those blocks are. Initially, all of the heap is free. The heap may be of a fixed size (the usual conceptualization), or it may appear to be of a fixed but extremely large size backed by virtual memory. In either case, it is possible for the heap to get "full" if all of its memory has been allocated and so it cannot satisfy an allocation request. The allocation function will communicate this run-time condition in some way to the program usually by returning a NULL pointer or raising a language specific run-time exception. The allocation function requests a block in the heap of a particular size. The heap manager selects an area of memory to use to satisfy the request, marks that area as "in use" in its private data structures, and returns a pointer to the heap block. The caller is now free to use that memory by dereferencing the pointer. The block is guaranteed to be reserved for the sole use of the caller the heap will not hand out that same area of memory to some other caller. The block does not move around inside the

27 heap its location and size are fixed once it is allocated. Generally, when a block is allocated, its contents are random. The new owner is responsible for setting the memory to something meaningful. Sometimes there is variation on the memory allocation function which sets the block to all zeros (calloc() in C). The deallocation function is the opposite of the allocation function. The program makes a single deallocation call to return a block of memory to the heap free area for later re-use. Each block should only be deallocated once. The deallocation function takes as its argument a pointer to a heap block previously furnished by the allocation function. The pointer must be exactly the same pointer returned earlier by the allocation function, not just any pointer into the block. After the deallocation, the program must treat the pointer as bad and not access the deallocated pointee. C Specifics In the C language, the library functions which make heap requests are malloc() ("memory allocate") and free(). The prototypes for these functions are in the header file <stdlib.h>. Although the syntax varies between languages, the roles of malloc() and free() are nearly identical in all languages... void* malloc(unsigned long size); The malloc() function takes an unsigned integer which is the requested size of the block measured in bytes. Malloc() returns a pointer to a new heap block if the allocation is successful, and NULL if the request cannot be satisfied because the heap is full. The C operator sizeof() is a convenient way to compute the size in bytes of a type sizeof(int) for an int pointee, sizeof(struct fraction) for a struct fraction pointee. void free(void* heapBlockPointer); The free() function takes a pointer to a heap block and returns it to the free pool for later reuse. The pointer passed to free() must be exactly the pointer returned earlier by malloc(), not just a pointer to somewhere in the block. Calling free() with the wrong sort of pointer is famous for the particularly ugly sort of crashing which it causes. The call to free() does not need to give the size of the heap block the heap manager will have noted the size in its private data structures. The call to free() just needs to identify which block to deallocate by its pointer. If a program correctly deallocates all of the memory it allocates, then every call to malloc() will later be matched by exactly one call to free() As a practical matter however, it is not always necessary for a program to deallocate every block it allocates see "Memory Leaks" below. Simple Heap Example Here is a simple example which allocates an int block in the heap, stores the number 42 in the block, and then deallocates it. This is the simplest possible example of heap block allocation, use, and deallocation. The example shows the state of memory at three different times during the execution of the above code. The stack and heap are shown separately in the drawing a drawing for code which uses stack and heap memory needs to distinguish between the two areas to be accurate since the rules which govern the two areas are so different. In this case, the lifetime of the local variable intPtr is totally separate from the lifetime of the heap block, and the drawing needs to reflect that difference.

28
void Heap1() { int* intPtr; // Allocates local pointer local variable (but not its pointee) // T1

Local
intPtr

Heap

// Allocates heap block and stores its pointer in local variable. // Dereferences the pointer to set the pointee to 42. intPtr = malloc(sizeof(int)); *intPtr = 42; // T2

Local
intPtr

Heap
42

// Deallocates heap block making the pointer bad. // The programmer must remember not to use the pointer // after the pointee has been deallocated (this is // why the pointer is shown in gray). free(intPtr); // T3

Local
intPtr

Heap

Simple Heap Observations After the allocation call allocates the block in the heap. The program stores the pointer to the block in the local variable intPtr. The block is the "pointee" and intPtr is its pointer as shown at T2. In this state, the pointer may be dereferenced safely to manipulate the pointee. The pointer/pointee rules from Section 1 still apply, the only difference is how the pointee is initially allocated.

29 At T1 before the call to malloc(), intPtr is uninitialized does not have a pointee at this point intPtr "bad" in the same sense as discussed in Section 1. As before, dereferencing such an uninitialized pointer is a common, but catastrophic error. Sometimes this error will crash immediately (lucky). Other times it will just slightly corrupt a random data structure (unlucky). The call to free() deallocates the pointee as shown at T3. Dereferencing the pointer after the pointee has been deallocated is an error. Unfortunately, this error will almost never be flagged as an immediate run-time error. 99% of the time the dereference will produce reasonable results 1% of the time the dereference will produce slightly wrong results. Ironically, such a rarely appearing bug is the most difficult type to track down. When the function exits, its local variable intPtr will be automatically deallocated following the usual rules for local variables (Section 2). So this function has tidy memory behavior all of the memory it allocates while running (its local variable, its one heap block) is deallocated by the time it exits. Heap Array In the C language, it's convenient to allocate an array in the heap, since C can treat any pointer as an array. The size of the array memory block is the size of each element (as computed by the sizeof() operator) multiplied by the number of elements (See CS Education Library/101 The C Language, for a complete discussion of C, and arrays and pointers in particular). So the following code heap allocates an array of 100 struct fraction's in the heap, sets them all to 22/7, and deallocates the heap array...
void HeapArray() { struct fraction* fracts; int i; // allocate the array fracts = malloc(sizeof(struct fraction) * 100); // use it like an array -- in this case set them all to 22/7 for (i=0; i<99; i++) { fracts[i].numerator = 22; fracts[i].denominator = 7; } // Deallocate the whole array free(fracts); }

30 Heap String Example Here is a more useful heap array example. The StringCopy() function takes a C string, makes a copy of that string in the heap, and returns a pointer to the new string. The caller takes over ownership of the new string and is responsible for freeing it.
/* Given a C string, return a heap allocated copy of the string. Allocate a block in the heap of the appropriate size, copies the string into the block, and returns a pointer to the block. The caller takes over ownership of the block and is responsible for freeing it. */ char* StringCopy(const char* string) { char* newString; int len; len = strlen(string) + 1; // +1 to account for the '\0' newString = malloc(sizeof(char)*len); // elem-size * number-of-elements assert(newString != NULL); // simplistic error check (a good habit) strcpy(newString, string); // copy the passed in string to the block return(newString); } // return a ptr to the block

Heap String Observations StringCopy() takes advantage of both of the key features of heap memory... Size. StringCopy() specifies, at run-time, the exact size of the block needed to store the string in its call to malloc(). Local memory cannot do that since its size is specified at compile-time. The call to sizeof(char) is not really necessary, since the size of char is 1 by definition. In any case, the example demonstrates the correct formula for the size of an array block which is element-size * number-of-elements. Lifetime. StringCopy() allocates the block, but then passes ownership of it to the caller. There is no call to free(), so the block continues to exist even after the function exits. Local memory cannot do that. The caller will need to take care of the deallocation when it is finished with the string. Memory Leaks What happens if some memory is heap allocated, but never deallocated? A program which forgets to deallocate a block is said to have a "memory leak" which may or may not be a serious problem. The result will be that the heap gradually fill up as there continue to be allocation requests, but no deallocation requests to return blocks for re-use. For a program which runs, computes something, and exits immediately, memory leaks are not usually a concern. Such a "one shot" program could omit all of its deallocation requests and still mostly work. Memory leaks are more of a problem for a program which runs for an indeterminate amount of time. In that case, the memory leaks can gradually fill the heap until allocation requests cannot be satisfied, and the program stops working or crashes. Many commercial programs have memory leaks, so that when run for long enough, or with large data-sets, they fill their heaps and crash. Often the error detection and avoidance code for the heap-full error condition is not well tested, precisely because the case is rarely encountered with short runs of the program that's why filling the heap often results in a real crash instead of a polite error message. Most compilers have a

31 "heap debugging" utility which adds debugging code to a program to track every allocation and deallocation. When an allocation has no matching deallocation, that's a leak, and the heap debugger can help you find them. Ownership StringCopy() allocates the heap block, but it does not deallocate it. This is so the caller can use the new string. However, this introduces the problem that somebody does need to remember to deallocate the block, and it is not going to be StringCopy(). That is why the comment for StringCopy() mentions specifically that the caller is taking on ownership of the block. Every block of memory has exactly one "owner" who takes responsibility for deallocating it. Other entities can have pointers, but they are just sharing. There's only one owner, and the comment for StringCopy() makes it clear that ownership is being passed from StringCopy() to the caller. Good documentation always remembers to discuss the ownership rules which a function expects to apply to its parameters or return value. Or put the other way, a frequent error in documentation is that it forgets to mention, one way or the other, what the ownership rules are for a parameter or return value. That's one way that memory errors and leaks are created. Ownership Models The two common patterns for ownership are... Caller ownership. The caller owns its own memory. It may pass a pointer to the callee for sharing purposes, but the caller retains ownership. The callee can access things while it runs, and allocate and deallocate its own memory, but it should not disrupt the caller's memory. Callee allocated and returned. The callee allocates some memory and returns it to the caller. This happens because the result of the callee computation needs new memory to be stored or represented. The new memory is passed to the caller so they can see the result, and the caller must take over ownership of the memory. This is the pattern demonstrated in StringCopy(). Heap Memory Summary Heap memory provides greater control for the programmer the blocks of memory can be requested in any size, and they remain allocated until they are deallocated explicitly. Heap memory can be passed back to the caller since it is not deallocated on exit, and it can be used to build linked structures such as linked lists and binary trees. The disadvantage of heap memory is that the program must make explicit allocation and deallocate calls to manage the heap memory. The heap memory does not operate automatically and conveniently the way local memory does.

Chapter 1 Arrays
1] What would the output of the following program? main() { char a[] = "Visual C++"; char *b = "Visual C++"; printf("\n %d %d",sizeof(a),sizeof(b)); printf("\n %d %d",sizeof(*a),sizeof(*b)); }

2]

For the following statements would arr[3] and ptr[3] fetch the same character? <Yes / No> char arr[] = "Surprised"; char *ptr = "surprised";

3]

For the statements in 9.2 does the compiler fetch the character arr[3] and ptr[3] in the same manner?

4]

What would be the output of the following program, if the array begins at address 1200? main() { int arr[] = {2,3,4,1,6}; printf("%d %d",arr, sizeof(arr)); }

5]

Does mentioning the array name gives the base address in all the contexts?

6]

What would be the output of the following prograam, if the aray begins at address 65486 ? main() { int arr[] = {12,14,15,23,45}; printf("%u %u",arr, &arr); }

7]

Are the expressions arr and &arr same for an array of 10 integers ?

8]

What would be the output of the following prograam, if the aray begins at address 65486 ? main() { int arr[] = {12,14,15,23,45}; printf("%u %u",arr + 1, &arr + 1); }

9]

When are 'char a[]' and 'char *a' treated as same by the compiler ?

10]

Would the following program compile successfully ? main() { char a[] = "Sunstroke"; char *p = "Coldwave"; a = "Coldwave"; b = "Sunstroke"; printf("\n %s %s",a,p); }

11]

What would be the output of the following program ? main() { float a[] = {12.4,2.3,4.5,6.7}; printf("\n %d",sizeof(a) / sizeof(a[0])); }

12] A pointer to a block of memory is effectively same as an array. <True / False>

13]

What would be the output of the following program if the array begins at 65472? main() { int a[3][4] = { 1,2,3,4, 4,3,2,1, 7,8,9,0 }; printf("\n %u %u",a + 1, &a + 1); }

14]

What does the follwoing declaration mean: int(*ptr)[10];

15]

If we pass the name of a 1-D int array to a function it decays into a pointer to an int. If we pass the name of a 2-D array of integers to a function what would it decay into ?

16]

How would you define the function f() in the following program? int arr[MAXROW][MAXCOL]; fun(arr);

17]

What would be the output of the following program ? main() { int a[3][4] = { 1,2,3,4, 4,3,2,8, 7,8,9,0 }; int *ptr; ptr = &a[0][0]; fun(&ptr); } fun(int **p) { printf("\n %d",**p); }

*********************************************************************** ************************* ANSWERS ****************************

***********************************************************************

1]

11 2 1 1

2]

Yes

3]

No. For arr[3] the compiler generates code to start at location arr, move past it, and fetch the character there. When it sees the expression ptr[3] it generates the code to start at

location stored in ptr, add three to the pointer, and finally fetch the character pointed to. In other words, arr[3] is three places past the start of the object named arr, whereas ptr[3] is three places past the object pointed to by ptr.

4]

1200

10

5]

No. Whenever mentioning the array name gives its base address it is said that the array has decayed into a pointer. This decaying doesn't take place in two situations: ----When array name is used with sizeof operator. When the array name is an operand of the & operator.

6]

65486

65486

7]

No. Even though both may give the same addresses as in (6) they mean two different things. 'arr' gives the address of the first 'int' whereas '&arr' gives the address of array of 'ints'. Since these addresses happen to be same the results of the expressions are same.

8]

65488

65496

9]

When using them as formal parameters while defining a function.

10]

No, because we may assign a new string ot a pointer but not to an array.

11]

12]

True

13]

65480

65496

14]

'ptr' is a pointer to an array of 10 integers.

15]

It decays into a pointer to an array and not a pointer to a pointer.

16]

fun(int a[][MAXCOL]) { }

OR fun(int (*ptr)[MAXCOL]) /* { } ptr is pointer to an array */

17]

Chapter-2 Bitwise Operators


1] What would be the output of the following program? main() { int i = 32,j = 0x20,k,l,m; k = j | j; l = i & j; m = k ^ l; printf("%d %d %d %d %d",i,j,k,l,m); } A] B] C] D] 32 32 32 32 0 0 0 0 0 0 0 32 32 32 32 32 32 32 32 32

2]

What would be the output of the following program? main() { unsigned int m = 32; printf("%x",~m); }

A] B] C] D]

ffff 0000 ffdf ddfd

3]

What would be the output of the following program?

main() { unsigned int a = 0xffff; ~a; printf("%x",a); } A] B] C] D] ffff 0000 00ff None of the above.

4]

Point out the error in the following program. main() { unsigned int a,b,c,d,e,f; a = b = c = d = e = f = 32; a <<= 2; b >>= 2; c ^= 2; d |= 2; e &= 2; f ~= 2; printf("\n %x %x %x %x %x %x",a,b,c,d,e,f); }

5]

To which numbering system can the binary number 1011011111000101 be easily converted to?

6]

Which bitwise operator is suitable for checking whether a particular bit is 'on' or 'off'?

7]

Which bitwise operator is suitable for turning of a particular bit in a number?

8]

Which bitwise operator is suitable for putting on a particular bit in a number?

9]

On left shifting, the bits from the left are rotated an brought to the right and accommodated where there is empty space on the right? < True / False >

10] Left shifthing a number by 1 is always equibalent to it by 2. < Yes / No >

multiplying

11]

Left shifting an unsigned int or char by 1 is always equivalent to multiplying it by 2. < Yes / No >

12]

What would be the output of the following program? main() { unsigned char i = 0x80; printf("\n %d",i << 1); }

A] B] C] D]

0 256 100 None of the above.

13]

What is the following program doing? main() { unsigned int m[] = {0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80}; unsinged char n,i; scanf("%d",&n); for(i = 0; i <= 7; i++) { if (n & m[i]) printf("\n yes"); } }

14]

What does the follwing program do? main() { char *s; s = fun(128,2); printf("\n %s",s) } fun(unsigned int num,int base) { static char buff[33]; char *ptr; ptr = &buff[ sizeof(buff) - 1]; *ptr = '\0'; do { *--ptr = "0123456789abcdef"[num % base]; num /= base; }while (num != 0); return ptr; }

A] B] C]

It converts a number to given base. It gives a compilation error. None of the above.

15]

#define #define #define #define #define #define

CHARSIZE 8 MASK(y) ( 1 << % CHARSIZE) BITSLOT(y) (y / CHARSIZE) SET(x,y) (x[BITSLOT(y) |= MASK(y)) TEST(x,y) (x[BITSLOT(y)] & MASK(y)) NUMSLOTS(n) ((n + CHARSIZE - 1) / CHARSIZE)

(a) (b) (c)

Given the above macros how would you declare an array arr of 50 bits. put the 20th bit on. test whether the 40th bit is 'on' or 'off'.

16]

Consider the macros in problem 14.15 above. On similar lines can you define a macro which would clear a given bit in a bit array?

17]

What does the following progaram do? main() { unsigned int num; int c = 0; scanf("%u",&num); for( ; num; num>>= 1) { if(num & 1) c++; } printf("%d",c); }

A] B] C] D]

It counts the number of bits which are on in the number num. It sets all bits in the number num to 1. It sets all bits in the number num to 0. None of the above.

18]

What would be the output of the following program? main() { printf("\n %x", -1 >> 4); }

A] B] C] D]

ffff 0fff 0000 fff0

19]

In the statement expression1 >> expression2 if expressin1 is a signed integer with its leftmost bit set to 1 then on

right-shifting it the result of the statement would vary from computer to computer. < True / False >

20]

What does the following program do? main() { unsigned int num; int i; scanf("%u",&num); for( i = 0; i < 16; i++) printf("%d",(num << 1 & 1 << 15)? 1: 0); }

A] B] C] D]

It prints all even bits from num. It prints all odd bits from num. It prints binary equivalent fo num. None of the above.

*********************************************************************** ****************** ANSWERS ******************

***********************************************************************

1]

2]

3]

4]

Error is in f~= 2, since there is no operator as '~='.

5]

Hexadecimal, since each 4-digit binary represents one hexadecimal digit.

6]

The '&' operator.

7]

The '|' operator.

8]

False.

10]

No.

11]

Yes.

12]

13]

14]

15]

char arr[NUMSLOTS(50)]; SET(arr,20); if (TEST(arr,40))

16]

#define CLEAR(x,y) (x[BITSLOT(y)] &= ~MASK(y))

17]

18]

A. On computers which don't support sign extension you may get B.

19]

True.

20]

Chapter-3 Command Line arguments

1]

What do the 'c' and 'v' in 'argc' and 'argv' stand for?

2]

According to ANSI specifications which is the correct way of decalrating main() when it receives command line arguments? main(int argc, char *argv[]) main(argc,argv) int argc; char *argv[]; main() { int argc; char *argv[]; } None of the above.

A] B] C]

D]

3]

What would be the output of the following program? /* sample.c*/ main(int argc,char **argv) { argc = argc - (argc - 1); printf("%s",argv[argc - 1]); }

4]

If different command line arguments are supplied at different times would the output of the following program change? < Yes / No> main(int argc, char *argv[]) { printf("%d",argv[argc]); }

5]

If the following program (myprog) is run form the command line as myprog 1 2 3 What would be the output/ main(int argc, char *argv[]) { int i; for(i = 0; i < argc; i++) printf("%s",argv[i]); }

6]

If the following program (myprog) is run form the command line as myprog 1 2 3 What would be the output? main(int argc,char *argv[]) { int i; i = argv[1] + argv[2] + argv[3]; printf("%d",i); }

A] B] C] D]

123 6 Error. "123"

7]

If the following program (myprog) is run form the command line as myprog 1 2 3 What would be the output? main(int argc,char *argv[]) { int i,j = 0; for(i = o; i < argc; i++) j = j + atoi(argv[i]); printf("%d",j); }

A] B] C] D]

123 6 Error. "123"

8]

Would the following program give the same output at all times? < Yes / No> main(int argc, char*argv[]) { strcpy(argv[0],"hello"); strcpy(argv[1],"good morning"); printf("%s %s",argv[0],argc[1]); }

9]

If the following program (myprog) is run from the command line as myprog one two three What would be the output? main(int argc, char *argv[]) { printf("%s",*++argv); }

10]

If the following program (myprog) is run from the command line as myprog one two three What would be the output?

main(int argc, char *argv[]) { printf("%c",*++argv); }

11]

The variables 'argc' and 'argv' are always local to main. <True / False>

12]

The maximum combined length of the command line arguments including the spaces between adjacent arguments is 128 characters. 256 characters. 67 hcaracters. It may vary from one operating system to another.

A] B] C] D]

13]

What will the following program output? main(int argc, char *argv[],char *env[]) { int i; for(i = 1; i < argc ; i++) printf("%s",env[i]); }

A] B] C] D]

List of all environment variables. List of all command line arguments. Error. NULL.

14]

If the following program (myprog) is run from the command line as myprog "*.c" What would be the output? main(int argc, char *argv[]) { int i; for(i = 1; i < argc; i++) printf("%s",argv[i]); }

A] B] C] D]

*.c List of all .c files in the current directory "*.c" None of the above

15]

If the following program (myprog) is run from the command line as

myprog *.c What would be the output? main(int argc, char *argv[]) { int i; for(i = 1; i < argc; i++) printf("%s",argv[i]); } A] B] C] D] *.c List of all .c files in the current directory "*.c" None of the above

16]

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?

17]

Does there exist any way to make the command line arguments available to other functions without passing them as arguments to the function? < Yes / No>

18]

If the following program (myprog) is run from the command line as myprog Jan Feb Mar What would be the output? #include "dos.h" main() { fun(); } fun() { int i; for(i = 0; i <_argc; i++) printf("%s",_argv[i]); }

19]

If the following program (myprog) is present in the directory c:\bc\tucs then what would be its output? main(int argc, char *argv[]) { printf("%s",argv[0]); }

A] B] C] D]

MYPROG C:\BC\TUCS\MYPROG Error C:\BC\TUCS

20]

Which is an easy way to extract myprog form the output of program 13.19 above?

21] A] B] C] D]

Which of the following is true about argv? It is an array of character pointers. It is a pointer to an array of character pointers. It is an array of strings. None of the above.

22]

If the following program (myprog) is run from the command line as myprog monday tuesday wednesday thursday What would be the output? main(int argc, char *argv[]) { while(--argc > 0) printf("%s",*++argv); }

A] B] C] D]

myprog monday tuesday wednesday thursday monday tuesday wednesday thursday myprog tuesday thursday None of the above.

23]

If the following program (myprog) is run form the command line as myprog friday tuesday sunday What will be the output? main(int argc, char *argv[]) { printf("%c",(*++argv)[0]); }

A] B] C] D]

m f myprog friday

24]

If the following program (myprog) is run form the command line as myprog friday tuesday sunday What will be the output? main(int argc, char *argv[]) { printf("%c",**++argv); }

A] B] C] D]

m f myprog friday

25]

If the following program (myprog) is run form the command line as myprog friday tuesday sunday What will be the output? main(int argc, char *argv[]) { printf("%c",*++argv[1]); }

A] B] C] D]

r f m y

26]

If the following program (myprog) is run form the command line as myprog friday tuesday sunday What will be the output? main(int sizeofargv, char *argv[]) { while(sizeofargv) printf("%s",argv[--sizeofargv]); }

A] B] C] D]

myprog myprog sunday sunday

friday tuesday sunday friday tuesday tuesday friday myprog tuesday friday

*********************************************************************** ************************* ANSWERS *******************************

***********************************************************************

1]

Count of arguments and vector(array) of arguments.

2]

3]

C:\SAMPLE.EXE

4]

No

5]

C:\MYPROG.EXE 1 2 3

6]

7]

B. When atoi() tries to convert argv[0] to a number it cannot do so (argv[0] being a file name) and hence returns a zero.

8]

No

9]

one

10]

11]

True

12]

13]

14]

15]

16]

Yes. Compile the program as tcc myprog wildargs.obj This compiles the file myprog.c and links it withe the wildcard expansion module WILDCARGs.OBJ, then run the resulting executable file MYPROG.EXE. If you want the wildcard expansion to be default so that you won't have to link your program explicitly with WILDCARGS.OBJ, you can midigy our standard C?.LIB library files to have WILDCARGS.OBJ linked automatically. To acheive htis we have to remove SET ARGV from the library and add WILDCRAGS. The commands will invoke the Turbo Librarian to modify all the standard library files (assuming the current directory contains the standard C libraries, and WILDCRAGS.OBJ): tlib tlib tlib tlib tlib cs cc cm cl ch -setargv -setragv -strargv -setargv -setargv +wildargs +wildargs +wildargs +wildargs +wildargs

17]

Yes.

Using the predefined variables_arcg,_argv.

18]

C:\MYPROG.EXE Jan Feb Mar

19]

20]

#include "dir.h" main(int arc, char *argv[]) { char drive[3],dir[50],name[8],ext[3]; printf("\n %s",argv[0]); fnsplit(argv[0],drive,dir,name,ext); printf("\n %s \n %s \n %s \n %s",drive,dir,name,ext); }

21]

22]

23]

24]

25]

26]

Chapter-4 Complicated Declarations


1] What do the following declarations signify?

A. B. C. D. E. F. G. H. I. J. K. L. M. N. O. P. Q.

int *f(); int (*pf)(); char **argv; void (*f[10])(int,int); char far *scr; char far *arr[10]; int (*a[5])(int far *p); char far *scr1, *scr2; int (*ftable[])(void) = {fadd,fsub,fmul,fdiv}; int (*ptr)[30]; int *ptr[30]; void *cmp(); void (*cmp)(); char (*(*f())[])(); char (*(*x[3])())[5]; void (*f)(int, void(*)()); int **(*)(int **, int **(*)(int **, int **));

R. S. T. U.

void(*)(void(*)(int *, void **), int(*)(void **, int *)); char far * far *ptr; char far * near *ptr; char far * huge *ptr;

2]

What would be the output of the following program? main() { char near * near *ptr1; char near * far *ptr2; char near * huge *ptr3; printf("%d %d %d",sizeof(ptr1),sizeof(ptr2),sizeof(ptr3)); }

3]

What would be the output of the following program? main() { char far * char far * char far * printf("%d }

near *ptr1; far *ptr2; huge *ptr3; %d %d",sizeof(ptr1),sizeof(ptr2),sizeof(ptr3));

4]

What would be the output of the following program? main() { char huge * near *ptr1; char huge * far *ptr2; char huge * huge *ptr3; printf("%d %d %d",sizeof(ptr1),sizeof(ptr2),sizeof(ptr3)); }

5]

What would be the output of the following program? main() { char huge * near * far *ptr1; char near * far * huge *ptr2; char far * huge * near *ptr3; printf("%d %d %d",sizeof(ptr1),sizeof(ptr2),sizeof(ptr3)); }

6]

What would be the output of the following program?

main() { char huge * near * far *ptr1; char near * far * huge *ptr2; char far * huge * near *ptr3; printf("%d %d %d",sizeof(ptr1),sizeof(*ptr2),sizeof(**ptr3)); }

7]

What would be the output of the following program? main() { char huge * near * far *ptr1; char near * far * huge *ptr2; char far * huge * near *ptr3; printf("%d %d %d",sizeof(*ptr1),sizeof(**ptr2),sizeof(ptr3)); }

8]

What would be the output of the following program? main() { char huge * near * far *ptr1; char near * far * huge *ptr2; char far * huge * near *ptr3; printf("%d %d %d",sizeof(**ptr1),sizeof(ptr2),sizeof(*ptr3)); }

9]

Are the following two declarations same? char far * far *scr; char far far **scr;

< Yes

No>

10]

How would you declare the following: An array of three pointers to chars. An array of three char pointers. A pointer to an array of three chars. A pointer to a function which receives an int pointer and returns a float pointer. A pointer to a function which receives nothing and returns nothing.

11]

Can you write a program which would implement the follwoing declaration. void (*f)(int, void (*)());

*********************************************************************** *********************** ANSWERS ***************************

***********************************************************************

1] A] B] C] D] f is a funciton returning pointer to an int. pf is a pointer to function which returns an int. argv is a pointer to a char pointer. f is an array of 10 function pointers, where each function receives two ints and returns nothing. which

E] scr is a far pointer to a char. ( far pointer is a pointer contains an address which lies outside the data segment). F] G] arr is an array of 10 character pointers.

a is an array of 5 function pointers. Each of these functions receive a far pointer to an int and returns an int. scr1 is a far pointer to a char, whereas scr2 is a near pointer to a char. ftable is an array of 4 function pointers which point to the functions fadd(), fsub() etc. Each of these functions accept nothing and return an int. ptr is a pointer to an array of 30 integers. ptr is an array of 30 pointers ot integers. cmp is a function returning pointer to void. cmp is a pointer to function which returns a void. f is a funciton returning pointer to array[] of pointer to function returning char. x is an array of 3 pointers to functions returning pointer to an array of 5 chars.

H]

I]

J] K] L] M] N]

O]

P]

f is a pointer to a funciton which returns nothing and receives as its parameter an integer and a pointer to a funciton which receives nothing and returns nothing. f is a pointer to a function which returns a pointer to an int pointer and receives two arguments: a pointer to an int pointer and a function pointer which points to a function which receives two pointers to int pointers an returns a pointer to an int pointer. f is a pointer to a function which returns nothing and receives two arguments, both function pointers: the first function pointer points to a function which returns nothing but receives two arguments - an int pointer and a pointer to a void pointer; the second function pointer points to a function which returns an int pointer an receives a pointer to a void pointer and an int pointer. ptr is a far pointer to a far pointer to a char, or in easier words, ptr contains a far address of a far pointer to a char. ptr is a near pointer to a far pointer to a char, or in easier words, ptr contains a near address of a far pointer to a char. ptr is a huge pointer to a far pointer to a char, or in easier words, ptr contains a huge address of a far pointer to a char.

Q]

R]

S]

T]

U]

2]

2 4 4

3]

2 4 4

4]

2 4 4

5]

4 4 2

6]

4 4 4

7]

2 2 2

8]

4 4 4

9]

No.

10]

char *ptr[3]; char *ptr[3]; char (*ptr)[3]; float *(*ptr)(int *); void( *ptr)();

11]

main() { void( *f)(int, void(*)()); void fun(int, void(*)()); void fun1(); void(*p)(); f = fun; p = fun1; (*f)(23,p); } void fun(int i, voud (*q)()) { printf("Hello"); } void fun1() { ; }

Chapter-5 Control Instructions

1]

What would be the output of the following program? main() { int i = 4; switch(i) { default: printf("\n a mouse is an elephant built by the japanese."); case 1: printf("\n Breeding rabbits is a hare raising experience."); case 2: printf("\n Friction is drag."); case3:

printf("\n If practice makes perfect, then nobody's perfect"); } }

2]

Point out the error, if any, in the for loop: main() { int i = 1; for( ; ; ) { printf("%d",i++); if (i > 10) break; } }

OPTIONS: (a) (b) (c) (d)

The condition in the for loop is a must. The two semicolons should be dropped. The for loop should be replaced by a while loop. No error.

3]

Point out to the error, if any, in the while loop: main() { int i = 1; while() { printf("%d",i++); if (i > 10) break; } }

OPTIONS: (a) (b) (c) (d)

The condition in the while loop is a must. Thereshould be a semicolons in the while loop. The while loop should be replaced by a for loop. No error.

4]

Point out the error, if any, in the while loop: main() { int i = 1; while(i <= 5) { printf("%d",i); if( i > 2) goto here; }

} fun() { here: printf("\n If it works, Don't fix it."); }

5]

Point out the error, if any, in the following program: main() { int i = 4, j = 2; switch(i) { case 1: printf("\n To err is human, to forgive is against company policy."); case j: printf("\n If you have nothing to do, don't do it here."); break; } }

6]

Point out the error, if any, in the following program: main() { int i = 1; switch(i) { case 1: printf("\n Radioactive cats have 18 half-lives."); break; case 1*2+4: printf("\n Bottle for rent-inquire within."); break; } }

7]

Point out the error, if any, in the following program: main() { int i = 10; switch(a) { } printf("Programmers never die. They just get lost in the processing."); }

8]

Point out the error,if any, in the following program: main() { int i = 1; switch(i) { printf("Hello"); case 1: printf("\n Individualists unite."); break; case 2: printf("\n Money is the root of all wealth."); break; } }

9]

Rewrite the following set of statements using conditional operators: int a = 1,b; if(a > 10) b = 20;

10]

Point out the error, if any, in the following program: main() { int a = 10, b; a >= 5? b = 100: b = 200; printf("\n %d",b); }

11]

What would be the output of the following program? main() { char str[] = "part-time musicians are semiconductors"; int a = 5; printf( a > 10 ? "%50s":"%s",str); }

OPTIONS: (a) (b) (c) (d)

Part-time musicians are semiconductors Part-time musicians are semiconductors Error None of the above

12]

What is more efficient a 'switch' statement or an 'if-else' chain?

13]

Can we use a 'switch' statement to switch on strings?

14]

We want to test whether a value lies in the range 2 to 4 or 5 to 7. Can we do this using a 'switch'?

15]

The way 'break' is used to take the control out of 'switch' can 'continue' be used to take the control to the beginning of the 'switch? <Yes / No>

************************

ANSWERS

***********************

1]

A mouse is an elephant built by the Japanese Breeding rabbits is a hare raising experience

2]

3]

4]

'goto' cannot take control to a different function.

5]

Constant expression required in the second case, we cannot use j.

6]

No error. Constant exprerssions like 1*2+4 are acceptable in cases of a 'switch'.

7]

Though never required, there can exist a 'switch which has no cases.

8]

Though there is no error, irrespective of the value of i the first 'printf()' can never get executed. In other words, all statements in a switch have to beling to some case or the other.

9]

int a = 1,b,dummy; a > 10 ? b = 20: dummy = 1;

Note that the following would not have worked: a > 10 ? b = 20: ; ;

10]

1value required in function 'amin()'. The second assignment should be written in parentheses as follows: a >= 5 ? b = 100: (b = 200);

11]

12]

As far as eficiency is concerned there would hardly be any difference if at all. If the cases in a 'switch' are sparsely distributed the compiler may internally use the equivalent of an 'if-else' chain instead of a compact jump table. However, one should use 'switch' where one can. It is definitely a cleaner way to program and certainly is not any less efficient than the 'if-else' chain.

13]

No. The cases in a 'switch' must either have integer constants or constant experssion.

14]

Yes, though in a way which would not be very pratical if the ranges are bigger. The vay is ahown below: switch(a) { case 2: case 3: case 4: /* statements */ case 5: case 6: case 7: /* some other statements */ break; }

15]

No. 'continue' can work only with loops and not with 'switch'.

Facts About Arrays


FACTS ABOUT ARRAYS:

1]

An array is a collection of similar elements. It is also known as a subscripted variable. Before using an array its type and size must be declared. For example int arr[30]; float a[60]; char ch[25]; The first element in the array is numbered as 0, so the last element is 1 less than the seze of the array. However big an array may be, its elements are always stored in contigouos locations.

2]

3]

4]

5] If we desire an array can be initilised at the same place where it is declared. For example, int num[6] = {2,3,12,5,45,5}; int n[] = {2,4,12,5,45,5}; float press[] = {12.3,34.2,-23.4,-11.3}; 6] If the array is initialised where it is declared, mentioning the dimension of the array is optional as in 2nd example above. 7] Till the array elements are not given any specific values, they are supposed to contain garbage values. 8] In 'C' there is no check to see if the subscript used for an array exceeds the size of the array. Data entered with a subscript exceeding the array size will simply be placed in memory outside the array; porbably on top of other data, or on the porgram itself. This will lead to unpredictable results, to say the least, and there will be no error message to warn you that you are going beyond the array size. In some cases the computer may just hang. Thus, the following program may turn out to be suicidal;: /* program */ main() { int num[40]; for(i = 0;i<= 100;i++) num[i] = i; } So do remember that, to see to it that we do not reach beyond the array size is entirely the programmer's botheraation and not the compiler's. While accessing array elements call by reference method is faster as compared to accessing elements by subscripts. However for convenience in programming we should observe the following : Array elements should be accessed using pointers, if the elements are to be accessed in a fixed order, say form beginning to end, or form end to beginning, or every alternate element or any such definite logic.

It would be easier to access the elements using a subscript if there is no fixed logic in accessing the elements. However, in this case also, accessing the elements by pointers would work faster than subscripts.

Chapter-6 Declarations and Initializations


WHAT WOULD BE THE OUTPUT OF THE FOLLOWING PROGRAMS:

1]

main() { char far *s1,*s2; printf("%d %d",sizeof(s1),sizeof(s2)); }

2]

int x = 40; main() { int x = 20; printf("\n %d",x); }

3]

main() { int x = 40; { int x = 20; printf("\n %d",x); } printf("\n %d",x); }

4]

IS THE FOLLOWING STATEMENT RIGHT? extern int i; main() { extern int i; i = 20; printf("%d",sizeof(i)); } (a) (b) 2 4

5]

(c) (d) 6]

Would vary form compiler to compiler Error, i undefined

Is it true that a global variable may have several declarations, but only one definition? [Yes / No]

7]

Is it true that a function may have several declarations, but only one definition? [Yes / No]

8]

In the following program where is the variable a getting defined and where is it getting declared? main() { extern int a; printf("%d",a); } int a = 20;

9]

main() { extern int a; printf("\n %d",a); } int a = 20; (a) (b) (c) (d) 20 0 Garbage value Error

10]

What's the difference between a defintion and declaration of a variable?

11] If the definition of an external variable occursin the source file before its use in a particular function, then there is no need for an extern declaration in the fuction. [True / False]

12] Suppose a program is divided into three files 'f1','f2' and 'f3' and varable is defined in the file 'f1' but used in the files 'f2' and 'f3'. In such a case would we need the external declaration for the variables in the files 'f2' and 'f3'. [Yes / No]

13] When we mention the prototype of a function are we defining the function or declaring it?

14]

What's the difference between the following declarations? (a) extern int fun();

(b)

int fun();

15] Why does the following program report a redecalration error of funtion display()? main() { display(); } void display() { printf("\n Cliffhanger"); }

16]

main() { extern int fun(float); int a; a = fun(3.14); printf("%d",a); } int fun(aa) float aa; { return((int)aa); } (a) (b) (c) (d) 3 3.14 0 Error

17]

Point out the error, if any, in the following program? struct emp { char name[20]; int age; } /* some more code may go here fun(int aa) { int bb; bb = aa * aa; return(bb); } main() { int a; a = fun(200; printf("\n %d",a);

*/

18] If you are to share the variables or fuctions across several source files how would you ensure that all definitions and declarations are consistent?

19]

How would you rectify the error in the following program/ f(struct emp) /* any other prototypes may go here struct emp { char name[20]; int age; }; main() { struct emp e = {"Soicher",34}; f(e); } f(struct emp ee) { printf("\n %s %d",ee.name, ee.age); }

*/

20] Global variables are available to all functions. Does there exist a mechanism by way of which K can make it available to some and not to others.

21]

What do you mean by a translation unit?

22]

What would be the output of the following program? main() { in a[5] = {2,3}; printf("\n %d %d %d",a[2],a[3],a[4]); } (a) (b) (c) (d) garbage values 2 3 3 3 2 2 0 0 0

23]

main() { struct emp {

char name[20]; int age; float sal; }; struct emp e = {"Tiger"}; printf("\n %d %f",e.age,e.sal); } (a) (b) (c) (d) 0 0.000000 Garbage values Error None of the above

24] some books suggest that the following definitions should be proceded by the word static. Is it correct? int a[] = {2,3,4,12,32}; struct emp e = {"sandy",23};

25]

Point out the error, if any, in the following program. main() { int(*p)() = fun; (*p)(); } fun() { printf("\n loud and clear"); }

26]

Print out the error, if any, in the following program. main() { union a { int i; char ch[2]; }; union a z = 512; printf("%d %d",z.ch[0],z.ch[1]); }

27] What do you mean by scope of a variable? what are the different types of scopes that a variable can have?

28]

What are the different types of linkages?

****************************

ANSWERS

******************************

1]

4 2

2]

20 Whenever there is a conflict between a local variable and a global variable, it is the local variable which gets a priority.

3]

20 40 In case of a conflict between local variables, the one which is more local that gets the priority.

4]

Declaration

5]

D "extern int i" is a declaration and not a definition, hence the error.

6]

Yes

7]

Yes

8]

"extern in a" is the declaration whereas "int a = 20" is the definition.

9]

10]

In the definition of a variable space is reserved for the variable and some initial value is given to it, whereas a declaration only identifies the type of the variable for a function. Thus definition is the place where the variable is created or assigned storage is allocated.

11]

True

12]

Yes

13]

We are declaring it. When the function alongwith the statements belonging to it are mentioned we are defining the function.

14]

There is no difference except for the fact that the first one gives a hint that the function "fun()" is probably in another source file.

15]

Here "display()" is called before it is defined. In such cases the compiler assumes that the function "display()" is declared as int display(); That is, an undeclared function is assumed to return an int and accept an unspecified number of arguements. Then when we define the function the compiler finds that it is returning void hence the compiler reports the discrepancy.

16]

The error occurs because we have mixed the ANSI prototype with K & R style of function definition. When we use ANSI prototype for a function and pass a float to the function it is promoted to a double. When the fuction accepts this double into a float a type mismatch occurs hence the error. The remedy for this error could be to define the functiona as: int fun(float aa) { .. .. .. }

17]

Because of the missing semicolon at the end of the structure declaration (the intervening comment further obscures it) the compiler believes that fun() would return something of the type struct emp, whereas in actuality it is attempting to return an int. This causes a mismatch, hence an error results.

18]

The best .c file. .h file) wherever

arrangement is to place each definiton in a relevant Then, put an external decalration in a header file ( and use "#include" to bring in the declaration needed.

The .c file which contains the definition should also include the header file, so that the compiler can check that compiler can check thta the definition matches the declaration.

19]

Declare the structure before the prototype of f().

20]

No. The only way this can be achieved is to define the variable locally in main() instead of defining it globally and then passing it to the functions which need it.

21]

A translatin unit is a set of source files seen by the compiler and translated as a unit: generally one .c file, plus all header files mentioned in "#include" directives.

22]

D. When an automatic array is partially initialised, the remaining array elements are initialised to 0.

23]

A. When an automatic structure is partially initialised, the remaining elements of the structure are initialised to 0.

24] Pre-ANSI C compilers had such a requirement. Compilers which conform to ANSI C standard do not have such a requirement.

25] Here we are initialising the function pointer p to the address of the function "fun()". But during this initialisation the function has not been defined. Hence an error. To eliminate this error add the prototype of the "fun()" before declaration of p, as shown below: extern int fun(); or simply int fun();

26]

In a pre-ANSI compiler a union variable cannot be initialised. However, ANSI C permits initialisation of first member of the union.

27]

Scope indicates the region over which the variable's declaration has an effect. The four kinds of scopes are: file, function, block and prototype.

28]

There are three different types of linkages: external, internal and none. External linkage means global, non-static variables and functions, internal linkages means static variables and functions with file scope, and no linkage means local variables.

Chapter-7 Expressions

1]

What would be the output of the following program? main() { static int a[20]; int i = 0; a[i] = i ++; printf("\n %d %d %d",a[0],a[1],i); }

2]

What would be the output of the following program? main(0 { int i = 3; i = i++; printf("%d",i); }

3]

The expression on the right hand side of && and || operators does not get evaluated if the left hand side determines the outcome? <True / False>

4]

What would be the output of the following program? main() { int i = 2; printf("\n %d %d",++i,++i); }

OPTIONS: (a) (b) (c) (d)

3 4 4 3 4 4 Output may vary from compiler to compiler.

5]

What would be the output of the following program? min(0 { int x = 10, y = 20,z = 5, i; i = x < y < z; printf("\n %d",i); }

OPTIONS: (a) (b) (c) (d)

1 0 Error None of the above.

6]

Are the following two statements true? a <= 20 ? b = 30 : c = 30; (a <= 20)? b: c = 30;

7]

Can you suggest any other way of writing the following expression such that 30 is used only once? a <= 20 ? b = 30 : c = 30;

8]

How come that the C standard says that the expression j = i++ * i++; is undefined, whereas, the expression j = i++ && i++; is perfectly legal.

9]

If 'a[i] = i++' is undefined, then by the same reason i = i + 1 should also be undefined. But it is not so. Why?

10]

Would the expression *p++ = c be disallowed by the compiler.

11]

In the following code in which order the funcitons would be called? a = f1(23,14) * f2(12/4) + f3();

OPTIONS: (a) (b) (c) (d)

f1,f2,f3 f3,f2,f1 The order may vary from compiler to compiler. None of the above.

12]

In the following code in which order the functions would be called? a = (f1(23,14) * f2(12/4)) + f3();

OPTIONS: (a) (b) (c) (d)

f1,f2,f3 f3,f2,f1 The order may vary from compiler to compiler. None of the above.

13]

What would be the output of the following program? main() { int i = -3, j = 2, k = 0, m;

m = ++i && ++j || ++k; printf("\n %d %d %d %d",i,j,k,m); }

14]

What would be the output of the following program?

main() { int i = -3, j = 2, k = 0, m; m = ++j && ++i || ++k; printf("\n %d %d %d %d",i,j,k,m); }

15]

What would be the output of the following program?

main() { int i = -3, j = 2, k = 0, m; m = ++i || ++j && ++k; printf("\n %d %d %d %d",i,j,k,m); }

16]

What would be the output of the following program?

main() { int i = -3, j = 2, k = 0, m; m = ++i && ++j && ++k; printf("\n %d %d %d %d",i,j,k,m); }

*********************************************************************** ************************** ANSWERS ***********************

***********************************************************************

1]

0 0 1 That's what some of the compilers would give. But some other compiler may give a different answer. The reason is, when a single expression causes the same object to be modified or to be modified and then inspected the behaviour is undefined.

2]

4. But basically the behaviour is undefined for the same reason as in (1) above.

3]

True. For example if 'a' is non-zero then 'b' will not be evaluated in the expression 'a || b'.

4]

D. The order of evaluation of the arguments to a function call is unspecified.

5]

A.

6]

No.

7]

*((a <= 20)? &b: &c) = 30;

8] According to the C standard an object's stored value can be modified only once (by evaluation of expression) between two sequence points. A sequence point occurs: at the end of full expression (expression which is not a sub-expression in a larger expression) at the &&, || and ?: operators at a fucntion call (after the evaluation of all arguments, just before the actual call) Since in the first expression 'i' is getting modified twice between two sequence points the expression is undefined. Also, the second expression is legal because a sequence point is occurring at && and 'i' is getting modified once before and once after this sequence point.

9]

i value.

The standard says that if an object is to get modified within an expression then all accesses to it within the same expression must be for computing the value to be stored in the object. The expression 'a[i] = i++' is disallowed because one of the accesses of 'i' ( the one in a[i]) has nothing to do with the value that ends up being stored in 'i'. In this case the compiler may not know whether the access should take place before or after the incremented value is stored. Since there's no good way to define it. the standard declares it as undefined. As against this the expression 'i = + 1' is allowed because 'i' is accessed to determine 'i's' final

10]

No.

Because here even though the value of p is accessed twice it is used to modify two different objects p and *p.

11]

C. Here the multiplication will happen before the addition, but in which order the functions would be called is undefined.

12]

C. Here the multiplication will happen before the addition, but in which order the functions would be called is undefined. In an arithmetic expression the parentheses tell the compiler which operators but do not force the compiler to evaluate everything within the parentheses first.

13]

-2 3 0 1

14]

-2 3 0 1

15]

-2 2 0 1

16]

-2 3 1 1

Chapter-8 Floating point Issues


1] WHAT WOULD THE OUTPUT OF THE FOLLOWING PROGRAM BE? main() { float a = 0.7; if ( a < 0.7) printf("C"); else printf("C++"); } OPTIONS: (a) (b) (c) (d)

C C++ Error None of the above

2]

WHAT WOULD THE OUTPUT OF THE FOLLOWING PROGRAM BE?

main() { float a = 0.7; if ( a < 0.7f) printf("C"); else printf("C++"); } OPTIONS: (a) (b) (c) (d)

C C++ Error None of the above

3]

WHAT WOULD THE OUTPUT OF THE FOLLOWING PROGRAM BE? main() { printf("%f",sqrt(36.0)); }

OPTIONS: (a) (b) (c) (d)

6.0 6 6.000000 Some absurd result

4]

Would this program give proper results? main() { printf("%f",log(36.0)); }

<Yes

No>

5] Would the following 'printf()' print the same values for any value of a? <Yes / No> main() { float a; scanf(%f",&a); printf("%f",a + a + a); printf("%f",3 * a); }

6] We want to round off c, a float, to an int value. The correct way to do so would be (a) (b) (c) (d) y y y y = = = = (int)(x + 0.5); int(x + 0.5); (int) x + 0.5; (int)((int)x + 0.5);

7] Which error are you likely to get when you run the following program? main() { struct emp { char name[20]; float sal; } struct emp e[10]; int i; for ( i = 0; i <= 9; i++) scanf("%s %f",e[i].name,&e[i].sal); } OPTIONS: (a) (b) (c) (d)

Suspicious pointer conversion Floating point formats not linked Cannot use 'scanf()' fpr structures Strings cannot be nested inside structures

8] What causes the error in problem 4.7 above to occur and how would you rectify the error in the above program?

9] Which are the three different types of real data types of real data types available in C and what are the format specifiers used for them?

10]

By default any real number is treated as (a) (b) (c) (d) a float a double a long double Depends upon the memory model that you are using.

11]

What should you do to treat the constant 3.14 as a 'float'?

12]

What would be the output of the following program? main() { printf("%d %d %d",sizeof(3.14f),sizeof(3.14)); }

OPTIONS: (a) (b) (c) (d)

4 4 4 4 Garbage value Garbage value 4 8 10 Error

14]

The binary equivalent of 5.375 is (a) (b) (c) (d) 101.101110111 101.011 101011 None of the above

15]

How 'floats' are stored in binary form?

16] A float occupies 4 bytes. If the hexadecimal equivalent of each of these bytes is A,B,C and D, then when this float is stored in memory these bytes get stored in the order (a) (b) (c) (d) ABCD DCBA 0xABCD 0xDCBA

17] If the binary equibalent of 5.375 in normalised form in 0100 0000 1010 1100 0000 0000 0000 0000, what would be the output of the following program? main() { float a = 5.375; char *p; int i; p = (char*) &a; for(i = 0;i <= 3; i++) printf("%02x",(unsigned char)p[i]); } OPTIONS: (a) (b) (c) (d)

40 04 00 00

AC CA 00 00

00 00 AC CA

00 00 40 04

*********************************************************************** ********************* ANSWERS ***********************

***********************************************************************

1]

2]

3]

4]

No, since we have not included the header file "math.h".

5] No. For example, for 1.7 the two 'printf()s' would print different values. 6] A

7]

8]

What causes the 'floating point formats not linked' error to occur? When the compiler encounters a reference to the address of a float it sets a flag to have the linder link in the floationg point emulator. A floating point emulator is used to manipulate floating point numbers in runtime library functions like 'scanf()' and 'atof()'. There are some cases in which the reference to the folat is a bit obscure and the compiler does not detect the need for the emulator. These situations usually occur during the initial stages of program development. Normally, once the program is fully developed, the emulator will be used in such a fashion that the compiler can accurately determine when to link in the emulator. To force linking of the floating point emulator into an application just include the following function in your progaram: void LinkFloat(void) { float a = 0, *b = &a; /* cause emulator to be linked */ a = *b; } There is no need to call this funciton form your program.

9]

float 4 bytes double 8 bytes long double 10 bytes %Lf

%f %lf

10]

11]

Use 3.14f

12]

Use 3.141

13]

14]

15]

Floating-point numbers are represented in IEEE format. The iEEE format for floating point storage uses a sign bit, a mantissa and an exponent for representing the power of 2. The sign bitdenotes the sign of the number: a ) represents a positive value and a 1 denotes a negative value. The mantissa is represented in binary after converting it to its normalised from. The normalised form results in a manissa whose most significant digit is always 1. The IEEE format takes advantage of this by not storing this bit at all. The exponent is an integer stored in unsigned binary format after adding a positive integer bias. This ensures that the stored exponent is always positive.. The value of the bias is 127 for floats and 1023 for doubles.

16]

17]

Chapter-9 Functions
1] What would be the output of the following program? main() { int a,b; a = sumdig(123); b = sumdig(123); printf(" %d %d",a,b); } sumdig(int n) { static int s = 0; int d; if( n != 0) { d = n % 10; n = (n - d) / 10; s = s + d; sumdig(n); }

else return(s); }

2]

What error would the following function give on compilation? f(int a, int b) { int a; a = 20; return a; }

OPTIONS: (a) (b) (c) (d)

Missing parenthesis in return statement. The function should be defined as 'int f(int a,int b)'. Redeclaration of 'a'. None of the above.

3]

There is a mistake in the following code. Add a statement in it to remove it. main() { int a; a = f(10,3.14); printf("%d",a); } f(int aa, float bb) { return ((float) aa + bb); }

4]

Point out the error in the following code. main() { int a = 10; void f(); a = f(); printf("\n %d",a); } void f() { printf("Hi"); }

5]

Point out the error, if any, in the following function. main() {

int b; b = f(20); printf(" %d",b); } int f(int a) { a>20? return(10): return(20); }

6]

A function cannot be defined inside another function. <True / False>

7]

Will the following functions work? f1(int a,int b) { return(f2(20)); } f2(int a) { return(a * a); }

<Yes

/ No>

8]

What are the following two notations of defining functions commonly known as: int f(int a, float b) { /* some code */ } int f(a,b) int a; float b; { /* some code */ }

9]

In a function two return statements should never occur. <True / False>

10]

In a function two return statements should never occur successively. < True / False>

11]

In C all functions except 'main()' can be called recursively. < True / False>

12]

Usually recursion works slower than loops. < True /

False>

13] Is it true that too many recursive calls may result int stack overflow? <Yes / No>

14]

How many times the following program would print 'Jamboree'? mani() { printf)"\n Jamboree"); main(); }

OPTIONS: (a) (b) (c) (d)

Infinite number of times 32767 times 65535 times Till the stack doesn't overflow.

*********************************************************************** ************************ ANSWERS ***********************

***********************************************************************

1]

6 12

2]

3]

Add the following function prototypw in amin(): float f(int, float);

4]

In spite of defining the function 'f()' as returning 'void', the program is trying to colect the value returned by 'f()' in the variable 'a'.

5] 'return' statement cannot be used as shown withe the conditional operators. Instead the following statement may be used:

return(a > 20 ? 10: 20);

5]

True.

7]

Yes.

8]

The first one is known as ANSI notation and the second is known as Kernighan and Ritchie or simply, K & R notation.

9]

False.

10]

True.

11]

False. Any function including 'main()' can be called

recursively.

12]

True.

13]

Yes.

14]

D.

12]

Chapter-10 Inputs and Outputs


*********************************************************************** *********************** INPUT AND OUTPUT **************************

***********************************************************************

1]

What would be the output of the following program ? main() { int a = 250; printf("%1d",a);

2]

What would be the output of the following program ? main() { float a = 3.15529; printf("\n %6.2f",a); printf("\n %6.3f",a); printf("\n %5.4f",a); printf("\n %2.1f",a); printf("\n %0.0f",a); }

3]

In the following code #include <stdio.h> main() { FILE *fp; fp = fopen("trial","r"); } 'fp' points to (a) The first character in the file. (b) A structure which contains a 'char' pointer which points to the first character in the file. (c) The name of the file. (d) None of the above.

4]

Point out the error, if any, in the following program: main() { unsigned char; FILE *fp; fp = fopen((ch = getc(fp)) != EOF) printf("%c",ch); fclose(fp); }

5]

Point out the error , if any, in the following program: #include "stdio.h" main() { unsigned char; FILE *fp; fp = fopen("trial","r"); if (!fp) { printf("Unable to open file."); exit();

} fclose(fp); }

6]

If a file contains the line " I am a boy\r\n" then on reading this line into the array 'str' using 'fgets()' what would 'str' contain ? (a) (b) (c) (d) "I "I "I "I am am am am a a a a boy\r\n\0" boy\r\0" boy\n\0" boy"

7]

Point ou the error if any in the following progarm : #include "stdio.h" main() { FILE *fp; fp = fopen("trial","r"); fseek(fp,20,SEEK_SET); fclose(fp); }

8]

To print out a and b below, which printf() statement would you use ? float a = 3.14; double b = 3.14; (a) (b) (c) (d) printf("%f %f",a,b); printf("%Lf %f",a,b); printf("%Lf Lf",a,b); printf("%f %Lf",a,b);

9]

To scan a and b fiven below which 'scanf()' statement would you use ? float a; double b; (a) (b) (c) (d) scanf("%f %f",&a,&b); scanf("%Lf %Lf",&a,&b); scanf("%f %Lf",&a,&b); scanf("%f %lf",&a,&b);

10]

Point out the wrror in the following program. # include<stdio.h> main() {

FILE *fp; char str[80]; fp = fopen("trial","r"); while(!feof(fp)) { fgets(str,80,fp); puts(str); } fclose(fp); }

11]

Point out the error in the following program. #include"stdio.h" main() { char ch; int i; scanf("%c",&i); scanf("%d",&ch); printf("%c %d",ch,i); }

12]

What would be the output of the following program ? main() { printf("\n % % % %"); }

13]

Point out the error, if any, in the following program? #include"stdio.h" main() { FILE *fp; fp = fopen("c:\tc\trial","w"); if(!fp) exit(); fclose(fp); }

14]

Would the following code work? If yes, what would be the output? main() { int n = 5; printf("\nn = %*d",n,n); }

<Yes, No>

15]

What is the * in the printf() of (14) indicative of?

16]

Can we specify variable field width in a scanf() format string? <Yes , No>

17]

To tackle a double in printf() we can use %f, Whereas in scanf() we should use %lf. <Yes , No>

18]

Out of fgets() and gets() which function is safe to use?

19]

A file writtern in text mode canf be read back in binary mode. <True , False>

20]

We should not read after a write to a file without an intervening call to fflush(),fseek() or rewind(). <True / False>

*********************************************************************** *************************** ANSWERS *******************************

*********************************************************************** 1] 250

2]

3.16 3.155 3.1553 3.2 3

3]

4]

EOF has been defined as #define EOF -1 in the file "stdio.h" and an usingned char ranges from 0 to 255 hence when EOF is read from the file it cannot be accommodated in ch. Solution is to declare ch as an int.

5]

No error.

6]

7]

Instead of 20 use 20L since fseek() needs a long offset value.

8]

A. It is possible to print a souble using %f.

9]

10]

The last line from the file "trial" would be read twice. To avoid this use: while(fgets(str,80,fp) != NULL) puts(str);

11]

You would not get a chance to supply a character for the second scanf() statement. Solution is to precede the second scanf() with the following statement. fflush(stdin); This would flush out the enter hit for the previous scanf() to be flushed out from the input stream, i.e. keyboard.

12]

%%

13]

The path of the filename should have been written as "c:\\tc\\trial".

14]

Yes. n = 5

15]

It indicates that an 'int' value from the argument list will be used for fiedld width. In the argument list the width precedes the value to be printed. In this case the format specifier becomes %5d.

16]

No. A '*' in scanf() format string after a % sign is used for suppression of assignment. That is, the current input field is scanned but not stored.

17]

True.

18]

'fgets()', because unlike 'fgets()', gets() cannot be told the size of the buffer into which the string supplied would be

stored. As a result there is always a possibility of overflow of buffer.

19]

False.

20]

True.

Chapter11 Library Functions


*********************************************************************** ***************** LIBRARY FUNCTIONS ******************

***********************************************************************

1]

What do the functions atoi(), atoa() and gcvt() do? Show how would you use them in a program.

2]

Does there exist any other function which can be used to convert an integer or a float to a string? If yes, show how you would use it.

3]

How would you use qsort() function to sort an array of structures?

4]

How would you use qsort() function to sort the names stored in an array of pointers to strings?

5]

How would you use bsearch() function to search a name stored in an array of pointers to strings?

6]

How would you use the function sin(), pow(), sqrt()?

7]

How would you use the function memcpy()?

8]

How would you use the function memset()?

9]

How would you use the function memmove()?

10]

How would you use the functions fseek(), fread(), fwrite() and ftell()?

11]

How would you obtain the current time and difference between two times?

12]

How would you use the function randomize() and random()?

13]

Would the following program always output 'Bangalore'? main() { char str1[] = "Bangalore - 440010"; char str2[10]; strncpy(str2,str1,8); printf("\n %s",str2); }

14]

Can you shorten this code? main() { char str1[] = "Bangalore - 440010"; char str2[10]; str2[0] = '\0'; strncat(str2,str1,8); printf("%s",str2); }

15]

How would you implement a substr() function that extracts a substring from a given string?

16] Given a sentence containing words separated by spaces how would you construct an array of pointers to strings containing addresses of each word in the sentance?

17] Write the comparison function qs_compare()for the following code struct date { int d,m,y; }; qs_compare(const void*,const void*);

main() { struct date dd[]={ {17,11,62}, {24,8,78}, {17,11,62}, {16,12,76}, {19,2,94} }; inti,w; clrscr (); w=sizeof(struct date); qsort(dd,5,w,qs_compare);

for(i=0;i<4;i++) printf("\n%d%d%d",dd[i].dd[i].m,dd[i].y); }

18]

How should we sort a linked list?

19] What's the difference between the functions rand(),random(),srand() and randomise()?

20] What's the difference between the funtion memmove() and memcpy()?

21]

How

would you print a string on the printer?

22] screen?

Can you use the funtion fprintf()to display the output on the

*********************************************************************** ********************** ANSWERS ***********************

***********************************************************************

1]

atoi() converts a string to an integer. itoa() converts an integer to a string. gcvt() converts a floating-point number to a string.

# include"stdlib.h" main() { char s[] = "12345"; char buffer[15],string[20]; int i; i = atoi(s); printf("\n %d",i); gcvt(20.141672,4,buffer); printf("\n %s",buffer); itoa(15,string,2); printf("\n %s",string); }

2]

The function sprintf() can be used for this purpose. This function also has the ability to format the numbers as they are converted to strings. The following program shows how to use this function. # include"stdio.h" main() { int a = 25; float b = 3.14; char str[40]; sprintf(str,"a = %d b = %f",a,b); puts(str); }

3]

# include"string.h" # inlucde"stdlib.h" struct stud { int rollno; int marks; char name[30]; }; int sort_m(struct stud *,struct stud *);

int sort_name(struct stud *,struct stud *); int sort_marks(struct stud *,struct stud *); main() { statis struct stud ss[] = { {15,96,"Akshay"}; {2,97,"Madhuri"}; {8,85,Aishvarya"}; {10,80,"Sushmita"}; }; int x,w; clrscr(); w = sizeof(struct stud); printf("\n In order of roll numbers:"); qsort(ss,4,w,sort_m); for(x = 0; x < 4; x++) printf("\n %d %s %d",ss[x].rollno,ss[x].name,ss[x].marks); printf("\n\n In order of names:"); qsort(ss,4,w,sort_name); for(x = 0; x < 4; x++) printf("\n %d %s %d",ss[x].rollno,ss[x].name,ss[x].marks); printf("\n\n In order of marks:"); qsort(ss,4,w,sort_marks); for(x = 0; x < 4; x++) printf("\n %d %s %d",ss[x].rollno,ss[x].name,ss[x].marks); }

int sort_m(struct stud *t1,struct stud *t2) { return(t1->rollno - t2->rollno); } int sort_name(struct stud *t1,struct stud *t2) { return(strcmp(t1->name - t2->name)); } int sort_marks(struct stud *t1,struct stud *t2) { return(t1->marks - t2->marks); }

4]

# include"string.h" # include"stdlib.h" int sort_name(const void * ,const void * );

main() { char *names[] = { "Akshay"; "Madhuri"; "Aishvarya"; "Sushmita"; "Sudeepta"; }; int i; qsort(names,5,sizeof(char *), sort_name); for(i = 0; i < 5; i++) printf("\n %s",names[i]); } int sort_name(const void *t1, const void *t2) { /* t1 and t2 are always pointers to objects being compared */ char **t11, **t22; /* cast appropriately */ t11 = (char **)t1; t22 = (char **)t2; return(strcmp(*t11,*t22)); }

5]

# include"string.h" # include"stdlib.h" int sort_name(const void *, const void *); int bs_compare(char **,char **); main() { char *names[] = { "Akshay"; "Madhuri"; "Aishvarya"; "Sushmita"; "Sudeepta"; }; int i,wide,nel; char *s = "aMadhuri", **b; qsort(names,5,sizeof(char *),sort_name); clrscr(); for(i = 0; i < 5; i++) printf("\n %s",names[i]); wide = sizeof(names[0]); nel = sizeof(names) / wide; b = bsearch(&s, names, nel, wide, bs_compare);

if(b == NULL) printf("Not found"); else pritf("\n\n %s",*b); }

int sort_name(const void *t1, const void *t2) { /* t1 and t2 are always pointers to objects being compared */ char **t11, **t22; /* cast appropriately */ t11 = (char **)t1; t22 = (char **)t2; return(strcmp(*t11,*t22)); } int bs_compare(char **s1,char **s2) { return(strcmp(*s1, *s2)); }

6]

# include"math.h" main() { int ang; float angrad,x,y,a,b; printf("\nEnter the angle in degrees"); scanf("%d",&and); angrad = ang * 3.14/ 180; c = sin(angrad); a = pow(x,2); b = 1 - a; y = sqrt(b); printf("\n cosine of angle %d is: %d",ang,y); }

7]

# include"math.h" # include"alloc.h" main() { int area; char scr[]="Pray, not for lighter load, but for stronger back"; char *dest; area = sizeof(src); dest = malloc(area); mamcpy(dest,src,area);

printf("\n %s",src); printf("\n %s",dest); }

8]

# include"mem.h" main() { int area; char src[] = "Bon jour, Madam"; area = sizeof(src); memset(src,"!",area - 7); printf("\n %s",src); }

9]

# include"mem.h" # include"alloc.h" main() { int area; char *dest; char src[] ="Life is the camera and you are the target" "so keep smiling always"; area = sizeof(Src); dest = malloc(Area); memmove(dest,src,area); printf("\n %s",dest); printf("\n %s",src); }

10]

# include"stdio.h" struct stud { int rollno; char name[10]; float per; }e; FILE *fs; main() { long position = OL; int rollno; char ch; float temp; fs = fopen("stud.dat","rb+");

if(fs == NULL) { puts("Unable to open file"); exit(1); } do { printf("\n Enter code no. to modify:"); scanf("%d",&rollno); while(fread(&e,sizeof(e),1,fs) == 1) { if(e.rollno == rollno) { printf("\n Enter the new record"); dcanf("%s %f",e.name, &temp); e.per temp; fseek(fs,position, SEEK_SET); fwrite(&e,sizeof(e),1,fs); break; } position = ftell(fs); } puts("You want to modify records"); ch = getche(); }while(ch == 'Y'); }

11]

# include"time.h" # include"dos.h" main() { time_t t1,t2; double diff,f; int i = 2; time(&t1); sleep(i); time(&t2); diff = difftime(t2,t1); printf("\n Program was active for %lf seconds",diff); }

12]

# include"dos.h" # inlcude"stdlib.h" main() { randomize();

printf("\n Press any key to stop."); while!kbhit()) { sound(random(500)); delay(random(100)); nosound(); } }

13]

No. Because after copying the source string into the target string strncpy() doesn't terminate the target string with a '\0'. A better way of copying would be: str[2] = '\0'; strncat(str2,str1,8); strncat() always terminates the target string with a '\0'.

14]

Yes, using sprintf() as shown below: main() { char str1[] = "Bangalore-440010"; char str2[10]; sprintf(str2,"%.*s",8,str1); printf("%s",str2); }

15]

main() { char str1[] = "Bangalore"; char str2[5]; /* Extract 3 characters beginning with first character */ sprintf(str2,str1,1,3); printf("%s",str2); } substr(char *t,char *s,int pos,int len) { t[0] = '\0'; strncat(t,s + pos,len); }

16]

# include"stdio.h" # include"string.h" main() { char str[] = "This is a test"; char *ptr; char *p; int i = 1,j;

p = strtok(str," "); if(p != NULL) { [tr[0] = p; while(1) { p = strtok(NULL," "); if(p == NULL) break; else { ptr[i] = p; i++; } } } for(j = 0; j < i; j++) printf("\n %s",ptr[j]); }

17]

int qs_compare(const void *p1,const void *p2) { const struct date *sp1 = p1; const struct date *sp2 = p2; if(sp1->y < sp2->y) return(-1); else if(sp1->y > sp2->y) return(1); else if(sp1->m < sp2->m) return(-1); else if(sp1->m > sp2->m) return(1); else if(sp1->d < sp2->d) return(-1); else if(sp1->d > sp2->d) return(1); else return(0); }

18]

Often it's easier to keep the list in order as we build it rather than sorting it later. Still if we want to sort the list then we can allocate a temporary array of pointers, fill it with pointers to the various nodes in the list, call qsort() and finally rebuild the list pointers based on the sorted array.

19]

rand() random() srand()

: returns a random number. : retruns a random number in a specified range. : initialses a random number generator with a given seed value.

randomize : initialises a random number genenrator with a random value based on time.

20]

Both the functions copy a block of bytes from source to destination. However, if source and destination overlaps the behaviour of memcpy() is undefined whereas memmove() carries out the copying correctly. memcpy() is more efficient, whereas memmove() is safer to use.

21]

# include"stdio.h" main() { char str[] = "There wouldn't have been COBOL without C"; fprintf(stdprn,"\n %s \n",str); }

22]

Yes, by replacing the usual file pointer with stdout as shown below: fprintf(stdout,"%s %d %f",str,i,a);

Chapter-12 Memory Allocation


*********************************************************************** ************* MEMORY ALLOCATION ******************

***********************************************************************

1]

What would be the output of the follwoing program? main() { char *s; char *fun();

s =s fun(); printf("%s",s); } char *fun() { char buffer[30];

strcpy(buffer,"RAM - Rarely Adequate Memory"); return(buffer); }

2]

What is the solution for the problem in program 17.1 above?

3]

Does there exist any other solution for the problem 17.1?

4]

How would you dynamically allocate a 1-D array of integers?

5]

How would you dynamically allocate a 2-D array of integers?

6]

How would you dynamically allocate a 2-D array of integers such that we are able to access any element using 2 subscripts, as in arr[i][j]?

7]

How would you dynamically allocate a 2-D array of integers such that we are able to access any element using 2 subscripts, as in arr[i][j]? Also the rows of the array should be stored in adjacent memory locations.

8]

How many bytes would be allocated by the following code? #include "alloc.h" #define MAXROW 3 #define MAXCOL 4 main() { int(*p)[MAXCOL]; p = (int(*)[MAXCOL]malloc(MAXROW * sizeof(*p)); }

9]

What would be the output of the following program? #include"alloc.h" #define MAXROW 3 #define MAXCOL 4 main() { int(*p)[MAXCOL]; p = (int(*)[MAXCOL])malloc(MAXROW * sizeof(*p)); printf("%d %d",sizeof(p),sizeof(*p)); }

10]

In the following code p is a pointer to an array of MAXCOL elements. Also, malloc() allocates memory for MAXROW such

arrays. Would these arrays be stored in adjacent locations? How would you access the elements of these array using p? #define MAXROW 3 #define MAXCOL 4 main() { int i,j; int (*p)[MAXCOL]; p = (int(*)[MAXCOL])malloc(MAXROW * sizeof (*p)); }

11]

How many bytes would be allocated by the following code? #include "alloc.h" #define MAXROW 3 #define MAXCOL 4 main() { int(*p)[MAXCOL][MAXROW]; [ = (int(*)[MAXCOL])malloc(sizeof(*p)); }

12]

How would you dynamically allocate a 3-D array of integers?

14]

How many bytes of memory would the following code reserve? #include "alloc.h" main() { int *p; p = (int *)malloc(256 * 256); if(p == NULL) printf("Allocation failed"); }

14]

How would you free the memory allocated by the follwoing program? #include"alloc.h" #define MAXROW 3 #define MAXCOL 4 main() { int **p,i; p = (int **)malloc(MAXROW * sizeof(int *)); for(i = 0; i < MAXROW; i++) p[i] = (int *)malloc(MAXCOL * sizeof(int)); }

15]

How would you free the memory allocated by the following program? #include"alloc.h" #define MAXROW 3 #define MAXCOL 4 main() { int **p,i,j; p = (int **)malloc(MAXROW * sizeof(int*)); p[0] = (int *)malloc(MAXROW * MAXCOL * sizeof(int)); for(i = 0; i < MAXROWl i++) p[i] = p[0] + MAXCOL; }

16]

Would the following code work at all times? main() { char *ptr; gets(ptr); printf("%s",ptr); }

17]

The following code is improper though it may work some times. How would you improve it? main() { char *s1 = "Cyber"; char *s2 = "Punk"; strcat(s1,s2); printf("%s",s1); }

18]

What ould be the output of the second printf() in the following program? #include "alloc.h" main() { int *p; p = (int*)malloc(20); printf("%u",p); /* Suoopse this prints 1314 */ free(p); printf("%u",p); }

19]

Something is logically wrong with this program. Can you point it out?

#include "alloc.h" main() { struct ex { int i; float j; char *s; } struct ex *p; p = (struct*) malloc(sizeof(struct ex)); p -> (char *) malloc(20); free(p); }

20]

To free() we only pass the pointer to the block of memory which we want to deallocate. Then how does free() know how many bytes it should deallocate?

21]

What would be the output of the following program? main() { char *ptr; *ptr = (char*) maolloc(30); strcpy(ptr,"RAM- Rarely Adequate Memory"); printf("\n %s",ptr); free(ptr); }

*********************************************************************** ****************** ANSWERS ***********************

***********************************************************************

1]

The output is unpredictable since buffer is an auto array and would die when the control goes back to main(). Thus s would be pointing to an array which no longer exists.

2]

main() { char *s; char *fun(); s = fun(); printf("%s",s); } char *fun() { static char bufer[30]; static(buffer,"RAM - Rarely Adequate Memory"); return(bufer); }

3]

#include "alloc.h" main() { char *s; char *fun(); s = fun(); printf("%s",s); free(s); } char *fun() { char *ptr; ptr = (char *)malloc(30); strcpy(ptr,"RAM - Rarely Adequate Memory"); return(ptr); }

4]

#include "alloc.h" #define MAX 10 main() { int *p,i; p = (int *)malloc(MAX * sizeof(int)); for(i = 0;i < MAX; i++) { p[i] = i; printf("%d",p[i]); } }

5]

#include "alloc.h" #define MAXROW 3 #define MAXCOL 4 main()

{ int *p,i,j; p = (int *)malloc(MAXROW * MAXCOL * sizeof(int)); for(i = 0; i < MAXROW; i++) { for(j = 0; j < MAXCOL; j++) { p[i * MAXCOL + j] = i; plrintf("%d",p[i * MAXCOL + j]); } printf("/n"); } }

6]

#include "alloc.h" #define MAXROW 3 #define MAXCOL 4 main() { int **p,i,j; p = (int **)malloc(MAXROW * sizeof(int)); for(i = 0; i < MAXROW; i++) p[i] = (int *)malloc(MAXCOL * sizeof(int)); for(i = 0; i < MAXROW; i++) { for(j = 0; j < MAXCOL; j++) { p[i][j] = i; printf("%d",p[i][j]); } printf("/n"); } }

7]

#include "alloc.h" #define MAXROW 3 #define MAXCOL 4 main() { int **p,i,j; p = (int **)malloc(MAXROW * sizeof(int)); p[0] = (int *)malloc(MAXROW * MAXCOL * sizeof(int)); for(i = 0; i < MAXROW; i++) p[i] = p[0] + i * MAXCOL; for(i = 0; i < MAXROW; i++) { for(j = 0; j < MAXCOL; j++) { p[i][j] = i; printf("%d",p[i][j]); } printf("/n"); }

8]

14 bytes

9]

10]

The arrays are stored in adjacent locations. You can confirm this by printing their addresses using the following loop. int i; for(i = 0; i < MAXROW; i++) lprintf("%d",p[i]); To access the array elements we can use the following set of loops. for(i = 0; i < MAXROW; i++) { for(j = 0; j < MAXCOL; j++) printf("%d",p[i][j]); }

11]

14 bytes

12]

#include "alloc.h" #define MAXY 3 #define MAXY 4 #define MAXZ 5 main() { int ***p,i,j,k; p = (int ***)malloc(MAXX * sizeof(int**)); for(i = 0; i< MAXX; i++) { p[i] = (int **)malloc(MAXY * sizeof(int *)); for(j = 0; j < MAXY; j++) p[i][j] = (int *)malloc(MAXZ * sizeof(int)); } for(k = 0; k < MAXZ; k++) { for(i = 0; i < MAXX; i++) { for(j = 0; j < MAXY; j++) { p[i][j][k] = i + j + k; lprintf("%d",p[i][j][k]); } printf("/n"); } printf("/n"); }

13]

It would fail to allocate any memory because 256 * 256 id 65536 which when passed to malloc() would become a negative number since the formal argument of malloc(), an unsigned int, can accomodate numbers only upto 65535.

14]

for(i = 0; i < MAXROW; i++) free(p[i]); free(p);

15]

free(p[0]); free(p);

16]

No. Since ptr is an uninitialised pointer it must be pointing at some unknown location in memory. The string that we type in would get stored at the location to which ptr is pointing thereby overwriting whatever is present at that location.

17]

main() { char s1[25] = "Cyber"; char *s2 = "Punk"; strcat(s1,s2); printf("%s",s1); }

18]

1314

19]

The memory chunk at which 's' is pointing has not been freed. Just freeing the memory pointed to by the struct pointer p is not enough. Ideally we should have used: free(p->s); free(p); In short when we allocate structures containing pointers to other dynamically allocated objects before freeing the structure we have to first free each pointer in the structure.

20]

In most implimentations of malloc() the number o fbytes allocted is stored adjacent to the allocated block. Hence it is simple for free() to know how many bytes ato deallocate.

21]

22]

No.

23]

Yes, using the realloc() function as shown below: #include "alloc.h" main() { int *p; p = (int *)malloc(20); t = p; t = (int *)realloc(p,40); if(t == NULL) { printf("Cannot reallocate, leaves previous"); printf("region unchanged."); } else { if(p == t) ; /* the array expanded at the same region */ else { free(p); /* deallocate the original array */ p = t; /* ste p to newly allocated region */ } } }

24]

Both. If the first strategy fails then it adopts the second. If the first is successful it returns the same pointer that you passed to it otherwise a different pointer for the newly allocated space.

25]

If realloc() expands allocated memory at the same place then there is no need of readjustment of other pointers. However. if it allocates a new region somewhere else the programmer has to readjust the other pointers.

26]

As against malloc(), calloc() needs two arguments, the number of elements to be allocted and othe size of each element. For example, p = (int *)calloc(10,sizeof(int)); would allocate space for a 10 integer array. Additionally, calloc() would also set each of this element with a value 0.

27]

The same that we use with mallloc(), i.e. free().

28]

True.

29]

64 KB.

30]

Use the standard library functions farmalloc() and farfree(). These functions are specific to DOS.

31]

Yes. Using interrupt 0x67, the details of which are beyond the scope of this book.

32]

While assigning the address returned by malloc() we should use ptr and not *ptr.

Chapter-13 Pointers
*********************************************************************** *********************** POINTERS ***********************

***********************************************************************

1]

Can you combine the following two statements into one? char *p; p = malloc(100);

2]

Can you split the following statement into two statements? char far *scr = (char far *) 0xB8000000L;

3]

Are the expressions '*ptr++' and '++*ptr' same?

4]

Can you write another expression which does the same job as '++*ptr' ?

5]

What would be the equivalent pointer expression for referring the same element as 'a[i] [j] [k] [l]'?

6]

What would be the ouptut of the following program? main()

{ int arr[] = { 12,13,14,15,16}; printf("\n d%d%d" sizeof(arr), sizeof(*arr), sizeof(arr[0])));

7]

What would be the output of the following program assuming that the array begins at location 1002? main() { int a[3][4] = { 1,2,3,4, 5,6,7,8, 9,10,11,12 }; printf("\n %u %u %u",a[0]+1, *(a[0]+1), *(*(a+0)+1));

8]

What would be the output of the followingt program assuming that the array begins at location 1002? main() { int a[2][3][4] = { { 1,2,3,4, 5,6,7,8, 9,1,1,2 }, { 2,1,4,7, 6,7,8,9, 0,0,0,0 } }; printf('\n %u %u %u %d",a,*a,**a,***a); }

9]

In the following program how would you proint 50 using 'p'? main() { int a[] = { 10,20,30,40,50}; char *p; p = (char *)a; };

10]

Where can one think of using pointers?

11]

In the following program add a statement in the function 'fun()' such that address of a gets a stored in j. main()

{ int *j; void fun(int**); fun(&j); } void fun(int**k) { int a = 10; /* add statement here */ }

12]

Would the following program give a compilation error or warning? <Yes / No> min() { float i = 10, *j; void *k; k = &i; j = k; printf("\n %f",*j); }

13]

Would the following program compile? main() { int a = 10, *j; void *k; j = k = &a; j++; k++; printf("\n %u %u",j,k); }

14]

Would the following code compile successfully? main() { printf("%c",7["Sundaram"]); }

*********************************************************************** *************************** ANSWERS *******************************

***********************************************************************

1]

char *p = malloc(100);

2]

char far *scr; scr = (char far *) 0xB8000000L;

3]

No. '*ptr++' increments the pointer and not the value pointed by it,whereas '++*ptr' increments the value being pointed by 'ptr'.

4]

(*ptr)++

5]

*(*(*(*(a + i) + j) + k) + l)

6]

10

7]

1004

8]

1002

1002

1002

9]

printf("\n %d",*((int *)p + 4));

10]

At lot of places, some of which are: (a) Accreeing array or string elements. (b) Dynamic memory allocation. (c) Call by reference (d) Implementing linked lists, trees, graphs and many other data structures.

11]

*k = &a;

12]

float(*arr[3])(int,int);

13] No. Here no typecasting is required while assigning the value to and form k because conversions are applied automatically when other pointer types are assigned to and from void* .

14]

No. An error would be reported in the statement 'k++' since arithmetic on void pointers is not permitted unless the void pointer is appropriately typecasted.

15]

Yes.

It would print 'm' of 'Sundaram'.

Chapter-14 More about pointers


*********************************************************************** **************** MORE ABOUT POINTERS ***********************

***********************************************************************

1]

Is the NULL pointer same as an uninitialiseed pointer? <Yes / No>

2]

In which header file is the NULL macro defined.

3]

Why is it that for large memeory models NULL has been difined as '0L' and for small memory models as just 0?

4]

What is a NULL pointer?

5]

What's the difference between a null pointer, a NULL macre, the ASCII NUL character and 'null string'?

6]

What would be the output of the following program? #include "stdio.h" main() { int a,b = 5; a = b + NULL; printf("%d",a);

7]

Is the programming style adopted in 8.6 good?

8]

What would be the output of the following program? #include "stdio.h" main() { printf("%d %d",sizeof(NULL),sizeof("")); }

9]

How many bytes are occupied by near, far and huge pointers ?

10]

What does the error "Null Pointer Assignment" mean and what causes this error ?

11]

How do we debug a Null Pointer Assignment error ?

12]

Can anything else generate a Null Pointer Assignment error ?

13]

Are the three declarations char **apple, char *orange[], and char cherry[][] same ? <Yes / No>

14]

Can two different near pointers contain two different address but refer to the same loction in memory? <Yes / No>

15]

Can two different far pointers contain two different address but refer to the same location in memeory? <Yes / No>

16]

Can two different huge pointers contain two different addresses but refer to the same location in memory?

17]

Would the following program give any warning on compilation ? #include"stdio.h" main() { int *p1,i = 25; void *p2; p1 = &i; p2 = &i; p1 = p2; p2 = p1; }

18]

Would the following program give any warning on compilation ? #include"stdio.h" main() { int *p1,i = 25; void *p2; p1 = &i; p2 = &i; }

19]

What warning would be generated on compiling the following program ? main() { char far *scr; scr = 0xB8000000; *scr = 'A'; }

20]

How would you eliminate the warning generated on compiling the following program? main() { char far *scr; scr = 0xB8000000; *scr = 'A'; }

21]

How would you obtain a 'far' address from the segment and offset addresses of a memory location ?

22]

How would you obtain segment and offset addresses form a 'far' address of a memory location ?

23]

In a large data model(compact, large, huge) all are 32 bits long, whereas in a small data model(tiny,small,medium) all pointers are 16 bits long. < True / False>

24]

A 'near' pointer uses the contents of CS register (if the pointer is pointing to data) for the segement part, whereas the offset part is stored in the 16-bit 'near' pointer. <True / False>

25]

What would be the output of the following program ? main()

{ char far *a = 0x00000120; char far *b = 0x00100020; char far *c = 0x00120000; if(a == b) printf("\n Hello"); if(a == c) printf("Hi"); if(b == c) printf("\n Hello Hi"); if(a > b && a > c && b > c) printf("\n Bye"); }

26]

main() { char huge *a = 0x00000120; char huge *b = 0x00100020; char huge *c = 0x00120000; if(a == b) printf("\n Hello"); if(a == c) printf("Hi"); if(b == c) printf("\n Hello Hi"); if(a > b && a > c && b > c) printf("\n Bye"); }

*********************************************************************** ************************** ANSWERS *******************************

***********************************************************************

1]

No

2]

In files "stdio.h" and "stddef.h"

3]

Because in small memeory models the pointer is two bytes long whereas in large memory models it is 4 bytes long.

4]

For each pointer type (like say a char pointer) C defines a special pointer balue which is guarenteed not to point to any object or function of that type. Usually, the null pointer constant used for representing a null pointer is the integer 0.

5]

A null pointer is a pointer which doesn't point anywhere. A NULL macro is used to represent the null pointer in source code. It has a value 0 associated with it. The ASCII NUL character has all its bits as 0 but doesn't have any relationaship with the null pointer. The null string is just another name for an empty string " ".

6]

7]

No. Only in context of pointers should NULL and 0 be considered equivalent. NULL should not be used when other kind of 0 is required. Even though this may work it is a bad style of programming. ANSI C permits deinition of the NULL macro as (( void *)0), which ensures that the NULL will not work in nonpointer contexts.

8]

9]

A 'near' pointer is 2 bytes long whereas a far and a 'huge' pointer are 4 bytes long.

10]

The Null Poiner Assignment error is generated only in small and medium memory models. This error occurs in programs which attempt to change the bottom of tahe data segment.

In Borland C and C++ compilers, Borland places four zero bytes at the bottom of the data segment, followed by the Borland copyright notice " Borland C++ - Copyright 1991 Borland Intl.". In the small and medium memory models, a null pointer points to DS: 0000. Thus assigning a value to the memory referenced by this pointer will overwrite the first zero byte in the data segment. At program termination, the four zeros and the copyright banner are checked. If either has beenm modified, then the Null Pointer Assignment error is generated. Note that the pointer may not truly be null, but may be a wild pointer that references these key areas in the data segment.

11]

In the Integrated Development Environment set two watches on the key memory locations mentioned in 8.10. These watches, and what they should display in the watch window, are: *(char *)4,42MS Borland C++ - Copyright 1991 Borland Intl."

(char *)0 Of course, the copyright banner will vary depennding on your version of the Borland C/C++ compiler. Step through your program using F8 or F7 and monitor these values in the watch window. At the point where one of them changes, you have just executed a statement that used a pointer that has not been properly initialized. The most common cause of this error is probably declaring a pointer and then using it before allocating memory for it. For example, compile the following program in the small memory model and execute it: #include "dos.h" #include "stdio.h" #include "string.h" main() { char *ptr,*banner; banner = ( char *) MK_FP(_DS,4); printf("banner:%s\n",banner); strcpy(ptr,"the world cup saga"); printf("&ptr = %Fp \n",(void far*) &ptr[0]); printf("banner:%s \n",banner); } One of the best debugging techniques for catching Null pointer assignment errors is to turn on all warinin compiler messages. If the above program is compiled with warnings turned off, no warnin g messages will be generated. However, if all warnings are turned on, both the strcpy() and printf() calls using the ptr bariable will generate warnings. YOu should be particularly suspicious of any warnings that a variable might be used before being initialzed, or of a suspicious pointer assignment. Note that a Null Pointer Assignment error is not generated in all midels. In the compact, large and huge memory models, far pointers are used for data. Therefore, a null pointer will reference 0000:0000, or the base of system memory, and using it will ot cause a corruption of the key balues at the base of the data segement. Modifying the base of system memory usually causes a system crah, however. Athough it would be possible that a wild pointer would ovrewrote the key walues, it would not indicate a null pointer. In the tiny memory model, DS = CS = SS. Therefore, using a null pointyer will overwrite the beginning of the code segment.

12}

Yes, using a wild pointer that happens to regerence the base area of the data segment may cause the same error since this would change the zeros or the copyright banner. Since data corruption or stack corruption could cause an otherwise-valid pointer to be corrupted and point to the base of the data segment, any memory corruption could result in this error being generated. If the pointer used in the program statement which

corrupts the key values appears to have been properly initialized, place a watch on that pointer. Step through your program again and watch for its value (address) to change.

13]

No.

14]

No.

15]

Yes.

16]

No.

17]

No.

18]

Yes. Suspicious pointer conversion in function main.

19]

Non-portable pointer assignment in function main.

20]

Use the typecast scr = (char far *) 0xb8000000;

21]

# include "dos.h" main() { char *seg = (char *) 0xb000; char *off = (char *) 0x8000; char far *p; p = MK_FP(seg,off); }

22]

# include "dos.h" main() { char far *scr = (char *) 0xb8000000; char *seg,*off; seg = (char*) FP_SEG(scr); off = (char *) FP_OFF(scr); }

23]

True.

24]

True.

25]

Bye

Here a,b and c reger to same location in memory still the first three ifs fail because while comparing the are pointers using ==( and !=) the full 32-bit value is used and since the 32-bit balues are different the ifs fail. The last if however gets satisfied, because while comparing using > (and >=, < , <= ) only the offset value is used for comparsion. And the offset values of a,b and c are such that the last condition is satisfied.

26]

Hello Hi Hello Hi Unlike far pointers, huge pointer are 'normalized' to avoid the strange behaviour as in the 25th above. A normalized pointer is a 32-bit pointer which has as much of its value in the segment address as possible. Since a segment can start every 16 bytes, this means that the offset will only have a value for 0 to F. Huge pointers are always kept normalized. As a result for any given memory address there is only one possible huge address segment: offset pair for it.

Chapter-15 Sample Programs


WILL THE FOLLOWING PROGRAM WORK??? SUPPOSE THAT THE BASE ADDRESS OF i IS 2008 AND THAT OF a IS 7006. THE ADDRESS OF ii IS 7602 AND THAT OF aa IS 9118.

/* main() {

PROGRAM

*/

int i = 54; float a = 3.14; char *ii,*aa; ii = &i; aa = &a; printf("\n printf("\n printf)"\n printf("\n }

address cintained in address cintained in value at the address value at the address

ii = %u",ii); aa = %u",aa); contained in ii = %d",*ii); contained in aa = %d",*aa);

ANSWER: Here ii and aa have been declared as char pointers. Still the statements ii = &i and aa = &a will work. Once again the addresses 2008 and 7006 get stored in ii and aa which are printed through the first

two printf()s. However, the porgram flaters at the next two printf()s.This is so since ii is a character pointer *ii gives the value at the address 2008 and dot the one present at 2008 and 2009.Similarly, *aa gives the value at 7006 and not the one comtained in 7006,7007,7008 and 7009. THIS IS BECAUSE A CHARACTER VARIBLE OCCUPIES ONLY ONE MEMORY LOCATION WHEN WE ACCESS THEM, ONLY ONE MEMORY LOCATION IS REFERRED TO. From this we come to know that iv we wish to access an integer value stored in a variable using its address it is necrssary that the address be stored in an integer pointer. Likewise if we wish to accrss a float value stored in a bariable using its address it is necessary to store the address in a float pointer.

PASSING ADDRESSES TO FUNCTIONS: There are 2 methods of doing so. They are 1) call by value(sending the values of the arguements). 2) call by reference(dending the addresses of the arguements.) 1) In the first menthod i.e. "call by value", the 'value' of each arguement in the calling function is copied into corresponding formal arguenents of the called fuction. With this method changes made to the formal arguenents in the called fuction will have no effect on the values of the actual arguements in the calling function. EXAMPLE: THE FOLLOWING PROGRAM ILLUSTRATES THE ' CALL BY VALUE'.

/* main() { int a int b swapv(a,b); printf(" \n printf(" \n }

PROGRAM

*/

= 10; = 20; a = %d",a); b = %d",b);

/* fuction subprogram */ swapv(int x,int y) { int t; t = x; x = y; y = t; printf("\n x = %d",x); printf("\n y = %d",y); } OUTPUT: x = 20 y = 10

a = 10 b = 20 NOTE: Here the values of a and b aremain unchanged even after exchanging the values of x and y.

2) In the second method i.e. "call by reference" the address of the actual arguements in the calling function are copied into the formal aruements of the called function. This means that using the formal arguements in the called function we can make changes in the actual arguements of the calling function. This method is faster than call by value method.

EXAMPLE: THE FOLLOWING PROGRAM ILLUSTRATES THIS FACT: /* PROGRAM main() { int a = int b = swapr(&a,&b); printf(" \n a printf(" \n b } 10; 20; = %d",a); = %d",b); */

/* fucntion subprogram swapr(int *x,int *y) { int t; t = *x; *x = *y; *y = t; printf("\n x = %d",x); printf("\n y = %d",y); } OUTPUT: a b x y

*/

= = = =

20 10 20 10

SOLVED PROBLEMS: WHAT WILL BE THE OUTPUT OF THE FOLLOWING PROGRAMS: FIRST PROGRAM 1] main() { int i = -5,j = -2; junk(i,&j); printf("\n i = %d j = %d",i,j);

} /* subprogram */ junk(int i, int *j) { i = i * i; *j = *j * *j; } OUTPUT: i = -5

j = 4

EXPLANATION: One doubt immediately that comes to the mind is that " can we use same variables in different functions?". Yes, by all means, without absolutely any conflict. Thus, the two sets of 'i' and 'j' are two totally different sets of variables. While calling the fuction 'junk()' the value of i and the address of j are passed to it. Naturally, in 'junk()' 'i' is declared as an ordinary int, whereas 'j' is dexlared as a pointer to an 'int'. Even though the value of 'i' is changed to 25 in junk(), this change will not be reflexted back in main(). As against this, since 'j' s' address is being passed to 'junk()', any change in 'junk()' gets reflected back in 'main()'.

SECOND PROGRAM 2] { main()

int *c; c = check(10,20); printf(\n c = %u",c); } /* subprogram */ check(int i, intj) { int *p,*q; p = &i; q = *j; if( i >= 45) return(p); else return(q); }

OUTPUT: error message:non portable pointer assignment in main. EXPLANATION: The reason for the error is simple. The integers bing passed to 'check()' are collexted in 'i' and 'j', and then their addresses are assigned to 'p' and 'q'. Then in the next statement the conditional operators test the value of 'i' against 45, and return return either tha address stored in 'p' or the address stored in'q'. It appears that this address would be collected in 'c' in 'main()', and

then wouldbe printed out. And there lies the error. The function 'check()' is not capable of returning an integer pointer. All that it can return is an ordinary integer. Thus just declaring 'c' as an integer ponter is not sufficient. We must make the following modifications is the program to make it work properly. MODIGFIED PROGRAM: main() { int *c: int *check(); c = check(10,20); printf("\n c = %u ",c); } /* subprogram */ int *check(int i,int j) { int *p,*q; p = &i; q = &j; if(i >= 45) return(p); else return(q); }

4]

Assume that the value of p is stored at 5498. main() { float *jamboree(); float p = 23.5,*q; q = &p; printf(" \n before call = %u",q); q = jamboree(&p); printf(" \n after call = %u",q); } /* subprogram */ float *jamboree(float *r) { r = r + 1; return(r); }

OUTPUT: q before call = 5498 q after call = 5502 EXPLANATION: In 'main()', q has been declared as a float pointer. It means 'q' is a variable capable of holding the address of a float. Through 'q = &p' the address of 'p', is stored in q and then pronted out through the printf(). This is the value of 'q' before 'jamporee()' is called. When 'jamboree()' is called the address of p is sent to it and collected in 'r'. At this juncture 'r' contains 5498(when we ran

the program it was 5498; when you execute the program this may turn out be some other address). When 'r' is incremented it would become 5502. why a step of 4? This is because 'r' is a float pointer and in incrementing it by 1 it would point to the next float which would be present 4 bytes hence, since every float is 4 bytes long. The return statement then returns this address 5502 back to 'main()'. Since a float pointer is being returned, a decalration float '*jamboree()' is necessary in 'main()', which tells the compoler that down the line there exists a function called 'jamboree()', which will return a float pointer.

****************

POINTERS AND ARRAYS

*****************

To be able to see what pointers have got to do with arrays, let us first learn some pointer arithmetic. Consider the following example: /* program */ main() { int i = 3,*x; float j = 1.5,*y; char k = 'c',*z; printf("\n value of i = %d",i); printf("\n value of j = %f",j); printf("\n value of k = %c",k); x = &i; y = &j; z = &k; printf("\n\n original value in x = %u",x); printf("\n original value in y = %u",y); printf("\n original value in z = %u",z); x++; y++; z++; printf("\n new value in x = %u",x); printf("\n new value in y = %u",y); printf("\n new value in z = %u",z); } SOLUTION: suppose 'i','j' and 'k' are stored in memeory at addresses 1002, 2004 and 5006, the output would be: value of i = 3 value of j = 1.500000 value of k = c original value in x = 1002 original value in y = 2004 original value in z = 5006

new value in x = 1004 new value in y = 2008 new value in z = 5007 Observe the last three lines of the outut. 1004 is original value in x plus 2, 2008 is original value in y plus 4, and 5007 is original balue in z plus 1.This so happens because every time a pointer is incremented it points to the immediately next location of its type. That is why, when the integer pointer x is incremented, it points to an address two locations after the current location, since an int is always 2 bytes long. Similarly 'y' points to an address 4 locations after the current location and 'z' points 1 location after the current location. This is a very important result and can be effectively used while passing the entire array to a function. The way a pointer can be incremented, it can be decremented as well, to earlier locations. Thus, the following operations can be performed on a pointer: 1] addition of a number to a pointer. int j = j = j = k = 2] i = &i; j + j + j + 4,*j,*k; 1; 9; 3;

subtraction of a number from a pointer. int j = j = j = k = i = &i; j j j 4, *j,*k; 2; 5; 6;

CAUTION: Do not attempt the following operations on pointers... they would never work out. (a) addition of two pointers. (b) Multiplying a pointer with a number. (c) Dividing a pointer with a number. ADVANTAGE: While handling arrays, accessing array elements by pointers is always faster than accessing them by subscripts.

/********************** SAMPLE PROGRAMS

********************/

WHAT WILL BE THE OUTPUT OF THE FOLLOWING PROGRAMS: 1] main() { int a[] = {10,20,30,40,50}; int j; for(j = 0; j < 5; j++) { printf("\n %d ",*a); a++; }

} OUTPUT: ERROR MESSAGE: Lvalue required in function main EXPLANATION: Whenever we mention the name of the array, we get its base address. Therefore, first time through the loop, the 'printf()' should print the value of this base address. There is no problem upto this. The problem lies in the next statement, 'a++'. Since C doesn;t perform bounds checking on an array, once declared is its base address. And 'a++' attempts to change this base address, which C won't allow because if it does so, it would be unable to remember the beginning of the array. Anything which can change - in compiler's language - is called Lvalue. Since vbalue of a cannot be changed through ++, it flashes the reeor saying 'Lvalue required' so that ++ operator can change it. 2] main() { float a[] = { 13.24,1.5,1.5,5.4,3.5}; float *j,*k; j = a; k = a + 4; j = j * 2; k = k/2; printf("\n %f %f",*j,*k); } OUTPUT: Error message: illegal use of pointer in function main EXPLANATION: 'j' and 'k' have been decalred as pointer variables, which would contain the addresses of floats. In other words, 'j' and 'k' are float pointers. To begin with, the base address of the array a[] is stored in 'j'. The next statement is perfectly acceptable; the address of the 4th float form the base address is dtored in 'k'. The next two statements aree erroneous. This is because the only operations that can be performed on pointers are addition and subtraction. Multiplication or division of a pointer is not allowed. Hence the error message.

3]

main() { int n[25]; n[0] = 100; n[24] = 200; printf("\n %d %d",*n,*(n + 24) + *(n + 0)); }

OUTPUT: 100

300

EXPLANATION: 'n[]' has been declared as an array capable of holding 25 elements numbvered form 0 to 24. Then 100 and 200 are assigned to 'n[0]' and 'n[24]' rexpectively. Then comes the most important part- the 'printf()' statement. Whenever we mention the name

of the array, we get its base address(i.e. address of the '0th' element of the array). Thus,'*n' would give the value at this base address, which in this case is 100. This is then printed out. Take a look at the next expression, '*(n + 24) + *(n + 0)'. 'n' gives the address of the zeroth element, 'n = 1' gives the address of the next element of the array, and so on. Thus, '*(n+24)' would give the value at this address, which is 200 in our case. Similarly, '*(n + 0)' would give 100 and the addition of the two would result into 300, which is outputted next.

4]

main() { int b[] = {10,20,30,40,50}; int i,*k; k = &b[4] - 4; for(i = 0; i <= 4; i++) { printf("%d",*k); k++; } }

OUTPUT: 10 20 30 40 50

EXPLANATION: The elements of the array are stored in contiguous memory locations and each element is an integer, hence is occupying 2 locations. ARRAY ELEMENT b[0] b[1] b[2] b[3] b[4] 10 20 30 40 50 VALUE MEMORY LOCATION 4002 4004 4006 4008 4010

The expression '&b[4]' gives the addressof 'b[4]'(4010 in the above case). From this address if we subtract 4, we get 4002. Or did you expect to get 4006? Remembre that by subtraction 4 form 4010 what we mean is: get the address of an integer which is 4 integers to the left of the integer whose address is 4010. Now, address of the integer which is 4 integers to the left of the integer whose address is 4010, i.e the address 4002. This address, 4002, is stored in k, which has been declared as a variable capable of holding an integer's address. First time through the for loop '*k' would result into 10, i.e. value at the address in 'k'. 'k++' then increments k such that it contains the address of the next integer, i.e. 4004, which is 20. Similarly, the loop prints out the rest of the elements of the array.

5]

main() { int a[] = {2,4,6,8,10}; int i;

for(i = 0; i <= 4; i++) { *(a + i) = a[i] + i[a]; printf("%d",*(i + a)); } } OUTPUT: 4 8 12 16 20

EXPLANATION: Imbibe the following three facts and the program becomes very simple to understand: (a) Mentioning the name of the array gives the base address of the array. (b) Array elements are stored in contiguous memory locations. (c) On adding 1 to the address of an integer, we get the address of the next integer. With those facts clearly laid out, let us now try to understand the program. Remember that internally C always accesses array elements using pointers. Thus, when we say a[i] internally C converts it to '*(a + i)', which means value of ith integer from the base address. Now, if the expression 'a[i]' is same as '*(a + i)' then '*(i + a)' must be same as 'i[a]'. But '*(a + i)' is same as '*(i + a)'. Therefore 'a[i]' must be same as 'i[a]'.thus 'a[i]', '*(a + i)', '*(i + a)' and 'i[a]' refer to the same element- 'i'th element form the base address. Therefore the expression used in the for loop, '*(a + i)' = 'a[i]' + 'i[a]' is nothing but 'a[i]' = 'a[i]' + 'a[i]'. thus all that is done in the for loop is each array element is doubled and then printedout through 'printf()'. 6] main() { int a[5] = {2,4,6,8,10}; int i,b = 5; for(i = 0; i < 5; i++) { f(a[i],&b) printf("\n %d %d",a[i],b); } } f(int x,int *y) { x = *(y) += 2; } OUTPUT: 2 7 4 9 6 11 8 13 10 15

EXPLANATION: After initialising the array when the control enters the for loop, the function f() gets called with value of a[i] and the address of b. In f() these are collected in variables x and y. then comes the expression x = *(y) += 2. Here *(y) += 2 is evaluated forst and then the result of this expression is assigned to x. The first time through the for loop *(y) gives 5, to which 2 is added and the result is stored at *(y). It means 7 is addigned to b. Finally, the = oerator assigns 7 to x. However, on assigning a new value to x, the array element a[0] in main remains unchanged. Thus, during every call to f(), b's value keeps getting updated whereas there is no change in the values of the array elements.

array element a[0] value memory location 2

b 5 4008

x 2

y 4008

7]

main() { int a[5] = {2,3,4,5,6}; int i; change(a);

Chapter-16 Strings
*********************************************************************** *************************** STRINGS ******************************

***********************************************************************

1]

What would be the output of the following program ? main() {

printf(5 + "Fascimile"); } OPTIONS: (a) (b) (c) (d)

Error Fascimile mile None of the above

2]

What would be the output of the following program ? main() { char str1[] = "Hello"; char str2[] = "Hello"; if (str1 == str2) printf("\n Equal"); else printf("\n Unequal"); }

OPTIONS: (a) (b) (c) (d)

Equal Unequal Error None of the above

3]

What would be the output of the following program ? main() { printf("%c","abcdefgh"[4]); }

OPTIONS: (a) (b) (c) (d)

Error d e abcdefgh

4]

What would be the output of the following program ? main() { char str[7] = "Strings"; printf("%s",str); }

OPTIONS: (a) (b) (c) (d)

Error Strings Cannot predict None of the above

5]

How would you output '\n' on the screen ?

6]

What would be the output of the following program ? main() { char ch = 'A'; printf("%d %d",sizeof(ch),sizeof('A')); }

OPTIONS: (a) (b) (c) (d)

1 1 2 2

1 2 2 1

7]

What would be the output of the following program ? main() { printf("\n%d %d %d",sizeof('3'),sizeof("3"),sizeof(3)); }

OPTIONS: (a) (b) (c) (d)

1 2 1 1

1 2 2 2

1 2 2 1

8]

Is the following program correct ? main() { char *str1 = "United"; char *str2 = "Front"; char *str3; str3 = strcat(str1,str2); printf("\n %s",str3); }

< Yes

No>

9]

How would you improve the code in (8) above ?

10] In the following code which function would get called, the defined strcpy() or the one in the standard library ? main() { char tr1[] = "keep India Beautiful ...emigrate!"); char str2[40]; strcpy(str2,str1); printf("\n %s",str2);

user-

} strcpy(char *t,char *s) { while(*s) { *t = *s; t++; s++; } *t = "\0"; }

11]

Can you compact the code in strcpy() into one line ?

12]

Can you compact the code in strcpy() into one line ? main() { char *str[] = {"Frogs","Do","Not","Die.","They","Crock!"}; printf("%d %d",sizeof(str),sizeof(str[0])); }

13]

How would you find the length of each string in the program (12) above ?

14]

What is the difference in the following declarations ? char *p = "Samuel"; char a[] = "Samuel";

15]

While handling a string do we always have to process it character by character or there exists a method to process the entire string as one unit.

*********************************************************************** ************************* ANSWERS *******************************

***********************************************************************

1]

2]

3]

4]

C. Here 'str[]' has been declared a 7 character array and into it a 8 character string has been stored. This would result into overwriting of the byte beyond the seventh byte reserved for the array with a '\0'. There is always a possibility that something important gets overwritten which would be unsafe.

5]

printf("\\n");

6]

7]

8] No, since what is present in memory beyond 'United' is not and we are attaching 'Front' at the end of 'United', thereby overwriting something, which is an unsafe thing to do.

known

9]

main() { char str1[15] = "United"; char *str2 = "Front"; char *str3; str3 = strcat(str1,str2); printf("\n %s",str3); }

10]

User-defined tyrcpy()

11]

strcpy(char *t,char *s) { while(*t++ = *s++) }

12]

12

13]

main() { char *str[] = {"Frogs","Do","Not","Die","They","Croak!"); int i; for(i = 0;i <= 5;i++)

printf("%s %d",str[i],strlen(str[i])); }

14]

Here 'a' is an array big enough to hold the message and the '\0' following the message. Individual characters within the array can be changed but the address of the array would remain same. On the other hand, 'p' is a pointer, initialized to point to a string constant. The pointer 'p' may be nodified to point to another string, but if you attempt to modify the string at which 'p' is pointing the result is undefined.

15]

A string can be processed only on a character by character

basis.

Chapter-17 Structure Union and Enumerator


*********************************************************************** ************* STRUCTURES,UNIONS AND ENUMERATIONS ****************

***********************************************************************

1]

What is the similarity between, union and an enumeration ?

2]

Would the following declaration work ? typedef struct s { int a; float b; } s;

3]

Can a structure contain a pointer to itself ?

4]

Point out the error, if any, in the following code: typedef struct { int data; NODEPTR link; } *NODEPTR;

5]

How will you eliminate the problem in (4) above ?

6]

Point out the error, if any, in the following code: void mocify(struct emp*); struct emp { char name[20]; int age; }; main() { struct emp e = {"Sanjay",35}; modify(&e); printf("\n %s %d",e.name, e.age); } void modify(struct emp *p) { strupr(p->name); p->age = p->age + 2; }

7]

Would the folowing code work ?

#include<calloc.h> struct emp { int len; char name[1]; }; main() { char newname[] = "Rahul"; struct emp *p = (struct emp *)malloc(sizeof(struct emp) -1 + strlen(newname) + 1); p->len = strlen(newname); strcpy(p->name,newname); printf("\n %d %s",p->len,p->name); }

8]

Can you suggest a better way to write the program in (7) above?

9]

How would you free the memory allocated in (8) above ?

10]

Can you rewrite the progaram in (8) such that while freeing the memory only one call to free() would suffice?

11]

What would be the output of the following program ? main() { struct emp { char *n; int age; }; struct emp e1 = {"Dravid",23}; struct emp e2 = e1; strupr(e2.n); printf("\n %s",e1.n); }

12]

Point out the error, if any, in the following code : main() { struct emp { char n[20]; int age; }; struct emp e1 = {"Dravid",23}; struct emp e2 = e1; if(e1 == e2) printf("\n the structures are equal."); }

13]

How would you check whether the contents of two structure variables are same or not ?

14]

How are structure passing and returning implemented by the compiler ?

15]

How can I read/ write structures from/to data files ?

16]

If the following structure is written to a file using fwrite(), can fread() read it back successfully? struct emp { char *n; int age; }; struct emp e = {"Sujay",15}; FIlE *fp; fwrite(&e,sizeof(e),1,fp);

17]

Would the following program always output the size of the structure as 7 bytes ? struct ex { char ch; int i; long int a; };

18]

What error does the following progarm give and what is the solution for it? main() { struct emp { char name[20]; float sal; }; struct emp e[10]; int i; for(i = 0;i <= 9; i++) scanf("%s %f",e[i].name,&e[1].sal); }

19]

How can I determine the byte offset of a field within a structure ?

20]

The way mentioning the array name of function name without [] or () yields their base addresses, what do you obtain on mentioning the structure name ?

21]

What is main() returning in the following progarm ? struct transaction { int sno; char desc[30]; char dc; float amount; } /* here is the main progarm */ main(int argc, char *argv[]) { struct transaction t; scanf("%d %s %c %f",&t.sno,t.desc,&t.dc,&t.amount); printf("%d %s %c %f",t.sno,t.desc,t.dc,t.amount); }

22]

What would be the output of the following progarm ? main() { struct a { category : 5; scheme : 4; }; printf("size = %d",sizeof(struct a)); }

23]

What's the difference between a structure and a union ?

24]

Is it necessary that size of all elements in a union should be same ?

25]

Point out the error, if any, in the following code: main() { union a { int i; char ch[2]; }; union a z1 = {512}; union a z2 = {0,2}; }

26]

What is the difference between an enumeration and a set of proprocessor # defines ?

27]

Since enumerations have integral type and enumeration constants are of type int can we freely intermix them with other integral types, without errors ? < Yes / No>

28]

Is there an easy way to print enumaeration values symbolically?

29]

What is the use of bit fields in a structure declaration ?

30]

Can we have an array of bit fields ?

<Yes

No>

*********************************************************************** ************************* ANSWERS *******************************

***********************************************************************

1]

All of them let you define new data types.

2]

Yes

3]

Certainly. Such structures are known as self-refertial structures.

4]

A 'typedef' defines a new name for a type, and in simpler cases like the one shown below you can define a new structure type and a 'typedef' for it at the same time. typedef struct { char name[20]; int age; }emp;

However, in the structure defined in (4) there is an error because a typedef declaration cannot be used until it is defined. In the given code fragment the 'typedef' declaration is not yet defined at the point where the link field is declared.

5]

To fix the code,first give the structure a name("struct node"). Then declare the link field as a simple struct node * as shown below: typedef sturct node { int data; struct node *link; }*NODEPTR;

Another way to eliminate the problem is to disentangle the typedef declaration from the structure definition as shown below: struct node { int data; struct node *link; }; typedef struct node *NODEPTR;

Yet another way to eliminate the problem is to precede the structure declaration with the typedef, in which case you could use the NODEPTR typedef when declaring the link field as shown below: typedef struct node *NODEPTR; struct node { int data; NODEPTR next; }; In this case, you declare a new typedef name involving struct node even though struct node has not been completely defined yet; this you're allowed to do. It's a matter of style which of the above solutions would you prefer.

6]

The 'stuct emp' is mintioned in the prototype of the function modify() before defining the structure. To solve the problem just put the prototype after the declaration of the structure or just add the statement 'struct emp' before the prototype.

7] Yes. The program allocates space for the structure with the size adjucted so that the name field can hold the requested name (not just one character, as the structure declaration would suggest). I don't know whether it is legal or portable. However, the code did work on all the compilers that I have tried it with.

8]

The truly safe way to implement the program is to use a character pointer instead of an array as shown below: #include <alloc.h> struct emp { int len; char *name; }; main() { char newname[] = "Rahul"; struct emp *p = (struct emp *)malloc(sizeof(struct emp)); p->len = strlen(newname); p->name = malloc(p->len + 12); strcpy( p->name,newname); printf("\n %d %s",p->len,p->name); }

Obviously, the "convenience" of having the lenght and the string stored in the same block of memory has now been lost, and freeing instances of this structure will reqwuire two calls to the function free().

9]

free(p->name); free(p);

10]

#include <alloc.h> struct emp { int len; char *name; }; main() { char newname[] = "Rahul"; char *buf = malloc(sizeof(struct emp) + (strlen(newname + 1); struct emp *p = (struct emp *)buf; p->len = strlen(newname); p->name = buf + sizeof(struct emp); strcpy(p->name, newname); printf("\n %d %s",p->len,p->name); free(p); }

11]

DRAVID When a sturcture is assigned, passed, or returned, the copying is done monolithically. This means that the copies of any pointer fields will point to the same place as the original. In other words, anything pointed to is not copied. Hence, on changing the name through 'e2.n' is automatically changed 'e1.n'.

12] Sturctures can't be compared using the built-in '==' and '!=' operations. This is because there is no single, good way for a compiler to implemenmt structure comparison. A simple byte-bybyte comparison could fail while comparing the bits present in unused paddings in the structure (such padding is used to keep the alignment of later fields correct). A field-by-field comparison might require unacceptable amounts of repetitive code for large sturctures. Also, any compiler-generated comparison could not expected to compare pointer fields appropriately in all cases; for example, it's often appropriate to compare 'char *' fields with 'strcmp()' rather than with '=='.

13]

struct emp { char n[20]; int age; }; main() { struct emp e1 = {"Dravid",23};

struct emp e2; scanf("%s %d",e2.name,&e2.age); if(structcmp(e1,e2) == 0) printf("the structures are equal"); else printf("the structures are not equal."); } structcmp(struct emp x, struct emp y) { if (strcmp(x.n,y.n) == 0) if(x.age == y.age) return(0); return(1); } In short, if you need to compare two sturctues, you'll have to write your own function to do so which carries out the comparison field by field.

14]

When structures are passed as arguements to functions, the entire structure is typically pushed on the stack. To avoid this overhead many programmers often prefer to pass pointers to structures instead of actual structures. Structures are often returned from functions in a location pointed to by an extra, compiler-supplied 'hidden' argument to the function.

15]

To write out a sturcture we can use 'fwrite()' as shown fwrite(&e,sizeof(e),1,fp); where e is a structure variable. A corresponding 'fread()' invocation can read the structure back form a file. On calling 'fwrite()' it writes out 'sizeof(e)' bytes from the address '&e'. Data files written as memory images with 'fwrite()', however, will not be portable, particularly if they contain floating-point fields or pointers. This is because memory layout of structures is machine and compiler dependent. Different compilers may use different amounts of padding, and the sizes and byte orders of fundamental types vary across machines. Therefore, structures written as memory images cannot necessarily be read back in by programs running on other machines (or even compiled by other compilers), and this is an important concern if the data files you're writing will ever be interchanged between machines.

16]

No, since the structure contains a 'char' pointer while writing the structure to the disk using 'fwrite()' only the value stored in the pointer 'n' would get written (and not the string pointed by it). When this structure is read back the address would be read back but it is quite unlikely that the desired string would be present at this address in memory.

17]

No. A compiler may leave holes in structures by padding the first 'char' in the sturcture with another byte

just to ensure that the integer that follows is stored at an even location. Also there might be two extra bytes after the integer to ensure that the long integer is stored at an address which is a multiple of 4. This is done because many machines access values in memory most efficiently when the values are appropriately aligned. Some machines cannot perform unaligned accesses at all and require that all data be appropriately aligned. Your compiler may provide an extension to give you control over the packing of structures(i.e., whether they are padded), perhaps with a #pragma, but there is no standard menthod. If you're worried about wasted space, you can minimise the effects of padding by ordering the members of a structure from largest to smallest. You can sometimes get more control over size and alignment by using bitfields, although they have their own drawbacks.

18] Error: Floating point formats not linked. What causes this error to occur? When the compiler encounters a reference to the address of a 'float', it sets a flag to have the linker link in the floating point emulator. A floating point emulator is used to manupilate floating point numbers in runtime library functions like 'scanf()' and 'atof()'. There are some cases in which the reference to the 'float' is a bit obscure and the compiler does not detect the need for the emulator. These situations usually occur during the initial stages of program development. Normally, once the progaram is fully developed, the emulator will be used in such a fashion that the compiler can accurately determine when to link in the emulator. To force linking of the floating point emulator into an application, just include the follwoing function in your program: void LinkFloat(void) { float a = 0, *b = &a; /* cause emulator to be linked */ a = *b; /* suppress warning - bar not used */ } There is no need to call this function from your program.

20] You can use the offset macro given below. How to use this macro has also been shown in the program: #define offset(type,mem)((int)((char*)&((type*)0)-mem-(char*)(type*)0)) main() { struct a { char name[15]; int age;

float sal; }; int offsetofname, offsetofage, offsetofsal; offsetname = offset(struct a, name); printf("\n %d",offsetofname); offsetofage = offset(struct a,age); printf("\n %d",offsetofage); offsetofsal = offset(struct a, sal); printf("\n %d",offsetofsal); } The output of the program will be 0 15 17

21]

The entire structure itself and not its base address.

22]

A missing semicolon at the end of the structure declarations is causing 'main()' to be declared as returning a structure. The connection is difficult to see because of the intervening comment.

23]

size = 2 Sin ce we have used bit fields in the structure and the total number of bits is turning out to be more than 8( 9 bits to be precise) the size of the structure is bing reported as 2 bytes.

24]

A union is essentially a structure in which all of the fields overlay each other; you can use only one field at a time. You can also write to one field and read from another, to inspect a type's bit patterns or interpret them differently.

25]

The ANSO C Standard allows an initializer for the first member of a union. There is no standard way of initializing any other member, hence the error in initilizing z2. Many proposals have been advanced to allow more flexible union initialization, but none has been adopted yet. If you still want to initialise different members of the union, with the members in different orders, so that you can declare and intitialize the one having the appropriate first member as shown below: unoin a { int i; char ch[2]; }; union b

{ char ch[2]; int i; }; main() { union a z1 = {512}; union b z2 = {0,2}; }

26]

There is hardly any differience between the two, except that a '#define' we have to explicitly define them. A disadvantage is that we have no control over the sizes of enumeration variables.

27]

Yes

28] No. You can write a small function ( one per enumeration) to map an enumeration contant to a string, either by using a switch statement or by searching an array.

29]

Bitfields are used ato save space in sturctures having several binary flags or other small fields. Note that the colon notation for specifying the size of a field in bits is valid only in structures (and in unions); you cannot use this mechanism to specify the size of arbitary variables.

30]

No

Chapter-18 Subtleties of typedef


*********************************************************************** ************* SUBTLETIES OF TYPEDEF ******************

***********************************************************************

1] Are tahe properties of i,j and x,y in the folowing program < Yes / No >

same?

typedef unsigned ling int uli; uli i,j; unsigned long in x,y;

2]

What is the type of compare in the following code segment? typedef int (*ptrtofun)(char *,char *); ptrtofun compare;

3]

What are the advantages of using typedef in a program?

4]

Is there any difference in the #define and the typedef in the follwoing code? If yes, what? typedef char *string_t; #define string_d char* string_t s1,s2; string_d s3,s4;

5]

typedefs have the advantage that obey scope rules, that is, they can be declared local to a function or a block whereas #defines always have aglobal effect. < True / False>

6]

Point out the error in the following decalrations and suggest atleast there solutions for it. tyupedef struct { int data; NODEPTR link; } *NODEPTR;

7]

In the following code can be delcare a new typedef name emp even though struct employee has not been completely defined while using typedef? < Yes / No > typedef struct employee *ptr; struct employee { char name[20]; int age; ptr next; };

8]

There is an error in the following declarations. Can you rectify it? typedef struct { int data1;

BPTR link1; }*APTR; typedef struct { int data2; APTR link2; }*BPTR;

9]

What do the following decalrations mean? typedef char *pc; typedef pc fpc(); typedef fpc *pfpc; typedef pfpc fpfpc(); typedef fpfpc *pfpfpc; pfpfpc a[N];

10]

How would you define a[N] in 15.9 above without using typedef?

11]

Improve the following code using typedef. struct node { int data1; float data2; struct node *left; struct node *right; }; struct node *ptr; ptr = (struct node *) malloc(sizeof(struct node));

12]

Is the following declaration acceptable? < Yes / No> typedef long no,*ptrtono; no n; ptrtono p;

13]

In the following code what is constant, p or the cahracter it is pointing to? typedef char *charp; const charp p;

14]

In the following code is p2 an integer or on integer pointer? typeder int *ptr; ptr p1,p2;

*********************************************************************** ******************* ANSWERS **********************

***********************************************************************

1]

Yes

2]

It is a pointer to function which receives two character pointers and an integer.

3]

There are three main reasons for using typedefs: (a) It makes writing of complicated decalrations a lot easier. This helps in eliminationg a lot of clutter in the program. (b) It helps in achieving portability in programs. That is, if we use typedefs for data types that are machine-dependent, only the typedefs need change when the program is moved to a new machine platform. (c) It helps in providing a better doumentation for a program. For example, a node of a doubly linked list is better understood as ptrtolist rather than just a pointer to a complicated structure.

4]

In these declarations, s1,s2 and s3 are all treated as char *, but s4 is treated as a char, which is probably not the intention.

5]

True.

6]

A typedef decalration cannot be used until it is defined, and in our example it is not yet defined at the point where the link field is declared. We can fix this problem in three ways: (a) Give the structure a name, say node and then decare the link as a simple struct node * as shown below:

typedef struct node { int data; struct node *link; }*NODEPTR; (b) Keep the typedef declaration separate from the structure definition: struct node { int data; struct node *link; }; typedeaf struct node *NODEPTR;

(c) Predede the structure declaration with typedef, so that you can use the NODEPTR typedef when declaring the link field: typedef struct node *NODEPTR; struct node { int data; NODEPTR link; };

7]

Yes

8]

The problem with the code is the compiler doesn't know about BPTR when it is used in the first structure declaration. We are violating the rule that a typedef declaration cannot be used until it is defined, and in our example it is not yet defined at the point where the link1 field is declared. To avoid this problem we can defint the structures as shown below: struct a { int data1; struct b *link1; }; struct b { int data2; struct a link*2; }; typedef struct a *APTR; typedef struct b *BPTR; The compiler can accept the field declaration strcut b *ptr1 within struct a, even though it has not yet heard of

struct b (which is "incomplete" at that point). is necessary to precede this couplet with the line struct b;

Occasionally, it

This empty declaration masks the pair of structure declarations (if in an inner scape) from a different struct b in an outer scope. After decalring the two structures we can then declare the typedefs separately as shown above. typedef struct a *APTR; typedef struct b *BPTR; struct a { int data1; BPTR link1; }; struct b { int data2; APTR link2; };

9]

pc is a pointer to char. fpc is function returning pointer to char. pfpc is pointer to a function returning pointer to char. fpfpc is a function returning pointer to a function returning pointer to char. pfpfpc is a pointer to function returning pointer to a function returning pointer to char. pfpfpc a[N] is an array of N pointers to functions returning pointers to functions returning pointers to characters.

10]

char *(*(*a[N])())();

11]

typedef struct node *treeptr typedef struct node { int data1; float data2; treeptr *left; treeptr *right; }treenode; treeptr ptr; ptr = (treeptr)malloc(sizeof(treenode));

12]

Yes.

13]

p is a constant.

14]

Integer pointer.

Chapter-19 Constant Phenomenon


*********************************************************************** ************* THE CONST PHENOMENON ******************

***********************************************************************

1]

Point out the error in the following program. main() { const int x; x = 128; printf("%d",x); }

2]

What would be the output of the following program? main() { int y = 128; const int x = y; printf("%d",x); }

A] B] C] D]

128 Garbage value Error 0

3]

What would be the output of the following program?

main() { const int x = get(); pjrintf("%d",x); } get() { return(20); } A] B] C] D] 20 Garbage value Error 0

4]

Point out the error, if any, in the following program : #define MAX = 128 main() { const int mac = 128; char array[max]; char string[MAX]; array[0] = string[0] = 'A'; printf("%c %c",array[0],string[0]); }

5]

Point out the error in the following program : main() { char mybuf[] = "Zanzibar"; charyourbuf[] = "Zienzkewiz"; cajr *const ptr = mybuf; *ptr = ''; ptr = yourbuf; }

6]

Point out the error in the following program : main() { char mybuf[] = "Zanzibar"; char yourbuf[] = "Zienckewiz"; const char *ptr = mybuf; *ptr = 'a'; ptr = yourbuf; }

7]

Point out the error in the following program : main()

{ char mybuf[] = "Zanzibar"; const char *const ptr = "Hello"; ptr = mybuf; *ptr = 'M'; }

8]

What does the following prototype indicate? strcpy(cahr *target, const char *source);

9]

What does the following prototype indicate? const char *change(char *,int)

10]

Point out the error in the following program: main() { const char *fun(); char *ptr = fun(); } const cahr *fun() { return"Hello"; }

11]

Is there any error in the following program? <Yes main() { const cahar *fun(); char *ptr = fun(); } const char *fun() { return"Hello"; }

No>

12]

Point out the error in the following program : main() { const char *fun(); *fun() = 'A'; } const char *fun() { return"Hello";

13]

What do you mean by const correctness?

14]

What would be the output of the following program? main() { const int x = 5; int *ptrx; ptrx = &x; *ptrx = 10; printf("%d",x); }

A] B] C] D

5 10 Error Garbage value

15]

What would be the output of the following program? main() { const int x = 5; const int *ptrx; ptrx = &x; *ptrx = 10; printf("%d",x); }

A] B] C] D

5 10 Error Garbage value

16]

Point out the error in thee following program: main() { const int k = 7; int *const q = &k; printf("%d",*q); }

17]

What is the difference int the following declarations? const char *s; char const *s;

18]

What is the difference int the following declarations?

const char *const s; char const *const s;

19]

Is the following a properly written function? If not, why not? int fun(const int n) { int a; a = n * n; return a; }

*********************************************************************** ****************** ANSWERS **********************

***********************************************************************

1]

Nowhere other than through initialization can a program assign a value to a const identifier. 'x' should have been initialised where it is declared.

2]

3]

4]

The dimension of an array must always be positive non-zero integer which max is not.

5]

'ptr' pointer is constant. In ptr = yourbuf the program is trying to modify it, hence an error.

6]

'ptr' can be modified but not the object that it is pointing to. Hence '*ptr = 'A'' gives an error.

7]

'ptr' is a constant pointer to a constant object. We can neither modify 'ptr' nor the object it is pointing to.

8]

We can modify the pointers source as well as target. However, the object to which source is pointing cannot be nodified.

9]

The function change() receives a char pointer and an int and returns a pointer to a constant char.

10]

No.

12]

fun() retruns a pointer to a const character which cannot be modified.

13]

A program is 'const correct' if it nevr changes (a more common term is mutates) a constant object.

14]

15]

16]

Warning: Suspicious pointer conversion. 'k' can be pointed to only by a pointer to a const; q is a const pointer.

17]

There is no difference.

18]

There is no difference.

19]

Since fun() would be called by value there is no need to declare n as a const since passing by value already prevents fun() from modifying n.

Chapter-20 C preprocessors
*********************************************************************** *********************** THE C PREPROCESSOR *************************

***********************************************************************

1]

If the file to be included doesn't exist, the preprocessor flashes an error message. < True / False>

2]

The preprocessor can trap simple errors like missing declarations, nested comments or mismatck of braces. <True / False>

3]

What would be the output of the following program? # define SQR(x) (x * x) main() { int a, b = 3; a = SQR(b + 2); printf("\n %d",a); }

OPTIONS: (a) (b) (c) (d)

25 11 Error Some garbage value

4]

How would you define the SQR macro in 6.3 above such that it gives the result of a as 25.

5]

What would be the output of the following program? # define CUBE(x) (x * x * x) main() { int a, b = 3; a = CUBE(b++); printf("\n %d %d",a,b); }

6]

Indicate what would the SWAP macro be expanded to on preprocessing. Would the code compile? # define SWAP(a,b,c) (ct; t = a; a = b; b = t;) main() { int x = 10,y = 20; SWAP(x,y,int); printf("%d %d",x,y); }

7]

How would you modify the SWAP macro in 6.6 above such that it is able to exchange two integers.

8]

What is the limitation of the SWAP macro of 6.7 above?

9]

In which line of the following program an error would be reported? (1) (2) (3) (4) (5) (6) (7) (8) (9) #define CIRCUM(R) (3.14 * R * R); main() { float r = 1.0, c; c = CIRCUM(r); printf("\n %f",c); if(CIRCUM(r) == 6.28) printf("\n Gobbledygook"); }

10]

What is the type of the variable 'b' in the following declaration? # define FLOATPTR float* FLOATPTR a,b;

11] Is it necessary that the header files should have a '.h' extension?

12]

What do the header files usually contain?

13] Would it result into an error if a header file is included twice? < Yes / No>

14] How can a header file ensure that it doesn't get included more than once?

15]

On inclusion, where are the header files searched for?

16]

Would the following typedef work? typedef #include I;

17]

Would the following code compile correctly? main() { #ifdef NOTE /* unterminated comment int a; */

a = 10; #else int a; a = 20; #endif printf("%d",a); }

18]

What would be the output of the following program? #define MESS Junk main() { printf("MESS"); }

19] Would the following program print the message infinite number of times? <Yes / No> #define INFINITELOOP while(1) main() { INFINITELOOP printf("\n Grey haired"); }

20]

What would be the output of the following program? #define MAX(a,b) ( a>b? a:b) main() { int x; x = MAX(3 + 2,2 + 7); printf("%d",x); }

21]

What would be the output of the following program? #define PRINT(int) printf("%d",int) main() { int x = 2, y = 3, z = 4; PRINT(x); PRINT(y); PRINT(z); }

22]

What would be the output of the following program? #define PRINT(int) printf(*int = %d*,int) main()

{ int x = 2, y = 3, z = 4; PRINT(x); PRINT(y); PRINT(z); }

23]

How would you modify the macro of 6.22 such that it outputs: x = 2 y = 3 z = 4

24]

Would the following program compile successfully? < Yes / No) main() { printf("Tips" "Traps); }

25]

Define the macro DEBUG such that the following program outputs: DEBUG: x = 4 DEBUG: y = 3.140000 DEBUG: ch = A main() { int x = 4; float a = 3.14; char ch = 'A'; DEBUG(x,%d); DEBUG(a,%f); DEBUG(ch,%c); }

*********************************************************************** ********************** *************************** ANSWERS

***********************************************************************

1]

True

2]

False

3]

B. Because, on preprocessing the expression becomes 'a = a(3 + 2 * 2 + 3).

4]

#define SQR(x) ((x) * (x))

5]

27 6. Though some compilers may give this as the answer, according to the ANSI C standard the expression b++ * b++ * b++ is undefined. Refer Chapter 3 for more details on this.

6]

(int t; t = a, a = b, b= t); This code won't compile since declaration of t cannot occur within parentheses.

7]

#define SWAP(a,b,c) ct; t = a, a = b, b = t;

8]

It cannot swap pointers. For example, the following code would not compile. #define SWAP(a,b,c) ct; t = a, a = b, b = t; main() { float x = 10,y = 20; float *p,*q; p = &x; q = &y; SWAP(p,q,float*); printf("%f %f",x,y); }

9]

Line number 7, whereas the culprit is really the semicolon in line number 1. On expansion line 7 becomes ' if ((3.14 * 1.0 * 1.0); == 6.28). Hence the error.

10]

'float' and not a pointer to a float, since on expansion the declaration becomes: float *a,b;

11]

No. However, traditionally they have been given a .h extension to identify them as someting different than the .c program files.

12]

Preprocessor directives like #define, structure, union and enum declarations, typedef declarations, global variable declarations and external function declarations. YOu should not write the actual code ( i.e. function bodies) or global variable definition (that is difining or initialising instances) in header files. The # include directives should be used to pull in header files, not other .c files.

13]

Yes, unless the header file has taken care to ensure that if already included it doesn't get included again.

14]

All declarations must be written in the manner shown below. Assume that the name of the header file in FUNCS.H. /* funcs.h */ #ifdef_FUNCS #define_FUNCS /* all declarations would go here */ #endif Now if we include this file twice as shown below, it would get included only once. #include "goto.c" #include "goto.c" main() { /* some code */ }

15]

If included using <> the files get searched in the predefined (can be changed) include path. If included withe the " " syntax in addition to the predefined include path the files also get searched in the current directory ( usually the directory form which you inboked the compiler).

16]

No.

Because 'typedef' goes to work after preprocessing.

17]

No. Even though the #ifdef fails in this case ( NOTE being undefined) and the if block doesn't go for compilation errors in it are not permitted.

18]

MESS

19]

Yes

20]

21]

2 3 4

22]

int = 2 int = 3 int = 4

23]

#defien PRINT(int) printf(#int "= %d", int) main() { int x = 2, y = 3, z = 4; PRINT(x); PRINT(y); PRINT(z); } The rule is if the parameter name is preceded by a # in the macro expansion, the combination(of # and parameter) will be expanded into quoted string with the parameter replaced by the actual argument. This can be combined with string concatenation to print the output desired in our program. On expansion the macro becomes: printf("x" "= %d",x); The two strings get concatenated, so the effect is printf("x = %d",x);

24]

Yes. The output would be TipsTraps. In fact this result has been used in 6.23 above.

25]

#define DEBUG(var,fmt) printf("DEBUG:" #var "="#fmt"\n",var)

26]

multiply Here two operations are being carried out expansion and stringizinf. Xstr() macro expands its argument, and then str() stringizes it.

27]

#define PRINT(var1,var2,var3) printf("\n" #var1 "= %d" #var2 "= %d" #var3 "= %d",var1,var2,var3)

Chapter-21 Variable Number of arguments


*********************************************************************** ****************** VARIABLE NUMBER OF ARGUEMENTS ********************** ***********************************************************************

1]

Which header file should you include if you are to develop a function which can accept variable number of arguments?

Options: (a) (b) (c) (d)

vararg.h stdlib.h stdio.h stdarg.h

2]

What would be the output of the following program? # include<stdio.h> # include<stdarg.h> main() { fun("Nothing specific", 1,4,7,11,0); } fun(char *msg, ...) { int tot = 0; va_list ptr; int num; va_start(ptr, msg); num = va_org(ptr,int); num = va_arg(ptr,int); printf("\n%d",num); }

3]

Is it necessary that in a function which accepts variable argument list there should at least be one fixed argument? < Yes / No >

4]

Can the fixed arguments passed to the functio which accepts variable argument list occur at the end? < Yes / No >

5]

Point out the error, if any, in the follwoing program. # include<stdarg.h> main() { varfun(3,7,-11,0); } varfun(intn, ...) { va_list ptr; int num; num = va_arg(ptr,int); printf("\n %d",num); }

6]

Point out the error, if any, in the follwoing program. # include<stdarg.h> main() { varfun(3,7.5,-11.2,0.66); } varfun(int n, ... ) { float * ptr; int num; va_start(ptr,n); num = va_arg(ptr,int); printf("\n %d",num); }

7]

Point out the error, if any, in the follwoing program. # include<stdarg.h> main() { fun(1,4,7,11,0); } fun( ... ) { va_list ptr; int num; va_start(ptr,int); num = va_arg(ptr,int); printf("\n %d",num); }

8]

The macro va_start is used to initialise a pointer to the beginning of the list of fixed arguments. < True / False >

9]

The macro va_arg is used to extract an argument from the variable argumetn list and advance the pointer to the next argument. < True / False >

10]

Point out the error, if any, in the following program. # include"stdarg.h" main() { display(4,'A','a','b','c'); } display(int num, ... ) { char c; int j; va_list ptr; va_start(ptr,num); for(j = 1; j <= num; j++) { c = va_arg(ptr,char); printf("%c",c); } }

11]

Mention any variable argument list function that you have used and its prototype.

12]

Point out the error, if any, in the follwoing program. # include"stdarg.h" main() { display(4,12.5,13.5,14.5,44.3); } display(int num, ... ) { float c; int j; va_list ptr; va_start(ptr, num); for(j = 1; j <= num; j++) { c = va_arg(ptr,float); printf("\n %f",c); } }

13]

Point out the error, if any, in the follwoing program. # include"stdarg.h" main() { display("Hello",4,2,12.5,13.5,14.5,44); } display(char *s,int num1, int num2, ... ) { float c; int j; va_list ptr; va_start(ptr, num); c = va_arg(ptr,double); printf("\n %f",c); }

14]

Can we pass a variable argumetn list to a function at run-time? < Yes / No >

15]

While defining a variable argument list function can we drop the ellipsis. ( ... ) < Yes / No >

16]

Can we write a function that takes a variable argumetn list and passes the list to another function (which takes a variable number of argumetns) < Yes / No>

17]

Point out the error, if any, in the foll0wing program. # include "stdarg.h" main() { display("Hello",4,12,13,14,44); } display(char *s, ... ) { show(s, ... ) } show(char *t, ... ) { va_list ptr; int a; va_start(ptr,t); a = va_arg(ptr,int); printf("%f",a); }

18]

How would you rewrite program 18.17 such that show() is able to handle variable argument list?

19]

If I use the following printf() to proint a long int why I am not warned about the type mismatch? printf("%d",num);

20]

Can you write a function that works similar to 'printf()'?

21]

How can a called function determine the number of arguments that have been passed to it?

22]

Can there be at least some solution to determine the number of arguments passed to a variable argument list function?

23]

Point out the error in the following program. # include main() { int int int "stdarg.h"

(*p1)(); (*p2)(); fun1(),fun();

p1 = fun1(); p2 = fun2(); display("Bye",p1,p2); } display(char *s, ... ) { int (*pp1)(); va_list ptr; va_start(ptr,s); pp1 = va_arg(ptr,int(*)()); (*pp1)(); pp2 = va_arg(ptr,int(*)()); (*pp2)(); } fun1() { printf("Hello"); } fun2() { printf("Hi"); }

24]

How would you rectify the error in the program 18.23 above?

*********************************************************************** ************************* ANSWERS *****************************

***********************************************************************

1]

2]

3]

Yes

4]

No

5]

Since 'ptr' has not been set at the beginning of the variable argument list using va_start it may be pointing anywhere and hence a call to va_arg would fetch a wrong integer.

6]

Irrespective of the type of argument passed to a function receiving variable argument list, 'ptr' must be of the type va_list.

7]

There is no fixed argument i n the definition of 'fun()'.

8]

False

9]

True

10]

While extracting a 'char' argument using va_arg we should have used c = va_arg(ptr,int).

11]

printf(const char *format, ... )

12]

While extracting a float argrment using va_arg we should have used c = va_arg(ptr,double).

13]

While setting the 'ptr' to the beginning of variable argument list we should have used va_start(ptr,num2).

14]

No. Every actual argument list must be completely known at compile time. In that sense it is not truely a variable argument list.

15]

Yes

16]

Yes

17]

The call to 'show()' is improper. This is not the way to pass variable argument list to a function.

18]

# include"stdarg.h" main() { display("Hello",4,12,13,14,44); } display(char *s, ... ) { va_list ptr; va_start(ptr,s); show(s,ptr); } show(char *,va_list ptr1) { int a,n,i; a = va_arg(ptr1,int); for(i = 0; i < a; i++) { n = va_arg(ptr1,int); printf("\n %d",n); } }

19]

When a function accepts a variable number of arguments, its prototype cannot provide any information about the number of arguments and type of those variable arguments. Hence the compiler cannot warn about the mismatches. The programmer must make sure that arguments match or must manually insert explicit typecasts.

20]

# include<stdio.h> # include<stdarg.h> main() { void myprintf(char *, ... ) char *convert(unsigned int,int); int i = 65; char str[] = "Intranets are here to stay .."; myprintf("\n Message = %s, %d %x",str,i,i); } void myprintf(char *fmt, ... ) { char *p; int i; unsigned j; char *s; va_list argp; va_start(argp,fmt); p = fmt; for(p = fmt; *p != '\0\; p++) { if(*p != '%') { putchar (*p); continue; } p++; switch(*p) { case 'c': i = va_arg(argp,int); putchar(i); break; case 'd': i = va_arg(argp,int); if(i < 0) { i = -i; purchar('-'); } puts(cionvert(i,10)); break;

case 'o': u = va_arg(argp,unsigned int); puts(convert(u,8)); break; case 's': s = va_arg(argp,char *); puts(s); break; case 'u': u = va_arg(argp,unsigned int); puts(convert(u,10)); break; case 'x': u = va_arg(argp,unsigned int); puts(convert(u,16)); break; case '%': purchar('%'); break; } } va_end(argp); } char *convert(unsigned int num, int base) { static char buff[33]; char *ptr; ptr = &buff[sizeof(buff) - 1]; *ptr = '\0\; do { *--ptr = "0123456789abcdef"[num % base]; num /= base; }while(num != 0); returnptr; }

21]

It cannot. Any function that takes a variable number of arguments must be able to determine from the arguments themselves how many of them there are. The printf() function, for example, does this by looking for format specifiers (%d etc.) in the format string. This is the reason why such

functions fail badly if the format string does not match the argument list.

22]

When the arguments passed are all of same type we can think of passing a sentinel value like -1 or 0 or a NULL pointer at the end of the variable argument list. Another way could be to explicitly pass the count of number of variable arguments.

23]

'va_arg' cannot extract the function pointer from the variable argument list in the manner tried here.

24]

Use 'typedef' as shown below: # include"stdarg.h" main() { int(*p1)(); int(*p2)(); int fun1(),fun2(); p1 = fun1; p2 = fun2; display("Bye",p1,p2); } display(char *s, ... ) { int (*pp1)(),(*pp2)(); va_list ptr; typedef int(*funcptr)(); va_start(ptr,s); pp1 = va_arg(ptr,funcptr); (*pp1)(); pp2 = va_arg(ptr,funcptr); (*pp2)(); } fun1() { printf("\n Hello"); } fun2() { printf("\n Hi"); }

First Job. Dream Job. Freshersworld.com

Data Structure
1. What is data structure? A data structure is a way of organizing data that considers not only the items stored, but also their relationship to each other. Advance knowledge about the relationship between data items allows designing of efficient algorithms for the manipulation of data. 2. List out the areas in which data structures are applied extensively? Compiler Design, Operating System, Database Management System, Statistical analysis package, Numerical Analysis, Graphics, Artificial Intelligence, Simulation

3. What are the major data structures used in the following areas : RDBMS, Network data model & Hierarchical data model. RDBMS Array (i.e. Array of structures) Network data model Graph Hierarchical data model Trees 4. If you are using C language to implement the heterogeneous linked list, what pointer type will you use? The heterogeneous linked list contains different data types in its nodes and we need a link, pointer to connect them. It is not possible to use ordinary pointers for this. So we go for void pointer. Void pointer is capable of storing pointer to any type as it is a generic pointer type. 5. Minimum number of queues needed to implement the priority queue? Two. One queue is used for actual storing of data and another for storing priorities. 6. What is the data structures used to perform recursion? Stack. Because of its LIFO (Last In First Out) property it remembers its caller so knows whom to return when the function has to return. Recursion makes use of system stack for storing the return addresses of the function calls. Every recursive function has its equivalent iterative (non-recursive) function. Even when such equivalent iterative procedures are written, explicit stack is to be used.

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com 7. What are the notations used in Evaluation of Arithmetic Expressions using prefix and postfix forms? Polish and Reverse Polish notations. 8. Convert the expression ((A + B) * C (D E) ^ (F + G)) to equivalent Prefix and Postfix notations. Prefix Notation: ^ - * +ABC - DE + FG Postfix Notation: AB + C * DE - - FG + ^ 9. Sorting is not possible by using which of the following methods? (a) Insertion (b) Selection (c) Exchange (d) Deletion (d) Deletion. Using insertion we can perform insertion sort, using selection we can perform selection sort, using exchange we can perform the bubble sort (and other similar sorting methods). But no sorting method can be done just using deletion. 10. A binary tree with 20 nodes has null branches? 21 Let us take a tree with 5 nodes (n=5)

Null Branches

It will have only 6 (ie,5+1) null branches. In general, A binary tree with n nodes has exactly n+1 null nodes. 11. What are the methods available in storing sequential files ? Straight merging, Natural merging, Polyphase sort, Distribution of Initial runs.

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com

12. How many different trees are possible with 10 nodes ? 1014 For example, consider a tree with 3 nodes(n=3), it will have the maximum combination of 5 different (ie, 23 - 3 = 5) trees.

ii

iii

iv

In general: If there are n nodes, there exist 2n-n different trees. 13. List out few of the Application of tree data-structure? The manipulation of Arithmetic expression, Symbol Table construction, Syntax analysis. 14. List out few of the applications that make use of Multilinked Structures? Sparse matrix, Index generation. 15. In tree construction which is the suitable efficient data structure? (a) Array (b) Linked list (c) Stack (d) Queue (e) none (b) Linked list 16. What is the type of the algorithm used in solving the 8 Queens problem? Backtracking 17. In an AVL tree, at what condition the balancing is to be done? If the pivotal value (or the Height factor) is greater than 1 or less than 1. 18. What is the bucket size, when the overlapping and collision occur at same time? One. If there is only one entry possible in the bucket, when the collision occurs, there is no way to accommodate the colliding value. This results in the overlapping of values.

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com 19. Traverse the given tree using Inorder, Preorder and Postorder traversals. Given tree:
A

Inorder : D H B E A F C I G J Preorder: A B D H E C F G I J Postorder: H D E B F I J G C A 20. There are 8, 15, 13, 14 nodes were there in 4 different trees. Which of them could have formed a full binary tree? 15. In general: There are 2n-1 nodes in a full binary tree. By the method of elimination: Full binary trees contain odd number of nodes. So there cannot be full binary trees with 8 or 14 nodes, so rejected. With 13 nodes you can form a complete binary tree but not a full binary tree. So the correct answer is 15. Note: Full and Complete binary trees are different. All full binary trees are complete binary trees but not vice versa. 21. In the given binary tree, using array you can store the node 4 at which location? 1

4 5 Freshersworld.com Resource Center 4

First Job. Dream Job. Freshersworld.com

At location 6

1 Root

2 LC1

3 RC1

LC2

RC2

4 LC3

RC3

LC4

5 RC4

where LCn means Left Child of node n and RCn means Right Child of node n 22. Sort the given values using Quick Sort?

65

70

75

80

85

60

55

50

45

Sorting takes place from the pivot value, which is the first value of the given elements, this is marked bold. The values at the left pointer and right pointer are indicated using L and R respectively. 65 70L 75 80 85 60 55 50 45R

Since pivot is not yet changed the same process is continued after interchanging the values at L and R positions 65 65 65 45 45 45 75 L 50 50 80 80 L 55 85 85 85 L 60 R 60 60 60 R 85 L 55 55 R 80 50 R 75 75 70 70 70

65

45

50

55

80

75

70

When the L and R pointers cross each other the pivot value is interchanged with the value at right pointer. If the pivot is changed it means that the pivot has occupied its original position in the sorted order (shown in bold italics) and hence two different arrays are formed, one from start of the original array to the pivot position-1 and the other from pivot position+1 to end. 60 L 55 L 50 L 45 45 45 R 50 50 R 55 55 R 60 60 65 65 65 85 L 70 R 70 80 80 L 80 L 75 75 75 R 70 R 85 85

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com In the next pass we get the sorted form of the array. 45 50 55 60 65 70 75 80 85

23. For the given graph, draw the DFS and BFS? The given graph:

BFS: DFS:

AXGHPEMYJ AXHPEYMJG

24. Classify the Hashing Functions based on the various methods by which the key value is found. Direct method, Subtraction method, Modulo-Division method, Digit-Extraction method, Mid-Square method, Folding method, Pseudo-random method. 25. What are the types of Collision Resolution Techniques and the methods used in each of the type? Open addressing (closed hashing), The methods used include: Overflow block, Closed addressing (open hashing) The methods used include: Linked list, Binary tree

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com 26. In RDBMS, what is the efficient data structure used in the internal storage representation? B+ tree. Because in B+ tree, all the data is stored only in leaf nodes, that makes searching easier. This corresponds to the records that shall be stored in leaf nodes. 27. Draw the B-tree of order 3 created by inserting the following data arriving in sequence 92 24 6 7 11 8 22 4 5 16 19 20 78
11

19

24

16

20

22

78

92

28.Of the following tree structure, which is, efficient considering space and time complexities?
(a) Incomplete Binary Tree (b) Complete Binary Tree (c) Full Binary Tree (b) Complete Binary Tree. By the method of elimination: Full binary tree loses its nature when operations of insertions and deletions are done. For incomplete binary trees, extra storage is required and overhead of NULL node checking takes place. So complete binary tree is the better one since the property of complete binary tree is maintained even after operations like additions and deletions are done on it. 29. What is a spanning Tree? A spanning tree is a tree associated with a network. All the nodes of the graph appear on the tree once. A minimum spanning tree is a spanning tree organized so that the total edge weight between nodes is minimized. 30. Does the minimum spanning tree of a graph give the shortest distance between any 2 specified nodes? No. Minimal spanning tree assures that the total weight of the tree is kept at its minimum. But it doesnt mean that the distance between any two nodes involved in the minimum-spanning tree is minimum.

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com 31. Convert the given graph with weighted edges to minimal spanning tree.

600

1
612
410 2985

3
310

200

5
400

1421

the equivalent minimal spanning tree is: 1

3 200 612 310 4 5

410 2

32. Which is the simplest file structure? (a) Sequential (b) Indexed (c) Random (a) Sequential 33. Whether Linked List is linear or Non-linear data structure? According to Access strategies Linked list is a linear one. According to Storage Linked List is a Non-linear one. 34. Draw a binary Tree for the expression : A * B - (C + D) * (P / Q) -

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com 35. For the following COBOL code, draw the Binary tree? 01 STUDENT_REC. 02 NAME. 03 FIRST_NAME PIC X(10). 03 LAST_NAME PIC X(10). 02 YEAR_OF_STUDY. 03 FIRST_SEM PIC XX. 03 SECOND_SEM PIC XX. 01 STUDENT_REC

02
NAME

02
YEAR_OF_STUDY

03
FIRST_NAME

03
LAST_NAME

03
FIRST_SEM

03
SECOND_SEM

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com

Freshersworld.com Resource Center

10

Q. Difference between calloc and malloc? A. malloc: allocate n bytes calloc: allocate m times n bytes initialized to 0 Q. What are the major data structures used in the following areas : RDBMS, Network data model & Hierarchical data model. A. 1. RDBMS Array (i.e. Array of structures) 2. Network data model Graph 3. Hierarchical data model Trees. Q. Which file contains the definition of member functions? A. Definitions of member functions for the Linked List class are contained in the LinkedList.cpp file. Q. How is any Data Structure application is classified among files? A. A linked list application can be organized into a header file, source file and main application file. The first file is the header file that contains the definition of the NODE structure and the LinkedList class definition. The second file is a source code file containing the implementation of member functions of the LinkedList class. The last file is the application file that contains code that creates and uses the LinkedList class. Q. What member function places a new node at the end of the linked list? A. The appendNode() member function places a new node at the end of the linked list. The appendNode() requires an integer representing the current data of the node. Q. What is Linked List ? A. Linked List is one of the fundamental data structures. It consists of a sequence of nodes, each containing arbitrary data fields and one or two (links) pointing to the next and/or previous nodes. A linked list is a self-referential datatype because it contains a pointer or link to another data of the same type. Linked lists permit insertion and removal of nodes at any point in the list in constant time, but do not allow random access. Q. What does each entry in the Link List called? A. Each entry in a linked list is called a node. Think of a node as an entry that has three sub entries. One sub entry contains the data, which may be one attribute or many attributes. Another points to the previous node, and the last points to the next node. When you enter a new item on a linked list, you allocate the new node and then set the pointers to previous and next nodes. Q. How is the front of the queue calculated ? A. The front of the queue is calculated by front = (front+1) % size.

Q. Why is the isEmpty() member method called? A. The isEmpty() member method is called within the dequeue process to determine if there is an item in the queue to be removed i.e. isEmpty() is called to decide whether the queue has at least one element. This method is called by the dequeue() method before returning the front element. Q. Which process places data at the back of the queue? A. Enqueue is the process that places data at the back of the queue. Q. What is the relationship between a queue and its underlying array? A. Data stored in a queue is actually stored in an array. Two indexes, front and end will be used to identify the start and end of the queue. When an element is removed front will be incremented by 1. In case it reaches past the last index available it will be reset to 0. Then it will be checked with end. If it is greater than end queue is empty. When an element is added end will be incremented by 1. In case it reaches past the last index available it will be reset to 0. After incrementing it will be checked with front. If they are equal queue is full. Q. What method removes the value from the top of a stack? A. The pop() member method removes the value from the top of a stack, which is then returned by the pop() member method to the statement that calls the pop() member method. Q. What method is used to place a value onto the top of a stack? A. push() method, Push is the direction that data is being added to the stack. push() member method places a value onto the top of a stack. Q. Run Time Memory Allocation is known as. A. Allocating memory at runtime is called a dynamically allocating memory. In this,you dynamically allocate memory by using the new operator when declaring the array, for example:int grades[] = new int[10]; Q. How do you assign an address to an element of a pointer array ? A. We can assign a memory address to an element of a pointer array by using the address operator, which is the ampersand (&), in an assignment statement such as ptemployee[0] = &projects[2];

Q. Why do we Use a Multidimensional Array? A. A multidimensional array can be useful to organize subgroups of data within an array. In addition to organizing data stored in elements of an array, a multidimensional array can store memory addresses of data in a pointer array and an array of pointers. Multidimensional arrays are used to store information in a matrix form. Q. What is significance of * ? A. The symbol * tells the computer that you are declaring a pointer. Actually it depends on context. In a statement like int *ptr; the * tells that you are declaring a pointer. In a statement like int i = *ptr; it tells that you want to assign value pointed to by ptr to variable i. The symbol * is also called as Indirection Operator/ Dereferencing Operator Q. What is Data Structure? A. A data structure is a group of data elements grouped together under one name. These data elements, known as members, can have different types and different lengths. Some are used to store the data of same type and some are used to store different types of data. Q. Is Pointer a variable? A. Yes, a pointer is a variable and can be used as an element of a structure and as an attribute of a class in some programming languages such as C++, but not Java. Q. How many parts are there in a declaration statement? A. There are two main parts, variable identifier and data type and the third type is optional which is type qualifier like signed/unsigned. Q. How memory is reserved using a declaration statement ? A. Memory is reserved using data type in the variable declaration. A programming language implementation has predefined sizes for its data types. For example, in C# the declaration int i; will reserve 32 bits for variable i. Q. What is impact of signed numbers on the memory? A. Sign of the number is the first bit of the storage allocated for that number. So you get one bit less for storing the number. For example if you are storing an 8-bit number, without sign, the range is 0-255. If you decide to store sign you get 7 bits for the number plus one bit for the sign. So the range is -128 to +127

Q. What is precision? A. Precision refers the accuracy of the decimal portion of a value. Precision is the number of digits allowed after the decimal point Q. What is the difference bitween NULL AND VOID pointer? A. NULL can be value for pointer type variables. VOID is a type identifier which has not size. NULL and void are not same. Example: void* ptr = NULL; Q. What is the difference between ARRAY and STACK? A. STACK follows LIFO. Thus the item that is first entered would be the last removed. In array the items can be entered or removed in any order. Basically each member access is done using index. No strict order is to be followed here to remove a particular element. Q. Tell how to check whether a linked list is circular. A. Create two pointers, each set to the start of the list. Update each as follows:
while (pointer1) { pointer1 = pointer1->next; pointer2 = pointer2->next; if (pointer2) pointer2=pointer2->next; if (pointer1 == pointer2) { print (\circular\n\); } }

Q. Whether Linked List is linear or Non-linear data structure? A. According to Access strategies Linked list is a linear one. According to Storage Linked List is a Non-linear one Q. What is the data structures used to perform recursion? A. Stack. Because of its LIFO (Last In First Out) property it remembers its caller so knows whom to return when the function has to return. Recursion makes use of system stack for storing the return addresses of the function calls.Every recursive function has its equivalent iterative (non-recursive) function. Even when such equivalent iterative procedures are written, explicit stack is to be used. Q. If you are using C language to implement the heterogeneous linked list, what pointer type will you use?

A. The heterogeneous linked list contains different data types in its nodes and we need a link, pointer to connect them. It is not possible to use ordinary pointers for this. So we go for void pointer. Void pointer is capable of storing pointer to any type as it is a generic pointer type. Q. List out the areas in which data structures are applied extensively? A. Compiler Design, Operating System, Database Management System, Statistical analysis package, Numerical Analysis, Graphics, Artificial Intelligence, Simulation Q. What is placement new? A. When you want to call a constructor directly, you use the placement new. Sometimes you have some raw memory thats already been allocated, and you need to construct an object in the memory you have. Operator news special version placement new allows you to do it. Q. When can you tell that a memory leak will occur? A. A memory leak occurs when a program loses the ability to free a block of dynamically allocated memory. Q. What is a node class? A. A node class is a class that has added new services or functionality beyond the services inherited from its base class. Q. How many different trees are possible with 10 nodes ? A. 1014 - For example, consider a tree with 3 nodes(n=3), it will have the maximum combination of 5 different (ie, 23 - 3 = 5) Q. Minimum number of queues needed to implement the priority queue? A. Two. One queue is used for actual storing of data and another for storing priorities. Q. In an AVL tree, at what condition the balancing is to be done? A. If the pivotal value (or the Height factor) is greater than 1 or less than 1. Q. What is the bucket size, when the overlapping and collision occur at same time? A. One. If there is only one entry possible in the bucket, when the collision occurs, there is no way to accommodate the colliding value. This results in the overlapping of values. Q. What is the easiest sorting method to use?

A. The answer is the standard library function qsort(). Its the easiest sort by far for several reasons: It is already written. It is already debugged. It has been optimized as much as possible (usually). Void qsort(void *buf, size_t num, size_t size, int (*comp)(const void *ele1, const void *ele2)); Q. What is the heap? A. The heap is where malloc(), calloc(), and realloc() get memory. Getting memory from the heap is much slower than getting it from the stack. On the other hand, the heap is much more flexible than the stack. Memory can be allocated at any time and deallocated in any order. Such memory isnt deallocated automatically; you have to call free(). Q. How can I search for data in a linked list? A. Unfortunately, the only way to search a linked list is with a linear search, because the only way a linked lists members can be accessed is sequentially. Sometimes it is quicker to take the data from a linked list and store it in a different data structure so that searches can be more efficient. Q. What is the quickest sorting method to use? A. The answer depends on what you mean by quickest. For most sorting problems, it just doesnt matter how quick the sort is because it is done infrequently or other operations take significantly more time anyway. Even in cases in which sorting speed is of the essence, there is no one answer. It depends on not only the size and nature of the data, but also the likely order. Q. what is quick short? A. The Quick Sort The quick sort algorithm is of the divide and conquer type. That means it works by reducing a sorting problem into several easier sorting problems and solving each of them. A dividing value is chosen from the input data, and the data is partitioned into three sets: elements that belong before the dividing value, the value itself, and elements that come after the dividing value. The partitioning is performed by exchanging elements that are in the first set but belong in the third with elements that are in the third set but belong in the first Elements that are equal to the dividing element can be put in any of the three setsthe algorithm will still work properly. Q. what is merge short?

A. The Merge Sort The merge sort is a divide and conquer sort as well. It works by considering the data to be sorted as a sequence of already-sorted lists (in the worst case, each list is one element long). Adjacent sorted lists are merged into larger sorted lists until there is a single sorted list containing all the elements. The merge sort is good at sorting lists and other data structures that are not in arrays, and it can be used to sort things that dont fit into memory. It also can be implemented as a stable sort. Q. what is radix short? A. The Radix Sort The radix sort takes a list of integers and puts each element on a smaller list, depending on the value of its least significant byte. Then the small lists are concatenated, and the process is repeated for each more significant byte until the list is sorted. The radix sort is simpler to implement on fixed-length data such as ints. Q. Does the minimum spanning tree of a graph give the shortest distance between any 2 specified nodes? A. Minimal spanning tree assures that the total weight of the tree is kept at its minimum. But it doesnt mean that the distance between any two nodes involved in the minimumspanning tree is minimum. Q. What is a spanning Tree? A. A spanning tree is a tree associated with a network. All the nodes of the graph appear on the tree once. A minimum spanning tree is a spanning tree organized so that the total edge weight between nodes is minimized. Q. In RDBMS, what is the efficient data structure used in the internal storage representation? A. B+ tree. Because in B+ tree, all the data is stored only in leaf nodes, that makes searching easier. This corresponds to the records that shall be stored in leaf nodes. Q. List out few of the Application of tree data-structure? A. The manipulation of Arithmetic expression,Symbol Table construction,Syntax analysis Q. What are the methods available in storing sequential files ? A. Straight merging,Natural merging,Polyphase sort,Distribution of Initial runs Q.

First Job. Dream Job. Freshersworld.com

Technical Questions
1. A 2MB PCM(pulse code modulation) has a) 32 channels b) 30 voice channels & 1 signalling channel. c) 31 voice channels & 1 signalling channel. d) 32 channels out of which 30 voice channels, 1 signalling channel, & 1 Synchronizatio channel. Ans: (c) 2. Time taken for 1 satellite hop in voice communication is a) 1/2 second b) 1 seconds c) 4 seconds d) 2 seconds Ans: (a) 3. Max number of satellite hops allowed in voice communication is : a) only one b) more han one c) two hops d) four hops Ans: (c) 4. What is the max. decimal number that can be accomodated in a byte. a) 128 b) 256 c) 255 d) 512 Ans: (c) 5. Conditional results after execution of an instruction in a micro processor is stored in a) register b) accumulator c) flag register d) flag register part of PSW(Program Status Word) Ans: (d)

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com

6. Frequency at which VOICE is sampled is a) 4 Khz b) 8 Khz c) 16 Khz d) 64 Khz Ans: (a) 7. Line of Sight is a) Straight Line b) Parabolic c) Tx & Rx should be visible to each other d) none Ans: (c) 8. Purpose of PC(Program Counter) in a MicroProcessor is a) To store address of TOS(Top Of Stack) b) To store address of next instruction to be executed. c) count the number of instructions. d) to store base address of the stack. Ans: (b) 9. What action is taken when the processor under execution is interrupted by a non-maskable interrupt? a) Processor serves the interrupt request after completing the execution of the current instruction. b) Processor serves the interupt request after completing the current task. c) Processor serves the interupt request immediately. d) Processor serving the interrupt request depends upon the priority of the current task under execution. Ans: (a) 10. The status of the Kernel is a) task b) process c) not defined. d) none of the above. Ans: (b)

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com


11. To send a data packet using datagram , connection will be established a) before data transmission. b) connection is not established before data transmission. c) no connection is required. d) none of the above. Ans: (c)

12. Word allignment is a) alligning the address to the next word boundary of the machine. b) alligning to even boundary. c) alligning to word boundary. d) none of the above. Ans: (a) 13 When a 'C' function call is made, the order in which parameters passed to the function are pushed into the stack is a) left to right b) right to left c) bigger variables are moved first than the smaller variales. d) smaller variables are moved first than the bigger ones. e) none of the above. Ans: (b) 14 What is the type of signalling used between two exchanges? a) inband b) common channel signalling c) any of the above d) none of the above. Ans: (a) 15 Buffering is a) the process of temporarily storing the data to allow for small variation in device speeds b) a method to reduce cross talks c) storage of data within transmitting medium until the receiver is ready to receive. d) a method to reduce routing overhead. Ans: (a)

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com

16. Memory allocation of variables declared in a program is a) allocated in RAM. b) allocated in ROM. c) allocated on stack. d) assigned to registers. Ans: (c)

17. A software that allows a personal computer to pretend as a computer terminal is a) terminal adapter b) bulletin board c) modem d) terminal emulation Ans: (d) 18. Find the output of the following program int *p,*q; p=(int *)1000; q=(int *)2000; printf("%d",(q-p)); Ans: 500

19. Which addressing mode is used in the following statements: (a) MVI B,55 (b) MOV B,A (c) MOV M,A Ans. (a) Immediate addressing mode. (b) Register Addressing Mode (c) Direct addressing mode

20. RS-232C standard is used in _____________. Ans. Serial I/O

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com

21. Memory. Management in Operating Systems is done by a) Memory Management Unit b) Memory management software of the Operating System c) Kernel Ans: (b)

22. What is done for a Push opertion? Ans: SP is decremented and then the value is stored. 23. Binary equivalent of 52 Ans. 110100 24. Hexadecimal equivalent of 3452 Ans. 72A 25. Explain Just In Time Concept ? Ans. Elimination of waste by purchasing manufacturing exactly when needed 26. A good way of unit testing s/w program is Ans. User test 27. OOT uses Ans. Encapsulated of detect methods 28.EDI useful in Ans. Electronic Transmission 29. MRPII different from MRP Ans. Modular version of man redundant initials 30. Hard disk time for R/W head to move to correct sector Ans. Latency Time
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com

31. The percentage of times a page number bound in associate register is called Ans. Bit ratio 32. Expand MODEM Ans. Modulator and Demodulator 33. RDBMS file system can be defined as Ans. Interrelated 34. Super Key is Ans. Primary key and Attribute 35. Windows 95 supports (a) Multiuser (b) n tasks (c) Both (d) None Ans. (a) 36.In the command scanf, h is used for Ans. Short int 37.A process is defined as Ans. Program in execution 38.A thread is Ans. Detachable unit of executable code) 39.What is the advantage of Win NT over Win 95 Ans. Robust and secure

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com

40.How is memory management done in Win95 Ans. Through paging and segmentation 41.What is meant by polymorphism Ans. Redfinition of a base class method in a derived class 42.What is the essential feature of inheritance Ans. All properties of existing class are derived 43.What does the protocol FTP do Ans. Transfer a file b/w stations with user authentification 44.In the transport layer ,TCP is what type of protocol Ans. Connection oriented 45.Why is a gateway used Ans. To connect incompatible networks 46.How is linked list implemented Ans. By referential structures 47.What method is used in Win95 in multitasking Ans. Non preemptive check 48.What is a semaphore Ans. A method synchronization of multiple processes 49.What is the precedence order from high to low ,of the symbols ( ) ++ / Ans.( ) , ++, /

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com

50.Preorder of A*(B+C)/D-G Ans.*+ABC/-DG 51.What is the efficiency of merge sort Ans. O(n log n) 52.In which layer are routers used Ans.In network layer 53.Which of the following sorting algorithem has average sorting behavior -Bubble sort,merge sort,heap sort,exchange sort Ans. Heap sort 54.In binary search tree which traversal is used for getting ascending order values--Inorder ,post order,preorder Ans.Inorder 55.What are device drivers used for Ans.To provide software for enabling the hardware 56.What is fork command in unix Ans. System call used to create process 57.What is make command in unix Ans. Used forcreation of more than one file 58.In unix .profile contains Ans. Start up program 59.In unix 'ls 'stores contents in Ans.inode block

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com

60. Which of the following involves context switch, (a) system call (b) priviliged instruction (c) floating poitnt exception (d) all the above (e) none of the above Ans: (a)

61. In OST, terminal emulation is done in (a) sessions layer (b) application layer (c) presentation layer (d) transport layer Ans: (b) 62. For 1 MB memory, the number of address lines required, (a)11 (b)16 (c)22 (d) 24 Ans. (b) 63. Semaphore is used for (a) synchronization (b) dead-lock avoidence (c) box (d) none Ans. (a) 64. Which holds true for the following statement class c: public A, public B a) 2 member in class A, B should not have same name b) 2 member in class A, C should not have same name c) both d) none Ans. (a)

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com


65.Preproconia.. does not do which one of the following (a) macro (b) conditional compliclation (c) in type checking (d) including load file Ans. (c)

66. Piggy backing is a technique for a) Flow control b) Sequence c) Acknowledgement d) retransmition Ans. (c)

67. Which is not a memory management scheme? a) buddy system b) swapping c) monitors d) paging Ans : c 68. There was a circuit given using three nand gates with two inputs and one output. Find the output. a) OR b) AND c) XOR d) NOT Ans. (a)

69.Iintegrated check value(ICV) are used as: Ans. The client computes the ICV and then compares it with the senders value. 70. When applets are downloaded from web sites , a byte verifier performs _________? Ans. Status check.

Freshersworld.com Resource Center

10

First Job. Dream Job. Freshersworld.com


71. An IP/IPX packet received by a computer using... having IP/IPX both how the packet is handled. Ans. Read the, field in the packet header with to send IP or IPX protocol. 72. The UNIX shell .... a) does not come with the rest of the system b) forms the interface between the user and the kernal c) does not give any scope for programming d) deos not allow calling one program from with in another e) all of the above Ans. (b) 73. In UNIX a files i-node ......? Ans. Is a data structure that defines all specifications of a file like the file size, number of lines to a file, permissions etc. 74. The very first process created by the kernal that runs till the kernal process is halts is a) init b) getty c) both (a) and (b) d) none of these Ans. (a) 75. In the process table entry for the kernel process, the process id value is (a) 0 (b) 1 (c) 2 (d) 255 (e) it does not have a process table entry Ans. (a)

76. Which of the following API is used to hide a window a) ShowWindow b) EnableWindow c) MoveWindow d) SetWindowPlacement e) None of the above Ans. (a)

Freshersworld.com Resource Center

11

First Job. Dream Job. Freshersworld.com


77. Which function is the entry point for a DLL in MS Windows 3.1 a) Main b) Winmain c) Dllmain d) Libmain e) None Ans. (b) 78. The standard source for standard input, standard output and standard error is a) the terminal b) /dev/null c) /usr/you/input, /usr/you/output/, /usr/you/error respectively d) None Ans. (a) 79. The redirection operators > and >> a) do the same function b) differ : > overwrites, while >> appends c) differ : > is used for input while >> is used for output d) differ : > write to any file while >> write only to standard output e) None of these Ans. (b) 80. The command grep first second third /usr/you/myfile a) prints lines containing the words first, second or third from the file /usr/you/myfile b) searches for lines containing the pattern first in the files second, third, and /usr/you/myfile and prints them c) searches the files /usr/you/myfiel and third for lines containing the words first or second and prints them d) replaces the word first with the word second in the files third and /usr/you/myfile e) None of the above Ans. (b) 81. You are creating a Index on EMPNO column in the EMPLOYEE table. Which statement will you use? a) CREATE INdEX emp_empno_idx ON employee, empno; b) CREATE INdEX emp_empno_idx FOR employee, empno; c) CREATE INdEX emp_empno_idx ON employee(empno); d) CREATE emp_empno_idx INdEX ON employee(empno); Ans. c
Freshersworld.com Resource Center

12

First Job. Dream Job. Freshersworld.com

82. Which program construct must return a value? a) Package b) Function c) Anonymous block d) Stored Procedure e) Application Procedure Ans. b

83. Which Statement would you use to remove the EMPLOYEE_Id_PK PRIMARY KEY constraint and all depending constraints fromthe EMPLOYEE table? a) ALTER TABLE employee dROP PRIMARY KEY CASCAdE; b) ALTER TABLE employee dELETE PRIMARY KEY CASCAdE; c) MOdIFY TABLE employee dROP CONSTRAINT employee_id_pk CASCAdE; d) ALTER TABLE employee dROP PRIMARY KEY employee_id_pk CASCAdE; e) MOdIFY TABLE employee dELETE PRIMARY KEY employee_id_pk CASCAdE; Ans. a

84. Which three commands cause a transaction to end? (Chosse three) a) ALTER b) GRANT c) DELETE d) INSERT e) UPdATE f) ROLLBACK Ans. a ,b ,f 85. Under which circumstance should you create an index on a table? a) The table is small. b) The table is updated frequently. c) A columns values are static and contain a narrow range of values d) Two columns are consistently used in the WHERE clause join condition of SELECT statements. Ans.d 86. What was the first name given to Java Programming Language. a) Oak - Java b) Small Talk c) Oak d) None Ans.a

Freshersworld.com Resource Center

13

First Job. Dream Job. Freshersworld.com 87.When a bicycle is in motion,the force of friction exerted by the ground on the two wheels is such that it acts (a) In the backward direction on the front wheel and in the forward direction on the rear wheel. (b) In the forward direction on the front wheel and in the backward direction on the rear wheel. (c) In the backward direction on both the front and rear wheels. (d) In the backward direction on both the front and rear wheels. Ans. (d)

88. A certain radioactive element A, has a half life = t seconds. In (t/2) seconds the fraction of the initial quantity of the element so far decayed is nearly (a) 29% (b) 15% (c) 10% (d) 45% Ans. (a)

89. Which of the following plots would be a straight line ? (a) Logarithm of decay rate against logarithm of time (b) Logarithm of decay rate against logarithm of number of decaying nuclei (c) Decay rate against time (d) Number of decaying nuclei against time Ans. (b)

90. A radioactive element x has an atomic number of 100. It decays directly into an element y which decays directly into element z. In both processes a charged particle is emitted. Which of the following statements would be true? (a) y has an atomic number of 102 (b) y has an atomic number of 101 (c) z has an atomic number of 100 (d) z has an atomic number of 101 Ans. (b)
Freshersworld.com Resource Center

14

First Job. Dream Job. Freshersworld.com

91. If the sum of the roots of the equation ax2 + bx + c=0 is equal to the sum of the squares of their reciprocals then a/c, b/a, c/b are in (a) AP (b) GP (c) HP (d) None of these Ans. (c)

92. A man speaks the truth 3 out of 4 times. He throws a die and reports it to be a 6. What is the probability of it being a 6? (a) 3/8 (b) 5/8 (c) 3/4 (d) None of the above Ans. (a) 93. If cos2A + cos2B + cos2C = 1 then ABC is a (a) Right angle triangle (b) Equilateral triangle (c) All the angles are acute (d) None of these Ans. (a)

94. Image of point (3,8) in the line x + 3y = 7 is (a) (-1,-4) (b) (-1,4) (c) (2,-4) (d) (-2,-4) Ans. (a)

Freshersworld.com Resource Center

15

First Job. Dream Job. Freshersworld.com

95. The mass number of a nucleus is (a) Always less than its atomic number (b) Always more than its atomic number (c) Sometimes more than and sometimes equal to its atomic number (d) None of the above Ans. (c)

96. The maximum KE of the photoelectron emitted from a surface is dependent on (a) The intensity of incident radiation (b) The potential of the collector electrode (c) The frequency of incident radiation (d) The angle of incidence of radiation of the surface Ans. (c)

97. Which of the following is not an essential condition for interference (a) The two interfering waves must be propagated in almost the same direction or the two interfering waves must intersect at a very small angle (b) The waves must have the same time period and wavelength (c) Amplitude of the two waves should be the same (d) The interfering beams of light must originate from the same source Ans. (c)

98. When X-Ray photons collide with electrons (a) They slow down (b) Their mass increases (c) Their wave length increases (d) Their energy decreases Ans. (c)

Freshersworld.com Resource Center

16

First Job. Dream Job. Freshersworld.com

99. An electron emits energy (a) Because its in orbit (b) When it jumps from one energy level to another (c) Electrons are attracted towards the nucleus (d) The electrostatic force is insufficient to hold the electrons in orbits Ans. (b)

100. How many bonds are present in CO2 molecule? (a) 1 (b) 2 (c) 0 (d) 4 Ans. (d)

Freshersworld.com Resource Center

17

Face Interviews Confidently!

Table of Contents

Data Structures Aptitude............................................................................. 3 C Aptitude.................................................................................................. 12 C++ Aptitude and OOPS ............................................................................ 75 Quantitative Aptitude .............................................................................. 104 UNIX Concepts......................................................................................... 122 RDBMS Concepts....................................... Error! Bookmark not defined. SQL............................................................ Error! Bookmark not defined. Computer Networks................................................................................. 136 Operating Systems .................................................................................. 144

Data Structures Aptitude


Data Structures Aptitude
1. What is data structure? A data structure is a way of organizing data that considers not only the items stored, but also their relationship to each other. Advance knowledge about the relationship between data items allows designing of efficient algorithms for the manipulation of data. 2. List out the areas in which data structures are applied extensively? Compiler Design, Operating System, Database Management System, Statistical analysis package, Numerical Analysis, Graphics, Artificial Intelligence, Simulation

3. What are the major data structures used in the following areas : RDBMS, Network data model & Hierarchical data model. RDBMS Array (i.e. Array of structures) Network data model Graph Hierarchical data model Trees 4. If you are using C language to implement the heterogeneous linked list, what pointer type will you use? The heterogeneous linked list contains different data types in its nodes and we need a link, pointer to connect them. It is not possible to use ordinary pointers for this. So we go for void pointer. Void pointer is capable of storing pointer to any type as it is a generic pointer type. 5. Minimum number of queues needed to implement the priority queue? Two. One queue is used for actual storing of data and another for storing priorities. 6. What is the data structures used to perform recursion?

Stack. Because of its LIFO (Last In First Out) property it remembers its caller so knows whom to return when the function has to return. Recursion makes use of system stack for storing the return addresses of the function calls. Every recursive function has its equivalent iterative (non-recursive) function. Even when such equivalent iterative procedures are written, explicit stack is to be used. 7. What are the notations used in Evaluation of Arithmetic Expressions using prefix and postfix forms? Polish and Reverse Polish notations. 8. Convert the expression ((A + B) * C (D E) ^ (F + G)) to equivalent Prefix and Postfix notations. Prefix Notation: ^ - * +ABC - DE + FG Postfix Notation: AB + C * DE - - FG + ^ 9. Sorting is not possible by using which of the following methods? (a) Insertion (b) Selection (c) Exchange (d) Deletion (d) Deletion. Using insertion we can perform insertion sort, using selection we can perform selection sort, using exchange we can perform the bubble sort (and other similar sorting methods). But no sorting method can be done just using deletion. 10. A binary tree with 20 nodes has null branches? 21 Let us take a tree with 5 nodes (n=5)

Null Branches

It will have only 6 (ie,5+1) null branches. In general, A binary tree with n nodes has exactly n+1 null nodes. 11. What are the methods available in storing sequential files ? Straight merging,

Natural merging, Polyphase sort, Distribution of Initial runs. 12. How many different trees are possible with 10 nodes ? 1014 For example, consider a tree with 3 nodes(n=3), it will have the maximum combination of 5 different (ie, 23 - 3 = 5) trees.

ii

iii

iv

In general: If there are n nodes, there exist 2n-n different trees. 13. List out few of the Application of tree data-structure? The manipulation of Arithmetic expression, Symbol Table construction, Syntax analysis. 14. List out few of the applications that make use of Multilinked Structures? Sparse matrix, Index generation. 15. In tree construction which is the suitable efficient data structure? (a) Array (b) Linked list (c) Stack (d) Queue (e) none (b) Linked list 16. What is the type of the algorithm used in solving the 8 Queens problem? Backtracking 17. In an AVL tree, at what condition the balancing is to be done? If the pivotal value (or the Height factor) is greater than 1 or less than 1. 18. What is the bucket size, when the overlapping and collision occur at same time?

One. If there is only one entry possible in the bucket, when the collision occurs, there is no way to accommodate the colliding value. This results in the overlapping of values. 19. Traverse the given tree using Inorder, Preorder and Postorder traversals. Given tree:
A

Inorder : D H B E A F C I G J Preorder: A B D H E C F G I J Postorder: H D E B F I J G C A 20. There are 8, 15, 13, 14 nodes were there in 4 different trees. Which of them could have formed a full binary tree? 15. In general: There are 2n-1 nodes in a full binary tree. By the method of elimination: Full binary trees contain odd number of nodes. So there cannot be full binary trees with 8 or 14 nodes, so rejected. With 13 nodes you can form a complete binary tree but not a full binary tree. So the correct answer is 15. Note: Full and Complete binary trees are different. All full binary trees are complete binary trees but not vice versa. 21. In the given binary tree, using array you can store the node 4 at which location? 1

At location 6

1 Root

2 LC1

3 RC1

LC2

RC2

4 LC3

RC3

LC4

5 RC4

where LCn means Left Child of node n and RCn means Right Child of node n 22. Sort the given values using Quick Sort?

65

70

75

80

85

60

55

50

45

Sorting takes place from the pivot value, which is the first value of the given elements, this is marked bold. The values at the left pointer and right pointer are indicated using L and R respectively. 65 70L 75 80 85 60 55 50 45R

Since pivot is not yet changed the same process is continued after interchanging the values at L and R positions 65 65 65 45 45 45 75 L 50 50 80 80 L 55 85 85 85 L 60 R 60 60 60 R 85 L 55 55 R 80 50 R 75 75 70 70 70

65

45

50

55

80

75

70

When the L and R pointers cross each other the pivot value is interchanged with the value at right pointer. If the pivot is changed it means that the pivot has occupied its original position in the sorted order (shown in bold italics) and hence two different arrays are formed, one from start of the original array to the pivot position-1 and the other from pivot position+1 to end. 60 L 45 50 55 R 65 85 L 80 75 70 R

55 L 50 L

45 45 R

50 R 55

60 60

65 65

70 R 70

80 L 80 L

75 75 R

85 85

In the next pass we get the sorted form of the array. 45 50 55 60 65 70 75 80 85

23. For the given graph, draw the DFS and BFS? The given graph:

BFS: DFS:

AXGHPEMYJ AXHPEYMJG

24. Classify the Hashing Functions based on the various methods by which the key value is found. Direct method, Subtraction method, Modulo-Division method, Digit-Extraction method, Mid-Square method, Folding method, Pseudo-random method. 25. What are the types of Collision Resolution Techniques and the methods used in each of the type? Open addressing (closed hashing), The methods used include: Overflow block, Closed addressing (open hashing) The methods used include: Linked list,

Binary tree 26. In RDBMS, what is the efficient data structure used in the internal storage representation? B+ tree. Because in B+ tree, all the data is stored only in leaf nodes, that makes searching easier. This corresponds to the records that shall be stored in leaf nodes. 27. Draw the B-tree of order 3 created by inserting the following data arriving in sequence 92 24 6 7 11 8 22 4 5 16 19 20 78
11

19

24

16

20

22

78

92

28.Of the following tree structure, which is, efficient considering space and time complexities?
(a) Incomplete Binary Tree (b) Complete Binary Tree (c) Full Binary Tree (b) Complete Binary Tree. By the method of elimination: Full binary tree loses its nature when operations of insertions and deletions are done. For incomplete binary trees, extra storage is required and overhead of NULL node checking takes place. So complete binary tree is the better one since the property of complete binary tree is maintained even after operations like additions and deletions are done on it. 29. What is a spanning Tree? A spanning tree is a tree associated with a network. All the nodes of the graph appear on the tree once. A minimum spanning tree is a spanning tree organized so that the total edge weight between nodes is minimized. 30. Does the minimum spanning tree of a graph give the shortest distance between any 2 specified nodes? No. Minimal spanning tree assures that the total weight of the tree is kept at its minimum. But it doesnt mean that the distance between any two nodes involved in the minimum-spanning tree is minimum.

31. Convert the given graph with weighted edges to minimal spanning tree.

600

1
612
410 2985

3
310

200

5
400

1421

the equivalent minimal spanning tree is: 1

3 200 612 310 4 5

410 2

32. Which is the simplest file structure? (a) Sequential (b) Indexed (c) Random (a) Sequential 33. Whether Linked List is linear or Non-linear data structure? According to Access strategies Linked list is a linear one. According to Storage Linked List is a Non-linear one. 34. Draw a binary Tree for the expression : A * B - (C + D) * (P / Q) -

35. For the following COBOL code, draw the Binary tree? 01 STUDENT_REC. 02 NAME. 03 FIRST_NAME PIC X(10). 03 LAST_NAME PIC X(10). 02 YEAR_OF_STUDY. 03 FIRST_SEM PIC XX. 03 SECOND_SEM PIC XX. 01 STUDENT_REC

02
NAME

02
YEAR_OF_STUDY

03
FIRST_NAME

03
LAST_NAME

03
FIRST_SEM

03
SECOND_SEM

C Aptitude

C Aptitude
Note : All the programs are tested under Turbo C/C++ compilers. It is assumed that, Programs run under DOS environment, The underlying machine is an x86 system, Program is compiled using Turbo C/C++ compiler. The program output may depend on the information based on this assumptions (for example sizeof(int) == 2 may be assumed). Predict the output or error(s) for the following: 1. void main() { int const * p=5; printf("%d",++(*p)); } Answer: Compiler error: Cannot modify a constant value. Explanation: p is a pointer to a "constant integer". But we tried to change the value of the "constant integer". 2. main() { char s[ ]="man"; int i; for(i=0;s[ i ];i++) printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]); } Answer: mmmm aaaa nnnn Explanation: s[i], *(i+s), *(s+i), i[s] are all different ways of expressing the same idea. Generally array name is the base address for that array. Here s is the base address. i is the

index number/displacement from the base address. So, indirecting it with * is same as s[i]. i[s] may be surprising. But in the case of C it is same as s[i]. 3. main() { float me = 1.1; double you = 1.1; if(me==you) printf("I love U"); else printf("I hate U"); } Answer: I hate U Explanation: For floating point numbers (float, double, long double) the values cannot be predicted exactly. Depending on the number of bytes, the precession with of the value represented varies. Float takes 4 bytes and long double takes 10 bytes. So float stores 0.9 with less precision than long double. Rule of Thumb: Never compare or at-least be cautious when using floating point numbers with relational operators (== , >, <, <=, >=,!= ) . 4. main() { static int var = 5; printf("%d ",var--); if(var) main(); } Answer: 54321 Explanation: When static storage class is given, it is initialized once. The change in the value of a static variable is retained even between the function calls. Main is also treated like any other ordinary function, which can be called recursively. 5. main() { int c[ ]={2.8,3.4,4,6.7,5}; int j,*p=c,*q=c; for(j=0;j<5;j++) { printf(" %d ",*c); ++q; } for(j=0;j<5;j++){ printf(" %d ",*p); ++p; }

} Answer: 2222223465 Explanation: Initially pointer c is assigned to both p and q. In the first loop, since only q is incremented and not c , the value 2 will be printed 5 times. In second loop p itself is incremented. So the values 2 3 4 6 5 will be printed. 6. main() { extern int i; i=20; printf("%d",i); } Answer: Linker Error : Undefined symbol '_i' Explanation: extern storage class in the following declaration, extern int i; specifies to the compiler that the memory for i is allocated in some other program and that address will be given to the current program at the time of linking. But linker finds that no other variable of name i is available in any other program with memory space allocated for it. Hence a linker error has occurred . 7. main() { int i=-1,j=-1,k=0,l=2,m; m=i++&&j++&&k++||l++; printf("%d %d %d %d %d",i,j,k,l,m); } Answer: 00131 Explanation : Logical operations always give a result of 1 or 0 . And also the logical AND (&&) operator has higher priority over the logical OR (||) operator. So the expression i++ && j++ && k++ is executed first. The result of this expression is 0 (-1 && -1 && 0 = 0). Now the expression is 0 || 2 which evaluates to 1 (because OR operator always gives 1 except for 0 || 0 combination- for which it gives 0). So the value of m is 1. The values of other variables are also incremented by 1. 8. main() { char *p; printf("%d %d ",sizeof(*p),sizeof(p));

} Answer: 12 Explanation: The sizeof() operator gives the number of bytes taken by its operand. P is a character pointer, which needs one byte for storing its value (a character). Hence sizeof(*p) gives a value of 1. Since it needs two bytes to store the address of the character pointer sizeof(p) gives 2. 9. main() { int i=3; switch(i) { default:printf("zero"); case 1: printf("one"); break; case 2:printf("two"); break; case 3: printf("three"); break; } } Answer : three Explanation : The default case can be placed anywhere inside the loop. It is executed only when all other cases doesn't match. 10. main() { printf("%x",-1<<4); } Answer: fff0 Explanation : -1 is internally represented as all 1's. When left shifted four times the least significant 4 bits are filled with 0's.The %x format specifier specifies that the integer value be printed as a hexadecimal value. 11. main() { char string[]="Hello World"; display(string); }

void display(char *string) { printf("%s",string); } Answer: Compiler Error : Type mismatch in redeclaration of function display Explanation : In third line, when the function display is encountered, the compiler doesn't know anything about the function display. It assumes the arguments and return types to be integers, (which is the default type). When it sees the actual function display, the arguments and type contradicts with what it has assumed previously. Hence a compile time error occurs. 12. main() { int c=- -2; printf("c=%d",c); } Answer: c=2; Explanation: Here unary minus (or negation) operator is used twice. Same maths rules applies, ie. minus * minus= plus. Note: However you cannot give like --2. Because -- operator can only be applied to variables as a decrement operator (eg., i--). 2 is a constant and not a variable. 13. #define int char main() { int i=65; printf("sizeof(i)=%d",sizeof(i)); } Answer: sizeof(i)=1 Explanation: Since the #define replaces the string int by the macro char 14. main() { int i=10; i=!i>14; printf("i=%d",i); } Answer: i=0

Explanation: In the expression !i>14 , NOT (!) operator has more precedence than > symbol. ! is a unary logical operator. !i (!10) is 0 (not of true is false). 0>14 is false (zero). 15. #include<stdio.h> main() { char s[]={'a','b','c','\n','c','\0'}; char *p,*str,*str1; p=&s[3]; str=p; str1=s; printf("%d",++*p + ++*str1-32); } Answer: 77 Explanation: p is pointing to character '\n'. str1 is pointing to character 'a' ++*p. "p is pointing to '\n' and that is incremented by one." the ASCII value of '\n' is 10, which is then incremented to 11. The value of ++*p is 11. ++*str1, str1 is pointing to 'a' that is incremented by 1 and it becomes 'b'. ASCII value of 'b' is 98. Now performing (11 + 98 32), we get 77("M"); So we get the output 77 :: "M" (Ascii is 77). 16. #include<stdio.h> main() { int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} }; int *p,*q; p=&a[2][2][2]; *q=***a; printf("%d----%d",*p,*q); } Answer: SomeGarbageValue---1 Explanation: p=&a[2][2][2] you declare only two 2D arrays, but you are trying to access the third 2D(which you are not declared) it will print garbage values. *q=***a starting address of a is assigned integer pointer. Now q is pointing to starting address of a. If you print *q, it will print first element of 3D array. 17. #include<stdio.h> main()

{ struct xx { int x=3; char name[]="hello"; }; struct xx *s; printf("%d",s->x); printf("%s",s->name); } Answer: Compiler Error Explanation: You should not initialize variables in declaration 18. #include<stdio.h> main() { struct xx { int x; struct yy { char s; struct xx *p; }; struct yy *q; }; } Answer: Compiler Error Explanation: The structure yy is nested within structure xx. Hence, the elements are of yy are to be accessed through the instance of structure xx, which needs an instance of yy to be known. If the instance is created after defining the structure the compiler will not know about the instance relative to xx. Hence for nested structure yy you have to declare member. 19. main() { printf("\nab"); printf("\bsi"); printf("\rha"); } Answer: hai

Explanation: \n - newline \b - backspace \r - linefeed 20. main() { int i=5; printf("%d%d%d%d%d%d",i++,i--,++i,--i,i); } Answer: 45545 Explanation: The arguments in a function call are pushed into the stack from left to right. The evaluation is by popping out from the stack. and the evaluation is from right to left, hence the result. 21. #define square(x) x*x main() { int i; i = 64/square(4); printf("%d",i); } Answer: 64 Explanation: the macro call square(4) will substituted by 4*4 so the expression becomes i = 64/4*4 . Since / and * has equal priority the expression will be evaluated as (64/4)*4 i.e. 16*4 = 64 22. main() { char *p="hai friends",*p1; p1=p; while(*p!='\0') ++*p++; printf("%s %s",p,p1); } Answer: ibj!gsjfoet Explanation: ++*p++ will be parse in the given order *p that is value at the location currently pointed by p will be taken ++*p the retrieved value will be incremented when ; is encountered the location will be incremented that is p++ will be executed

Hence, in the while loop initial value pointed by p is h, which is changed to i by executing ++*p and pointer moves to point, a which is similarly changed to b and so on. Similarly blank space is converted to !. Thus, we obtain value in p becomes ibj!gsjfoet and since p reaches \0 and p1 points to p thus p1doesnot print anything. 23. #include <stdio.h> #define a 10 main() { #define a 50 printf("%d",a); } Answer: 50 Explanation: The preprocessor directives can be redefined anywhere in the program. So the most recently assigned value will be taken. 24. #define clrscr() 100 main() { clrscr(); printf("%d\n",clrscr()); } Answer: 100 Explanation: Preprocessor executes as a seperate pass before the execution of the compiler. So textual replacement of clrscr() to 100 occurs.The input program to compiler looks like this : main() { 100; printf("%d\n",100); } Note: 100; is an executable statement but with no action. So it doesn't give any problem 25. main() { printf("%p",main); } Answer: Some address will be printed. Explanation:

Function names are just addresses (just like array names are addresses). main() is also a function. So the address of function main will be printed. %p in printf specifies that the argument is an address. They are printed as hexadecimal numbers. 27) main() { clrscr(); } clrscr(); Answer: No output/error Explanation: The first clrscr() occurs inside a function. So it becomes a function call. In the second clrscr(); is a function declaration (because it is not inside any function). 28) enum colors {BLACK,BLUE,GREEN} main() { printf("%d..%d..%d",BLACK,BLUE,GREEN); return(1); } Answer: 0..1..2 Explanation: enum assigns numbers starting from 0, if not explicitly defined. 29) void main() { char far *farther,*farthest; printf("%d..%d",sizeof(farther),sizeof(farthest)); } Answer: 4..2 Explanation: the second pointer is of char type and not a far pointer 30) main() { int i=400,j=300; printf("%d..%d");

} Answer: 400..300 Explanation: printf takes the values of the first two assignments of the program. Any number of printf's may be given. All of them take only the first two values. If more number of assignments given in the program,then printf will take garbage values. 31) main() { char *p; p="Hello"; printf("%c\n",*&*p); } Answer: H Explanation: * is a dereference operator & is a reference operator. They can be applied any number of times provided it is meaningful. Here p points to the first character in the string "Hello". *p dereferences it and so its value is H. Again & references it to an address and * dereferences it to the value H. main() { int i=1; while (i<=5) { printf("%d",i); if (i>2) goto here; i++; } } fun() { here: printf("PP"); } Answer: Compiler error: Undefined label 'here' in function main Explanation: Labels have functions scope, in other words The scope of the labels is limited to functions . The label 'here' is available in function fun() Hence it is not visible in function main.

32)

33)

main() { static char names[5][20]={"pascal","ada","cobol","fortran","perl"}; int i; char *t; t=names[3]; names[3]=names[4]; names[4]=t; for (i=0;i<=4;i++) printf("%s",names[i]); } Answer: Compiler error: Lvalue required in function main Explanation: Array names are pointer constants. So it cannot be modified. void main() { int i=5; printf("%d",i++ + ++i); } Answer: Output Cannot be predicted exactly. Explanation: Side effects are involved in the evaluation of i void main() { int i=5; printf("%d",i+++++i); } Answer: Compiler Error Explanation: The expression i+++++i is parsed as i ++ ++ + i which is an illegal combination of operators. #include<stdio.h> main() { int i=1,j=2; switch(i) { case 1: printf("GOOD"); break;

34)

35)

36)

case j: printf("BAD"); break; } } Answer: Compiler Error: Constant expression required in function main. Explanation: The case statement can have only constant expressions (this implies that we cannot use variable names directly so an error). Note: Enumerated types can be used in case statements. 37) main() { int i; printf("%d",scanf("%d",&i)); // value 10 is given as input here } Answer: 1 Explanation: Scanf returns number of items successfully read and not 1/0. Here 10 is given as input which should have been scanned successfully. So number of items read is 1. #define f(g,g2) g##g2 main() { int var12=100; printf("%d",f(var,12)); } Answer: 100 main() { int i=0; for(;i++;printf("%d",i)) ; printf("%d",i); } Answer: 1 Explanation: before entering into the for loop the checking condition is "evaluated". Here it evaluates to 0 (false) and comes out of the loop, and i is incremented (note the semicolon after the for loop).

38)

39)

40)

#include<stdio.h> main() { char s[]={'a','b','c','\n','c','\0'}; char *p,*str,*str1; p=&s[3]; str=p; str1=s; printf("%d",++*p + ++*str1-32); } Answer: M Explanation: p is pointing to character '\n'.str1 is pointing to character 'a' ++*p meAnswer:"p is pointing to '\n' and that is incremented by one." the ASCII value of '\n' is 10. then it is incremented to 11. the value of ++*p is 11. ++*str1 meAnswer:"str1 is pointing to 'a' that is incremented by 1 and it becomes 'b'. ASCII value of 'b' is 98. both 11 and 98 is added and result is subtracted from 32. i.e. (11+98-32)=77("M"); #include<stdio.h> main() { struct xx { int x=3; char name[]="hello"; }; struct xx *s=malloc(sizeof(struct xx)); printf("%d",s->x); printf("%s",s->name); } Answer: Compiler Error Explanation: Initialization should not be done for structure members inside the structure declaration #include<stdio.h> main() { struct xx { int x;

41)

42)

struct yy { char s; struct xx *p; }; struct yy *q; }; } Answer: Compiler Error Explanation: in the end of nested structure yy a member have to be declared. 43) main() { extern int i; i=20; printf("%d",sizeof(i)); } Answer: Linker error: undefined symbol '_i'. Explanation: extern declaration specifies that the variable i is defined somewhere else. The compiler passes the external variable to be resolved by the linker. So compiler doesn't find an error. During linking the linker searches for the definition of i. Since it is not found the linker flags an error. main() { printf("%d", out); } int out=100; Answer: Compiler error: undefined symbol out in function main. Explanation: The rule is that a variable is available for use from the point of declaration. Even though a is a global variable, it is not available for main. Hence an error. main() { extern out; printf("%d", out); } int out=100; Answer:

44)

45)

100 Explanation: This is the correct way of writing the previous program. 46) main() { show(); } void show() { printf("I'm the greatest"); } Answer: Compier error: Type mismatch in redeclaration of show. Explanation: When the compiler sees the function show it doesn't know anything about it. So the default return type (ie, int) is assumed. But when compiler sees the actual definition of show mismatch occurs since it is declared as void. Hence the error. The solutions are as follows: 1. declare void show() in main() . 2. define show() before main(). 3. declare extern void show() before the use of show(). main( ) { int a[2][3][2] = {{{2,4},{7,8},{3,4}},{{2,2},{2,3},{3,4}}}; printf(%u %u %u %d \n,a,*a,**a,***a); printf(%u %u %u %d \n,a+1,*a+1,**a+1,***a+1); } Answer: 100, 100, 100, 2 114, 104, 102, 3 Explanation: The given array is a 3-D one. It can also be viewed as a 1-D array. 2 4 7 8 3 4 2 2 2 3 3 4 100 102 104 106 108 110 112 114 116 118 120 122 thus, for the first printf statement a, *a, **a give address of first element . since the indirection ***a gives the value. Hence, the first line of the output. for the second printf a+1 increases in the third dimension thus points to value at 114, *a+1 increments in second dimension thus points to 104, **a +1 increments the first dimension thus points to 102 and ***a+1 first gets the value at first location and then increments it by 1. Hence, the output.

47)

48)

main( ) { int a[ ] = {10,20,30,40,50},j,*p; for(j=0; j<5; j++) { printf(%d ,*a); a++; } p = a; for(j=0; j<5; j++) { printf(%d ,*p); p++; } } Answer: Compiler error: lvalue required. Explanation: Error is in line with statement a++. The operand must be an lvalue and may be of any of scalar type for the any operator, array name only when subscripted is an lvalue. Simply array name is a non-modifiable lvalue.

49)

main( ) { static int a[ ] = {0,1,2,3,4}; int *p[ ] = {a,a+1,a+2,a+3,a+4}; int **ptr = p; ptr++; printf(\n %d %d %d, ptr-p, *ptr-a, **ptr); *ptr++; printf(\n %d %d %d, ptr-p, *ptr-a, **ptr); *++ptr; printf(\n %d %d %d, ptr-p, *ptr-a, **ptr); ++*ptr; printf(\n %d %d %d, ptr-p, *ptr-a, **ptr); } Answer: 111 222 333 344 Explanation: Let us consider the array and the two pointers with some address a

0 100

1 102

2 104

3 106

4 108 p

100 102 104 106 108 1000 1002 1004 1006 1008 ptr 1000 2000 After execution of the instruction ptr++ value in ptr becomes 1002, if scaling factor for integer is 2 bytes. Now ptr p is value in ptr starting location of array p, (1002 1000) / (scaling factor) = 1, *ptr a = value at address pointed by ptr starting value of array a, 1002 has a value 102 so the value is (102 100)/(scaling factor) = 1, **ptr is the value stored in the location pointed by the pointer of ptr = value pointed by value pointed by 1002 = value pointed by 102 = 1. Hence the output of the firs printf is 1, 1, 1. After execution of *ptr++ increments value of the value in ptr by scaling factor, so it becomes1004. Hence, the outputs for the second printf are ptr p = 2, *ptr a = 2, **ptr = 2. After execution of *++ptr increments value of the value in ptr by scaling factor, so it becomes1004. Hence, the outputs for the third printf are ptr p = 3, *ptr a = 3, **ptr = 3. After execution of ++*ptr value in ptr remains the same, the value pointed by the value is incremented by the scaling factor. So the value in array p at location 1006 changes from 106 10 108,. Hence, the outputs for the fourth printf are ptr p = 1006 1000 = 3, *ptr a = 108 100 = 4, **ptr = 4. 50) main( ) { char *q; int j; for (j=0; j<3; j++) scanf(%s ,(q+j)); for (j=0; j<3; j++) printf(%c ,*(q+j)); for (j=0; j<3; j++) printf(%s ,(q+j)); } Explanation: Here we have only one pointer to type char and since we take input in the same pointer thus we keep writing over in the same location, each time shifting the pointer value by 1. Suppose the inputs are MOUSE, TRACK and VIRTUAL. Then for the first input suppose the pointer starts at location 100 then the input one is stored as M O U S E \0 When the second input is given the pointer is incremented as j value becomes 1, so the input is filled in memory starting from 101. M T R A C K \0 The third input starts filling from the location 102

M T V I R T U A L \0 This is the final value stored . The first printf prints the values at the position q, q+1 and q+2 = M T V The second printf prints three strings starting from locations q, q+1, q+2 i.e MTVIRTUAL, TVIRTUAL and VIRTUAL. 51) main( ) { void *vp; char ch = g, *cp = goofy; int j = 20; vp = &ch; printf(%c, *(char *)vp); vp = &j; printf(%d,*(int *)vp); vp = cp; printf(%s,(char *)vp + 3); } Answer: g20fy Explanation: Since a void pointer is used it can be type casted to any other type pointer. vp = &ch stores address of char ch and the next statement prints the value stored in vp after type casting it to the proper data type pointer. the output is g. Similarly the output from second printf is 20. The third printf statement type casts it to print the string from the 4th value hence the output is fy. main ( ) { static char *s[ ] = {black, white, yellow, violet}; char **ptr[ ] = {s+3, s+2, s+1, s}, ***p; p = ptr; **++p; printf(%s,*--*++p + 3); } Answer: ck Explanation: In this problem we have an array of char pointers pointing to start of 4 strings. Then we have ptr which is a pointer to a pointer of type char and a variable p which is a pointer to a pointer to a pointer of type char. p hold the initial value of ptr, i.e. p = s+3. The next statement increment value in p by 1 , thus now value of p = s+2. In the printf statement the expression is evaluated *++p causes gets value s+1 then the pre decrement is executed and we get s+1 1 = s . the indirection operator now gets the

52)

value from the array of s and adds 3 to the starting address. The string is printed starting from this position. Thus, the output is ck. 53) main() { int i, n; char *x = girl; n = strlen(x); *x = x[n]; for(i=0; i<n; ++i) { printf(%s\n,x); x++; } } Answer: (blank space) irl rl l Explanation: Here a string (a pointer to char) is initialized with a value girl. The strlen function returns the length of the string, thus n has a value 4. The next statement assigns value at the nth location (\0) to the first location. Now the string becomes \0irl . Now the printf statement prints the string after each iteration it increments it starting position. Loop starts from 0 to 4. The first time x[0] = \0 hence it prints nothing and pointer value is incremented. The second time it prints from x[1] i.e irl and the third time it prints rl and the last time it prints l and the loop terminates. int i,j; for(i=0;i<=10;i++) { j+=5; assert(i<5); } Answer: Runtime error: Abnormal program termination. assert failed (i<5), <file name>,<line number> Explanation: asserts are used during debugging to make sure that certain conditions are satisfied. If assertion fails, the program will terminate reporting the same. After debugging use, #undef NDEBUG and this will disable all the assertions from the source code. Assertion is a good debugging tool to make use of.

54)

55)

main() { int i=-1; +i; printf("i = %d, +i = %d \n",i,+i); } Answer: i = -1, +i = -1 Explanation: Unary + is the only dummy operator in C. Where-ever it comes you can just ignore it just because it has no effect in the expressions (hence the name dummy operator). What are the files which are automatically opened when a C file is executed? Answer: stdin, stdout, stderr (standard input,standard output,standard error).

56)

57) what will be the position of the file marker? a: fseek(ptr,0,SEEK_SET); b: fseek(ptr,0,SEEK_CUR); Answer : a: The SEEK_SET sets the file position marker to the starting of the file. b: The SEEK_CUR sets the file position marker to the current position of the file. 58) main() { char name[10],s[12]; scanf(" \"%[^\"]\"",s); } How scanf will execute? Answer: First it checks for the leading white space and discards it.Then it matches with a quotation mark and then it reads all character upto another quotation mark. What is the problem with the following code segment? while ((fgets(receiving array,50,file_ptr)) != EOF) ; Answer & Explanation: fgets returns a pointer. So the correct end of file check is checking for != NULL. main()

59)

60)

{ main(); } Answer: Runtime error : Stack overflow. Explanation: main function calls itself again and again. Each time the function is called its return address is stored in the call stack. Since there is no condition to terminate the function call, the call stack overflows at runtime. So it terminates the program and results in an error. 61) main() { char *cptr,c; void *vptr,v; c=10; v=0; cptr=&c; vptr=&v; printf("%c%v",c,v); } Answer: Compiler error (at line number 4): size of v is Unknown. Explanation: You can create a variable of type void * but not of type void, since void is an empty type. In the second line you are creating variable vptr of type void * and v of type void hence an error. main() { char *str1="abcd"; char str2[]="abcd"; printf("%d %d %d",sizeof(str1),sizeof(str2),sizeof("abcd")); } Answer: 255 Explanation: In first sizeof, str1 is a character pointer so it gives you the size of the pointer variable. In second sizeof the name str2 indicates the name of the array whose size is 5 (including the '\0' termination character). The third sizeof is similar to the second one. main() { char not; not=!2; printf("%d",not); }

62)

63)

Answer: 0 Explanation: ! is a logical operator. In C the value 0 is considered to be the boolean value FALSE, and any non-zero value is considered to be the boolean value TRUE. Here 2 is a non-zero value so TRUE. !TRUE is FALSE (0) so it prints 0. 64) #define FALSE -1 #define TRUE 1 #define NULL 0 main() { if(NULL) puts("NULL"); else if(FALSE) puts("TRUE"); else puts("FALSE"); } Answer: TRUE Explanation: The input program to the compiler after processing by the preprocessor is, main(){ if(0) puts("NULL"); else if(-1) puts("TRUE"); else puts("FALSE"); } Preprocessor doesn't replace the values given inside the double quotes. The check by if condition is boolean value false so it goes to else. In second if -1 is boolean value true hence "TRUE" is printed. main() { int k=1; printf("%d==1 is ""%s",k,k==1?"TRUE":"FALSE"); } Answer: 1==1 is TRUE Explanation: When two strings are placed together (or separated by white-space) they are concatenated (this is called as "stringization" operation). So the string

65)

is as if it is given as "%d==1 is %s". The conditional operator( ?: ) evaluates to "TRUE". 66) main() { int y; scanf("%d",&y); // input given is 2000 if( (y%4==0 && y%100 != 0) || y%100 == 0 ) printf("%d is a leap year"); else printf("%d is not a leap year"); } Answer: 2000 is a leap year Explanation: An ordinary program to check if leap year or not. #define max 5 #define int arr1[max] main() { typedef char arr2[max]; arr1 list={0,1,2,3,4}; arr2 name="name"; printf("%d %s",list[0],name); } Answer: Compiler error (in the line arr1 list = {0,1,2,3,4}) Explanation: arr2 is declared of type array of size 5 of characters. So it can be used to declare the variable name of the type arr2. But it is not the case of arr1. Hence an error. Rule of Thumb: #defines are used for textual replacement whereas typedefs are used for declaring new types. int i=10; main() { extern int i; { int i=20; { const volatile unsigned i=30; printf("%d",i); }

67)

68)

printf("%d",i); } printf("%d",i); } Answer: 30,20,10 Explanation: '{' introduces new block and thus new scope. In the innermost block i is declared as, const volatile unsigned which is a valid declaration. i is assumed of type int. So printf prints 30. In the next block, i has value 20 and so printf prints 20. In the outermost block, i is declared as extern, so no storage space is allocated for it. After compilation is over the linker resolves it to global variable i (since it is the only variable visible there). So it prints i's value as 10. 69) main() { int *j; { int i=10; j=&i; } printf("%d",*j); } Answer: 10 Explanation: The variable i is a block level variable and the visibility is inside that block only. But the lifetime of i is lifetime of the function so it lives upto the exit of main function. Since the i is still allocated space, *j prints the value stored in i since j points i. main() { int i=-1; -i; printf("i = %d, -i = %d \n",i,-i); } Answer: i = -1, -i = 1 Explanation: -i is executed and this execution doesn't affect the value of i. In printf first you just print the value of i. After that the value of the expression -i = -(-1) is printed.

70)

71)

#include<stdio.h> main() { const int i=4; float j; j = ++i; printf("%d %f", i,++j); } Answer: Compiler error Explanation: i is a constant. you cannot change the value of constant #include<stdio.h> main() { int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} }; int *p,*q; p=&a[2][2][2]; *q=***a; printf("%d..%d",*p,*q); } Answer: garbagevalue..1 Explanation: p=&a[2][2][2] you declare only two 2D arrays. but you are trying to access the third 2D(which you are not declared) it will print garbage values. *q=***a starting address of a is assigned integer pointer. now q is pointing to starting address of a.if you print *q meAnswer:it will print first element of 3D array. #include<stdio.h> main() { register i=5; char j[]= "hello"; printf("%s %d",j,i); } Answer: hello 5 Explanation: if you declare i as register compiler will treat it as ordinary integer and it will take integer value. i value may be stored either in register or in memory. main()

72)

73)

74)

{ int i=5,j=6,z; printf("%d",i+++j); } Answer: 11 Explanation: the expression i+++j is treated as (i++ + j) 76) struct aaa{ struct aaa *prev; int i; struct aaa *next; }; main() { struct aaa abc,def,ghi,jkl; int x=100; abc.i=0;abc.prev=&jkl; abc.next=&def; def.i=1;def.prev=&abc;def.next=&ghi; ghi.i=2;ghi.prev=&def; ghi.next=&jkl; jkl.i=3;jkl.prev=&ghi;jkl.next=&abc; x=abc.next->next->prev->next->i; printf("%d",x); } Answer: 2 Explanation: above all statements form a double circular linked list; abc.next->next->prev->next->i this one points to "ghi" node the value of at particular node is 2. struct point { int x; int y; }; struct point origin,*pp; main() { pp=&origin; printf("origin is(%d%d)\n",(*pp).x,(*pp).y); printf("origin is (%d%d)\n",pp->x,pp->y); }

77)

Answer: origin is(0,0) origin is(0,0) Explanation: pp is a pointer to structure. we can access the elements of the structure either with arrow mark or with indirection operator. Note: Since structure point is globally declared x & y are initialized as zeroes 78) main() { int i=_l_abc(10); printf("%d\n",--i); } int _l_abc(int i) { return(i++); } Answer: 9 Explanation: return(i++) it will first return i and then increments. i.e. 10 will be returned. main() { char *p; int *q; long *r; p=q=r=0; p++; q++; r++; printf("%p...%p...%p",p,q,r); } Answer: 0001...0002...0004 Explanation: ++ operator when applied to pointers increments address according to their corresponding data-types. main() { char c=' ',x,convert(z); getc(c);

79)

80)

if((c>='a') && (c<='z')) x=convert(c); printf("%c",x); } convert(z) { return z-32; } Answer: Compiler error Explanation: declaration of convert and format of getc() are wrong. 81) main(int argc, char **argv) { printf("enter the character"); getchar(); sum(argv[1],argv[2]); } sum(num1,num2) int num1,num2; { return num1+num2; } Answer: Compiler error. Explanation: argv[1] & argv[2] are strings. They are passed to the function sum without converting it to integer values. # include <stdio.h> int one_d[]={1,2,3}; main() { int *ptr; ptr=one_d; ptr+=3; printf("%d",*ptr); } Answer: garbage value Explanation: ptr pointer is pointing to out of the array range of one_d. # include<stdio.h> aaa() {

82)

83)

printf("hi"); } bbb(){ printf("hello"); } ccc(){ printf("bye"); } main() { int (*ptr[3])(); ptr[0]=aaa; ptr[1]=bbb; ptr[2]=ccc; ptr[2](); } Answer: bye Explanation: ptr is array of pointers to functions of return type int.ptr[0] is assigned to address of the function aaa. Similarly ptr[1] and ptr[2] for bbb and ccc respectively. ptr[2]() is in effect of writing ccc(), since ptr[2] points to ccc. 85) #include<stdio.h> main() { FILE *ptr; char i; ptr=fopen("zzz.c","r"); while((i=fgetch(ptr))!=EOF) printf("%c",i); } Answer: contents of zzz.c followed by an infinite loop Explanation: The condition is checked against EOF, it should be checked against NULL. main() { int i =0;j=0; if(i && j++) printf("%d..%d",i++,j); printf("%d..%d,i,j); } Answer:

86)

0..0 Explanation: The value of i is 0. Since this information is enough to determine the truth value of the boolean expression. So the statement following the if statement is not executed. The values of i and j remain unchanged and get printed. 87) main() { int i; i = abc(); printf("%d",i); } abc() { _AX = 1000; } Answer: 1000 Explanation: Normally the return value from the function is through the information from the accumulator. Here _AH is the pseudo global variable denoting the accumulator. Hence, the value of the accumulator is set 1000 so the function returns value 1000. int i; main(){ int t; for ( t=4;scanf("%d",&i)-t;printf("%d\n",i)) printf("%d--",t--); } // If the inputs are 0,1,2,3 find the o/p Answer: 4--0 3--1 2--2 Explanation: Let us assume some x= scanf("%d",&i)-t the values during execution will be, t i x 4 0 -4 3 1 -2 2 2 0 main(){ int a= 0;int b = 20;char x =1;char y =10;

88)

89)

if(a,b,x,y) printf("hello"); } Answer: hello Explanation: The comma operator has associativity from left to right. Only the rightmost value is returned and the other values are evaluated and ignored. Thus the value of last variable y is returned to check in if. Since it is a non zero value if becomes true so, "hello" will be printed. 90) main(){ unsigned int i; for(i=1;i>-2;i--) printf("c aptitude"); } Explanation: i is an unsigned integer. It is compared with a signed value. Since the both types doesn't match, signed is promoted to unsigned value. The unsigned equivalent of -2 is a huge value so condition becomes false and control comes out of the loop. In the following pgm add a stmt in the function fun such that the address of 'a' gets stored in 'j'. main(){ int * j; void fun(int **); fun(&j); } void fun(int **k) { int a =0; /* add a stmt here*/ } Answer: *k = &a Explanation: The argument of the function is a pointer to a pointer. What are the following notations of defining functions known as? i. int abc(int a,float b) { /* some code */ } ii. int abc(a,b) int a; float b; {

91)

92)

/* some code*/ } Answer: i. ANSI C notation ii. Kernighan & Ritche notation 93) main() { char *p; p="%d\n"; p++; p++; printf(p-2,300); } Answer: 300 Explanation: The pointer points to % since it is incremented twice and again decremented by 2, it points to '%d\n' and 300 is printed. main(){ char a[100]; a[0]='a';a[1]]='b';a[2]='c';a[4]='d'; abc(a); } abc(char a[]){ a++; printf("%c",*a); a++; printf("%c",*a); } Explanation: The base address is modified only in function and as a result a points to 'b' then after incrementing to 'c' so bc will be printed. func(a,b) int a,b; { return( a= (a==b) ); } main() { int process(),func(); printf("The value of process is %d !\n ",process(func,3,6)); } process(pf,val1,val2)

94)

95)

int (*pf) (); int val1,val2; { return((*pf) (val1,val2)); } Answer: The value if process is 0 ! Explanation: The function 'process' has 3 parameters - 1, a pointer to another function 2 and 3, integers. When this function is invoked from main, the following substitutions for formal parameters take place: func for pf, 3 for val1 and 6 for val2. This function returns the result of the operation performed by the function 'func'. The function func has two integer parameters. The formal parameters are substituted as 3 for a and 6 for b. since 3 is not equal to 6, a==b returns 0. therefore the function returns 0 which in turn is returned by the function 'process'. 96) void main() { static int i=5; if(--i){ main(); printf("%d ",i); } } Answer: 0000 Explanation: The variable "I" is declared as static, hence memory for I will be allocated for only once, as it encounters the statement. The function main() will be called recursively unless I becomes equal to 0, and since main() is recursively called, so the value of static I ie., 0 will be printed every time the control is returned. void main() { int k=ret(sizeof(float)); printf("\n here value is %d",++k); } int ret(int ret) { ret += 2.5; return(ret); } Answer: Here value is 7 Explanation:

97)

The int ret(int ret), ie., the function name and the argument name can be the same. Firstly, the function ret() is called in which the sizeof(float) ie., 4 is passed, after the first expression the value in ret will be 6, as ret is integer hence the value stored in ret will have implicit type conversion from float to int. The ret is returned in main() it is printed after and preincrement. 98) void main() { char a[]="12345\0"; int i=strlen(a); printf("here in 3 %d\n",++i); } Answer: here in 3 6 Explanation: The char array 'a' will hold the initialized string, whose length will be counted from 0 till the null character. Hence the 'I' will hold the value equal to 5, after the pre-increment in the printf statement, the 6 will be printed. void main() { unsigned giveit=-1; int gotit; printf("%u ",++giveit); printf("%u \n",gotit=--giveit); } Answer: 0 65535 Explanation: void main() { int i; char a[]="\0"; if(printf("%s\n",a)) printf("Ok here \n"); else printf("Forget it\n"); } Answer: Ok here Explanation: Printf will return how many characters does it print. Hence printing a null character returns 1 which makes the if statement true, thus "Ok here" is printed.

99)

100)

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

102)

103)

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

104)

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. 104) main() { unsigned int i=10; while(i-->=0) printf("%u ",i); } Answer: 10 9 8 7 6 5 4 3 2 1 0 65535 65534.. Explanation: Since i is an unsigned integer it can never become negative. So the expression i-- >=0 will always be true, leading to an infinite loop. 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. main() { int a[10];

106)

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 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 postdecrement operator.

108)

113)

main() { float f=5,g=10; enum{i=10,j=20,k=50}; printf("%d\n",++k); printf("%f\n",f<<2); printf("%lf\n",f%g); printf("%lf\n",fmod(f,g)); } Answer: Line no 5: Error: Lvalue required Line no 6: Cannot apply leftshift to float Line no 7: Cannot apply mod to float Explanation: Enumeration constants cannot be modified, so you cannot apply ++. Bit-wise operators and % operators cannot be applied on float values. fmod() is to find the modulus values for floats as % operator is for ints.

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 doesnt 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 programmers 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 dont use such overloading of names. It reduces the readability of the code. Possible doesnt 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 00 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 . arr2D arr2D[1] arr2D[2] arr2D[3]

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 doesnt 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 1s 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 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. 126) int aaa() {printf(Hi);} int bbb(){printf(hello);} iny ccc(){printf(bye);} main() { int ( * ptr[3]) (); ptr[0] = aaa;

124)

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. 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 doesnt 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.

131)

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

134)

135)

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' a="Hi" 3. Same as 1. : legal : illegal

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: 41 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 expressions 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 expressions 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. 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 2 3 4 1 4 7 2 1 2 3 4 1 4 7 2

146)

5 6 7 8 9

5 8 3 6 9

5 6 7 8 9

5 8 3 6 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 doesnt 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: 11 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: 21 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. 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])( ); 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.month, &student.dob.year);

153)

&student.dob.day,

} Answer: Compiler Error: Undefined structure date Explanation: Inside the struct definition of student the member of type struct date is given. The compiler doesnt 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. 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.

156)

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 shouldnt be used. A plain if and the corresponding remedy statement has to be given. 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: Dont use expressions that have side-effects in assert statements. 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

159)

160)

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. 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). 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. Is the following code legal? void main() { typedef struct a aType; aType someVariable; struct a {

164)

165)

166)

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. 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. 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. void main() {

168)

169)

170)

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. 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. main() { char a[4]="HELLO"; printf("%s",a); } Answer:

172)

173)

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() { { { } printf("%d",i); } printf("%d",i); } extern int i; int i=20; const volatile unsigned i=30; 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 doesnt 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.

C++ Aptitude and OOPS


C++ Aptitude and OOPS
Note : All the programs are tested under Turbo C++ 3.0, 4.5 and Microsoft VC++ 6.0 compilers. It is assumed that, Programs run under Windows environment, The underlying machine is an x86 based system, Program is compiled using Turbo C/C++ compiler. The program output may depend on the information based on this assumptions (for example sizeof(int) == 2 may be assumed). 1) class Sample { public: int *ptr; Sample(int i) { ptr = new int(i); } ~Sample() { delete ptr; } void PrintVal() { cout << "The value is " << *ptr; } }; void SomeFunc(Sample x) { cout << "Say i am in someFunc " << endl; } int main() { Sample s1= 10; SomeFunc(s1); s1.PrintVal(); } Answer:

Say i am in someFunc Null pointer assignment(Run-time error) Explanation: As the object is passed by value to SomeFunc the destructor of the object is called when the control returns from the function. So when PrintVal is called it meets up with ptr that has been freed.The solution is to pass the Sample object by reference to SomeFunc: void SomeFunc(Sample &x) { cout << "Say i am in someFunc " << endl; } because when we pass objects by refernece that object is not destroyed. while returning from the function. 2) Which is the parameter that is added to every non-static member function when it is called? Answer: this pointer 3) class base { public: int bval; base(){ bval=0;} }; class deri:public base { public: int dval; deri(){ dval=1;} }; void SomeFunc(base *arr,int size) { for(int i=0; i<size; i++,arr++) cout<<arr->bval; cout<<endl; } int main() { base BaseArr[5]; SomeFunc(BaseArr,5); deri DeriArr[5]; SomeFunc(DeriArr,5);

} Answer: 00000 01010 Explanation: The function SomeFunc expects two arguments.The first one is a pointer to an array of base class objects and the second one is the sizeof the array.The first call of someFunc calls it with an array of bae objects, so it works correctly and prints the bval of all the objects. When Somefunc is called the second time the argument passed is the pointeer to an array of derived class objects and not the array of base class objects. But that is what the function expects to be sent. So the derived class pointer is promoted to base class pointer and the address is sent to the function. SomeFunc() knows nothing about this and just treats the pointer as an array of base class objects. So when arr++ is met, the size of base class object is taken into consideration and is incremented by sizeof(int) bytes for bval (the deri class objects have bval and dval as members and so is of size >= sizeof(int)+sizeof(int) ). 4) class base { public: void baseFun(){ cout<<"from base"<<endl;} }; class deri:public base { public: void baseFun(){ cout<< "from derived"<<endl;} }; void SomeFunc(base *baseObj) { baseObj->baseFun(); } int main() { base baseObject; SomeFunc(&baseObject); deri deriObject; SomeFunc(&deriObject); } Answer: from base from base Explanation: As we have seen in the previous case, SomeFunc expects a pointer to a base class. Since a pointer to a derived class object is passed, it treats the argument only as a base class pointer and the corresponding base function is called.

5) class base { public: virtual void baseFun(){ cout<<"from base"<<endl;} }; class deri:public base { public: void baseFun(){ cout<< "from derived"<<endl;} }; void SomeFunc(base *baseObj) { baseObj->baseFun(); } int main() { base baseObject; SomeFunc(&baseObject); deri deriObject; SomeFunc(&deriObject); } Answer: from base from derived Explanation: Remember that baseFunc is a virtual function. That means that it supports runtime polymorphism. So the function corresponding to the derived class object is called.

void main() { int a, *pa, &ra; pa = &a; ra = a; cout <<"a="<<a <<"*pa="<<*pa <<"ra"<<ra ; } /* Answer : Compiler Error: 'ra',reference must be initialized Explanation : Pointers are different from references. One of the main differences is that the pointers can be both initialized and assigned, whereas references can only be initialized. So this code issues an error. */

const int size = 5; void print(int *ptr) { cout<<ptr[0]; } void print(int ptr[size]) { cout<<ptr[0]; } void main() { int a[size] = {1,2,3,4,5}; int *b = new int(size); print(a); print(b); } /* Answer: Compiler Error : function 'void print(int *)' already has a body Explanation: Arrays cannot be passed to functions, only pointers (for arrays, base addresses) can be passed. So the arguments int *ptr and int prt[size] have no difference as function arguments. In other words, both the functoins have the same signature and so cannot be overloaded. */ class some{ public: ~some() { cout<<"some's destructor"<<endl; } }; void main() { some s; s.~some(); } /* Answer: some's destructor some's destructor

Explanation: Destructors can be called explicitly. Here 's.~some()' explicitly calls the destructor of 's'. When main() returns, destructor of s is called again, hence the result. */ #include <iostream.h> class fig2d { int dim1; int dim2; public: fig2d() { dim1=5; dim2=6;} virtual void operator<<(ostream & rhs); }; void fig2d::operator<<(ostream &rhs) { rhs <<this->dim1<<" "<<this->dim2<<" "; } /*class fig3d : public fig2d { int dim3; public: fig3d() { dim3=7;} virtual void operator<<(ostream &rhs); }; void fig3d::operator<<(ostream &rhs) { fig2d::operator <<(rhs); rhs<<this->dim3; } */ void main() { fig2d obj1; // fig3d obj2; obj1 << cout; obj2 << cout;

// }

/* Answer : 56 Explanation: In this program, the << operator is overloaded with ostream as argument. This enables the 'cout' to be present at the right-hand-side. Normally, 'cout' is implemented as global function, but it doesn't mean that 'cout' is not possible to be overloaded as member function. Overloading << as virtual member function becomes handy when the class in which it is overloaded is inherited, and this becomes available to be overrided. This is as opposed to global friend functions, where friend's are not inherited. */ class opOverload{ public: bool operator==(opOverload temp); }; bool opOverload::operator==(opOverload temp){ if(*this == temp ){ cout<<"The both are same objects\n"; return true; } else{ cout<<"The both are different\n"; return false; } } void main(){ opOverload a1, a2; a1= =a2; } Answer : Runtime Error: Stack Overflow Explanation : Just like normal functions, operator functions can be called recursively. This program just illustrates that point, by calling the operator == function recursively, leading to an infinite loop.

class complex{ double re; double im;

public: complex() : re(1),im(0.5) {} bool operator==(complex &rhs); operator int(){} }; bool complex::operator == (complex &rhs){ if((this->re == rhs.re) && (this->im == rhs.im)) return true; else return false; } int main(){ complex c1; cout<< c1; } Answer : Garbage value Explanation: The programmer wishes to print the complex object using output re-direction operator,which he has not defined for his lass.But the compiler instead of giving an error sees the conversion function and converts the user defined object to standard object and prints some garbage value.

class complex{ double re; double im; public: complex() : re(0),im(0) {} complex(double n) { re=n,im=n;}; complex(int m,int n) { re=m,im=n;} void print() { cout<<re; cout<<im;} }; void main(){ complex c3; double i=5; c3 = i; c3.print(); } Answer:

5,5 Explanation: Though no operator= function taking complex, double is defined, the double on the rhs is converted into a temporary object using the single argument constructor taking double and assigned to the lvalue.

void main() { int a, *pa, &ra; pa = &a; ra = a; cout <<"a="<<a <<"*pa="<<*pa <<"ra"<<ra ; } Answer : Compiler Error: 'ra',reference must be initialized Explanation : Pointers are different from references. One of the main differences is that the pointers can be both initialized and assigned, whereas references can only be initialized. So this code issues an error. Try it Yourself 1) Determine the output of the 'C++' Codelet. class base { public : out() { cout<<"base "; } }; class deri{ public : out() { cout<<"deri "; } }; void main() { deri dp[3]; base *bp = (base*)dp; for (int i=0; i<3;i++) (bp++)->out(); }

2) Justify the use of virtual constructors and destructors in C++. 3) Each C++ object possesses the 4 member fns,(which can be declared by the programmer explicitly or by the implementation if they are not available). What are those 4 functions? 4) What is wrong with this class declaration? class something { char *str; public: something(){ st = new char[10]; } ~something() { delete str; } }; 5) Inheritance is also known as -------- relationship. Containership as relationship. ________

6) When is it necessary to use member-wise initialization list (also known as header initialization list) in C++? 7) Which is the only operator in C++ which can be overloaded but NOT inherited. 8) Is there anything wrong with this C++ class declaration? class temp { int value1; mutable int value2; public : void fun(int val) const{ ((temp*) this)->value1 = 10; value2 = 10; } };

1. What is a modifier? Answer: A modifier, also called a modifying function is a member function that changes the value of at least one data member. In other words, an operation that modifies the state of an object. Modifiers are also known as mutators. 2. What is an accessor? Answer: An accessor is a class operation that does not modify the state of an object. The accessor functions need to be declared as const operations 3. Differentiate between a template class and class template. Answer:
Template class:

A generic definition or a parameterized class not instantiated until the client provides the needed information. Its jargon for plain templates.
Class template:

A class template specifies how individual classes can be constructed much like the way a class specifies how individual objects can be constructed. Its jargon for plain classes. 4. When does a name clash occur? Answer: A name clash occurs when a name is defined in more than one place. For example., two different class libraries could give two different classes the same name. If you try to use many class libraries at the same time, there is a fair chance that you will be unable to compile or link the program because of name clashes. 5. Define namespace. Answer: It is a feature in c++ to minimize name collisions in the global name space. This namespace keyword assigns a distinct name to a library that allows other libraries to use the same identifier names without creating any name collisions. Furthermore, the compiler uses the namespace signature for differentiating the definitions. 6. What is the use of using declaration. Answer: A using declaration makes it possible to use a name from a namespace without the scope operator. 7. What is an Iterator class? Answer: A class that is used to traverse through the objects maintained by a container class. There are five categories of iterators: input iterators, output iterators, forward iterators,

bidirectional iterators, random access. An iterator is an entity that gives access to the contents of a container object without violating encapsulation constraints. Access to the contents is granted on a one-ata-time basis in order. The order can be storage order (as in lists and queues) or some arbitrary order (as in array indices) or according to some ordering relation (as in an ordered binary tree). The iterator is a construct, which provides an interface that, when called, yields either the next element in the container, or some value denoting the fact that there are no more elements to examine. Iterators hide the details of access to and update of the elements of a container class. The simplest and safest iterators are those that permit read-only access to the contents of a container class. The following code fragment shows how an iterator might appear in code: cont_iter:=new cont_iterator(); x:=cont_iter.next(); while x/=none do ... s(x); ... x:=cont_iter.next(); end; In this example, cont_iter is the name of the iterator. It is created on the first line by instantiation of cont_iterator class, an iterator class defined to iterate over some container class, cont. Succesive elements from the container are carried to x. The loop terminates when x is bound to some empty value. (Here, none)In the middle of the loop, there is s(x) an operation on x, the current element from the container. The next element of the container is obtained at the bottom of the loop. 9. List out some of the OODBMS available. Answer: GEMSTONE/OPAL of Gemstone systems. ONTOS of Ontos. Objectivity of Objectivity inc. Versant of Versant object technology. Object store of Object Design. ARDENT of ARDENT software. POET of POET software. 10. List out some of the object-oriented methodologies. Answer: Object Oriented Development (OOD) (Booch 1991,1994). Object Oriented Analysis and Design (OOA/D) (Coad and Yourdon 1991). Object Modelling Techniques (OMT) (Rumbaugh 1991). Object Oriented Software Engineering (Objectory) (Jacobson 1992). Object Oriented Analysis (OOA) (Shlaer and Mellor 1992). The Fusion Method (Coleman 1991).

11. What is an incomplete type? Answer: Incomplete types refers to pointers in which there is non availability of the implementation of the referenced location or it points to some location whose value is not available for modification. Example: int *i=0x400 // i points to address 400 *i=0; //set the value of memory location pointed by i. Incomplete types are otherwise called uninitialized pointers. 12. What is a dangling pointer? Answer: A dangling pointer arises when you use the address of an object after its lifetime is over. This may occur in situations like returning addresses of the automatic variables from a function or using the address of the memory block after it is freed. 13. Differentiate between the message and method. Answer: Message Method Objects communicate by sending messages Provides response to a message. to each other. A message is sent to invoke a method. It is an implementation of an operation. 14. What is an adaptor class or Wrapper class? Answer: A class that has no functionality of its own. Its member functions hide the use of a third party software component or an object with the non-compatible interface or a nonobject- oriented implementation. 15. What is a Null object? Answer: It is an object of some class whose purpose is to indicate that a real object of that class does not exist. One common use for a null object is a return value from a member function that is supposed to return an object with some specified properties but cannot find such an object. 16. What is class invariant? Answer: A class invariant is a condition that defines all valid states for an object. It is a logical condition to ensure the correct working of a class. Class invariants must hold when an object is created, and they must be preserved under all operations of the class. In particular all class invariants are both preconditions and post-conditions for all operations or member functions of the class.

17. What do you mean by Stack unwinding? Answer: It is a process during exception handling when the destructor is called for all local objects between the place where the exception was thrown and where it is caught. 18. Define precondition and post-condition to a member function. Answer: Precondition: A precondition is a condition that must be true on entry to a member function. A class is used correctly if preconditions are never false. An operation is not responsible for doing anything sensible if its precondition fails to hold. For example, the interface invariants of stack class say nothing about pushing yet another element on a stack that is already full. We say that isful() is a precondition of the push operation. Post-condition: A post-condition is a condition that must be true on exit from a member function if the precondition was valid on entry to that function. A class is implemented correctly if post-conditions are never false. For example, after pushing an element on the stack, we know that isempty() must necessarily hold. This is a post-condition of the push operation. 19. What are the conditions that have to be met for a condition to be an invariant of the class? Answer: The condition should hold at the end of every constructor. The condition should hold at the end of every mutator(non-const) operation. 20. What are proxy objects? Answer: Objects that stand for other objects are called proxy objects or surrogates. Example: template<class T> class Array2D { public: class Array1D { public: T& operator[] (int index); const T& operator[] (int index) const; ... }; Array1D operator[] (int index); const Array1D operator[] (int index) const; ... };

The following then becomes legal: Array2D<float>data(10,20); ........ cout<<data[3][6]; // fine Here data[3] yields an Array1D object and the operator [] invocation on that object yields the float in position(3,6) of the original two dimensional array. Clients of the Array2D class need not be aware of the presence of the Array1D class. Objects of this latter class stand for one-dimensional array objects that, conceptually, do not exist for clients of Array2D. Such clients program as if they were using real, live, two-dimensional arrays. Each Array1D object stands for a one-dimensional array that is absent from a conceptual model used by the clients of Array2D. In the above example, Array1D is a proxy class. Its instances stand for one-dimensional arrays that, conceptually, do not exist. 21. Name some pure object oriented languages. Answer: Smalltalk, Java, Eiffel, Sather. 22. Name the operators that cannot be overloaded. Answer: sizeof . .* .-> :: ?: 23. What is a node class? Answer: A node class is a class that, relies on the base class for services and implementation, provides a wider interface to te users than its base class, relies primarily on virtual functions in its public interface depends on all its direct and indirect base class can be understood only in the context of the base class can be used as base for further derivation can be used to create objects. A node class is a class that has added new services or functionality beyond the services inherited from its base class. 24. What is an orthogonal base class? Answer: If two base classes have no overlapping methods or data they are said to be independent of, or orthogonal to each other. Orthogonal in the sense means that two classes operate in different dimensions and do not interfere with each other in any way. The same derived class may inherit such classes with no difficulty.

25. What is a container class? What are the types of container classes? Answer: A container class is a class that is used to hold objects in memory or external storage. A container class acts as a generic holder. A container class has a predefined behavior and a well-known interface. A container class is a supporting class whose purpose is to hide the topology used for maintaining the list of objects in memory. When a container class contains a group of mixed objects, the container is called a heterogeneous container; when the container is holding a group of objects that are all the same, the container is called a homogeneous container. 26. What is a protocol class? Answer: An abstract class is a protocol class if: it neither contains nor inherits from classes that contain member data, non-virtual functions, or private (or protected) members of any kind. it has a non-inline virtual destructor defined with an empty implementation, all member functions other than the destructor including inherited functions, are declared pure virtual functions and left undefined. 27. What is a mixin class? Answer: A class that provides some but not all of the implementation for a virtual base class is often called mixin. Derivation done just for the purpose of redefining the virtual functions in the base classes is often called mixin inheritance. Mixin classes typically don't share common bases. 28. What is a concrete class? Answer: A concrete class is used to define a useful object that can be instantiated as an automatic variable on the program stack. The implementation of a concrete class is defined. The concrete class is not intended to be a base class and no attempt to minimize dependency on other classes in the implementation or behavior of the class. 29.What is the handle class? Answer: A handle is a class that maintains a pointer to an object that is programmatically accessible through the public interface of the handle class. Explanation: In case of abstract classes, unless one manipulates the objects of these classes through pointers and references, the benefits of the virtual functions are lost. User code may become dependent on details of implementation classes because an abstract type cannot be allocated statistically or on the stack without its size being known. Using pointers or references implies that the burden of memory management falls on the user. Another limitation of abstract class object is of fixed size. Classes however are used to represent concepts that require varying amounts of storage to implement them.

A popular technique for dealing with these issues is to separate what is used as a single object in two parts: a handle providing the user interface and a representation holding all or most of the object's state. The connection between the handle and the representation is typically a pointer in the handle. Often, handles have a bit more data than the simple representation pointer, but not much more. Hence the layout of the handle is typically stable, even when the representation changes and also that handles are small enough to move around relatively freely so that the user neednt use the pointers and the references. 30. What is an action class? Answer: The simplest and most obvious way to specify an action in C++ is to write a function. However, if the action has to be delayed, has to be transmitted 'elsewhere' before being performed, requires its own data, has to be combined with other actions, etc then it often becomes attractive to provide the action in the form of a class that can execute the desired action and provide other services as well. Manipulators used with iostreams is an obvious example. Explanation: A common form of action class is a simple class containing just one virtual function. class Action { public: virtual int do_it( int )=0; virtual ~Action( ); } Given this, we can write code say a member that can store actions for later execution without using pointers to functions, without knowing anything about the objects involved, and without even knowing the name of the operation it invokes. For example: class write_file : public Action { File& f; public: int do_it(int) { return fwrite( ).suceed( ); } }; class error_message: public Action { response_box db(message.cstr( ),"Continue","Cancel","Retry"); switch (db.getresponse( )) { case 0: return 0; case 1: abort(); case 2: current_operation.redo( );return 1;

} }; A user of the Action class will be completely isolated from any knowledge of derived classes such as write_file and error_message. 31. When can you tell that a memory leak will occur? Answer: A memory leak occurs when a program loses the ability to free a block of dynamically allocated memory. 32.What is a parameterized type? Answer: A template is a parameterized construct or type containing generic code that can use or manipulate any type. It is called parameterized because an actual type is a parameter of the code body. Polymorphism may be achieved through parameterized types. This type of polymorphism is called parameteric polymorphism. Parameteric polymorphism is the mechanism by which the same code is used on different types passed as parameters. 33. Differentiate between a deep copy and a shallow copy? Answer: Deep copy involves using the contents of one object to create another instance of the same class. In a deep copy, the two objects may contain ht same information but the target object will have its own buffers and resources. the destruction of either object will not affect the remaining object. The overloaded assignment operator would create a deep copy of objects. Shallow copy involves copying the contents of one object into another instance of the same class thus creating a mirror image. Owing to straight copying of references and pointers, the two objects will share the same externally contained contents of the other object to be unpredictable. Explanation: Using a copy constructor we simply copy the data values member by member. This method of copying is called shallow copy. If the object is a simple class, comprised of built in types and no pointers this would be acceptable. This function would use the values and the objects and its behavior would not be altered with a shallow copy, only the addresses of pointers that are members are copied and not the value the address is pointing to. The data values of the object would then be inadvertently altered by the function. When the function goes out of scope, the copy of the object with all its data is popped off the stack. If the object has any pointers a deep copy needs to be executed. With the deep copy of an object, memory is allocated for the object in free store and the elements pointed to are copied. A deep copy is used for objects that are returned from a function. 34. What is an opaque pointer? Answer:

A pointer is said to be opaque if the definition of the type to which it points to is not included in the current translation unit. A translation unit is the result of merging an implementation file with all its headers and header files. 35. What is a smart pointer? Answer: A smart pointer is an object that acts, looks and feels like a normal pointer but offers more functionality. In C++, smart pointers are implemented as template classes that encapsulate a pointer and override standard pointer operators. They have a number of advantages over regular pointers. They are guaranteed to be initialized as either null pointers or pointers to a heap object. Indirection through a null pointer is checked. No delete is ever necessary. Objects are automatically freed when the last pointer to them has gone away. One significant problem with these smart pointers is that unlike regular pointers, they don't respect inheritance. Smart pointers are unattractive for polymorphic code. Given below is an example for the implementation of smart pointers.
Example:

template <class X> class smart_pointer { public: smart_pointer(); smart_pointer(const X& x) X& operator *( ); const X& operator*( ) const; X* operator->() const;

// makes a null pointer // makes pointer to copy of x

smart_pointer(const smart_pointer <X> &); const smart_pointer <X> & operator =(const smart_pointer<X>&); ~smart_pointer(); private: //... }; This class implement a smart pointer to an object of type X. The object itself is located on the heap. Here is how to use it: smart_pointer <employee> p= employee("Harris",1333); Like other overloaded operators, p will behave like a regular pointer, cout<<*p; p->raise_salary(0.5); 36. What is reflexive association? Answer: The 'is-a' is called a reflexive association because the reflexive association permits classes to bear the is-a association not only with their super-classes but also with themselves. It differs from a 'specializes-from' as 'specializes-from' is usually used to describe the association between a super-class and a sub-class. For example: Printer is-a printer.

37. What is slicing? Answer: Slicing means that the data added by a subclass are discarded when an object of the subclass is passed or returned by value or from a function expecting a base class object. Explanation: Consider the following class declaration: class base { ... base& operator =(const base&); base (const base&); } void fun( ) { base e=m; e=m; } As base copy functions don't know anything about the derived only the base part of the derived is copied. This is commonly referred to as slicing. One reason to pass objects of classes in a hierarchy is to avoid slicing. Other reasons are to preserve polymorphic behavior and to gain efficiency. 38. What is name mangling? Answer: Name mangling is the process through which your c++ compilers give each function in your program a unique name. In C++, all programs have at-least a few functions with the same name. Name mangling is a concession to the fact that linker always insists on all function names being unique.
Example:

In general, member names are made unique by concatenating the name of the member with that of the class e.g. given the declaration: class Bar { public: int ival; ... }; ival becomes something like: // a possible member name mangling ival__3Bar Consider this derivation: class Foo : public Bar { public: int ival;

... } The internal representation of a Foo object is the concatenation of its base and derived class members. // Pseudo C++ code // Internal representation of Foo class Foo { public: int ival__3Bar; int ival__3Foo; ... }; Unambiguous access of either ival members is achieved through name mangling. Member functions, because they can be overloaded, require an extensive mangling to provide each with a unique name. Here the compiler generates the same name for the two overloaded instances(Their argument lists make their instances unique). 39. What are proxy objects? Answer: Objects that points to other objects are called proxy objects or surrogates. Its an object that provides the same interface as its server object but does not have any functionality. During a method invocation, it routes data to the true server object and sends back the return value to the object. 40. Differentiate between declaration and definition in C++. Answer: A declaration introduces a name into the program; a definition provides a unique description of an entity (e.g. type, instance, and function). Declarations can be repeated in a given scope, it introduces a name in a given scope. There must be exactly one definition of every object, function or class used in a C++ program. A declaration is a definition unless: it declares a function without specifying its body, it contains an extern specifier and no initializer or function body, it is the declaration of a static class data member without a class definition, it is a class name definition, it is a typedef declaration. A definition is a declaration unless: it defines a static class data member, it defines a non-inline member function. 41. What is cloning? Answer: An object can carry out copying in two ways i.e. it can set itself to be a copy of another object, or it can return a copy of itself. The latter process is called cloning. 42. Describe the main characteristics of static functions.

Answer: The main characteristics of static functions include, It is without the a this pointer, It can't directly access the non-static members of its class It can't be declared const, volatile or virtual. It doesn't need to be invoked through an object of its class, although for convenience, it may. 43. Will the inline function be compiled as the inline function always? Justify. Answer: An inline function is a request and not a command. Hence it won't be compiled as an inline function always. Explanation: Inline-expansion could fail if the inline function contains loops, the address of an inline function is used, or an inline function is called in a complex expression. The rules for inlining are compiler dependent. 44. Define a way other than using the keyword inline to make a function inline. Answer: The function must be defined inside the class. 45. How can a '::' operator be used as unary operator? Answer: The scope operator can be used to refer to members of the global namespace. Because the global namespace doesnt have a name, the notation :: member-name refers to a member of the global namespace. This can be useful for referring to members of global namespace whose names have been hidden by names declared in nested local scope. Unless we specify to the compiler in which namespace to search for a declaration, the compiler simple searches the current scope, and any scopes in which the current scope is nested, to find the declaration for the name. 46. What is placement new? Answer: When you want to call a constructor directly, you use the placement new. Sometimes you have some raw memory that's already been allocated, and you need to construct an object in the memory you have. Operator new's special version placement new allows you to do it. class Widget { public : Widget(int widgetsize); ... Widget* Construct_widget_int_buffer(void *buffer,int widgetsize) { return new(buffer) Widget(widgetsize); }

}; This function returns a pointer to a Widget object that's constructed within the buffer passed to the function. Such a function might be useful for applications using shared memory or memory-mapped I/O, because objects in such applications must be placed at specific addresses or in memory allocated by special routines.

OOAD 1. What do you mean by analysis and design? Analysis: Basically, it is the process of determining what needs to be done before how it should be done. In order to accomplish this, the developer refers the existing systems and documents. So, simply it is an art of discovery. Design: It is the process of adopting/choosing the one among the many, which best accomplishes the users needs. So, simply, it is compromising mechanism. 2. What are the steps involved in designing? Before getting into the design the designer should go through the SRS prepared by the System Analyst. The main tasks of design are Architectural Design and Detailed Design. In Architectural Design we find what are the main modules in the problem domain. In Detailed Design we find what should be done within each module. 3. What are the main underlying concepts of object orientation? Objects, messages, class, inheritance and polymorphism are the main concepts of object orientation. 4. What do u meant by "SBI" of an object? SBI stands for State, Behavior and Identity. Since every object has the above three. State: It is just a value to the attribute of an object at a particular time. Behaviour: It describes the actions and their reactions of that object. Identity: An object has an identity that characterizes its own existence. The identity makes it possible to distinguish any object in an unambiguous way, and independently from its state. 5. Differentiate persistent & non-persistent objects? Persistent refers to an object's ability to transcend time or space. A persistent object stores/saves its state in a permanent storage system with out losing the information represented by the object.

A non-persistent object is said to be transient or ephemeral. By default objects are considered as non-persistent. 6. What do you meant by active and passive objects? Active objects are one which instigate an interaction which owns a thread and they are responsible for handling control to other objects. In simple words it can be referred as client. Passive objects are one, which passively waits for the message to be processed. It waits for another object that requires its services. In simple words it can be referred as server. Diagram: client server (Active) (Passive) 7. What is meant by software development method? Software development method describes how to model and build software systems in a reliable and reproducible way. To put it simple, methods that are used to represent ones' thinking using graphical notations. 8. What are models and meta models? Model: It is a complete description of something (i.e. system). Meta model: It describes the model elements, syntax and semantics of the notation that allows their manipulation. 9. What do you meant by static and dynamic modeling? Static modeling is used to specify structure of the objects that exist in the problem domain. These are expressed using class, object and USECASE diagrams. But Dynamic modeling refers representing the object interactions during runtime. It is represented by sequence, activity, collaboration and statechart diagrams. 10. How to represent the interaction between the modeling elements? Model element is just a notation to represent (Graphically) the entities that exist in the problem domain. e.g. for modeling element is class notation, object notation etc. Relationships are used to represent the interaction between the modeling elements. The following are the Relationships. Association: Its' just a semantic connection two classes. e.g.: uses class A class B Aggregation: Its' the relationship between two classes which are related in the fashion

that master and slave. The master takes full rights than the slave. Since the slave works under the master. It is represented as line with diamond in the master area. ex: car contains wheels, etc. car car wheels

Containment: This relationship is applied when the part contained with in the whole part, dies when the whole part dies. It is represented as darked diamond at the whole part. example: class A{ //some code }; class B { A aa; // an object of class A; // some code for class B; }; In the above example we see that an object of class A is instantiated with in the class B. so the object class A dies when the object class B dies.we can represnt it in diagram like this. class A class B

Generalization: This relationship used when we want represents a class, which captures the common states of objects of different classes. It is represented as arrow line pointed at the class, which has captured the common states. class A

class B

class C

Dependency: It is the relationship between dependent and independent classes. Any change in the independent class will affect the states of the dependent class. DIAGRAM: class A class B 11. Why generalization is very strong? Even though Generalization satisfies Structural, Interface, Behaviour properties.

It is mathematically very strong, as it is Antisymmetric and Transitive. Antisymmetric: employee is a person, but not all persons are employees. Mathematically all As are B, but all Bs not A. Transitive: A=>B, B=>c then A=>c. A. Salesman. B. Employee. C. Person. Note: All the other relationships satisfy all the properties like Structural properties, Interface properties, Behaviour properties. 12. Differentiate Aggregation and containment? Aggregation is the relationship between the whole and a part. We can add/subtract some properties in the part (slave) side. It won't affect the whole part. Best example is Car, which contains the wheels and some extra parts. Even though the parts are not there we can call it as car. But, in the case of containment the whole part is affected when the part within that got affected. The human body is an apt example for this relationship. When the whole body dies the parts (heart etc) are died. 13. Can link and Association applied interchangeably? No, You cannot apply the link and Association interchangeably. Since link is used represent the relationship between the two objects. But Association is used represent the relationship between the two classes. link :: student:Abhilash course:MCA Association:: student course 14. what is meant by "method-wars"? Before 1994 there were different methodologies like Rumbaugh, Booch, Jacobson, Meyer etc who followed their own notations to model the systems. The developers were in a dilemma to choose the method which best accomplishes their needs. This particular span was called as "method-wars" 15. Whether unified method and unified modeling language are same or different? Unified method is convergence of the Rumbaugh and Booch. Unified modeling lang. is the fusion of Rumbaugh, Booch and Jacobson as well as Betrand Meyer (whose contribution is "sequence diagram"). Its' the superset of all the methodologies. 16. Who were the three famous amigos and what was their contribution to the object community? The Three amigos namely, James Rumbaugh (OMT): A veteran in analysis who came up with an idea about the objects and their Relationships (in particular Associations). Grady Booch: A veteran in design who came up with an idea about partitioning of systems into subsystems.

Ivar Jacobson (Objectory): The father of USECASES, who described about the user and system interaction. 17. Differentiate the class representation of Booch, Rumbaugh and UML? If you look at the class representaiton of Rumbaugh and UML, It is some what similar and both are very easy to draw. Representation: OMT UML. Diagram:

Booch: In this method classes are represented as "Clouds" which are not very easy to draw as for as the developer's view is concern. Diagram:

18. What is an USECASE? Why it is needed? A Use Case is a description of a set of sequence of actions that a system performs that yields an observable result of value to a particular action. In SSAD process <=> In OOAD USECASE. It is represented elliptically. Representation:

19. Who is an Actor? An Actor is someone or something that must interact with the system.In addition to that an Actor initiates the process(that is USECASE). It is represented as a stickman like this. Diagram:

20. What is guard condition? Guard condition is one, which acts as a firewall. The access from a particular object can be made only when the particular condition is met. For Example,

customer check customer number ATM. Here the object on the customer accesses the ATM facility only when the guard condition is met. 21. Differentiate the following notations? I: :obj1 :obj2 II: :obj1 :obj2

In the above representation I, obj1 sends message to obj2. But in the case of II the data is transferred from obj1 to obj2. 22. USECASE is an implementation independent notation. How will the designer give the implementation details of a particular USECASE to the programmer? This can be accomplished by specifying the relationship called "refinement which talks about the two different abstraction of the same thing. Or example, calculate pay calculate class1 class2 class3 23. Suppose a class acts an Actor in the problem domain, how to represent it in the static model? In this scenario you can use stereotype. Since stereotype is just a string that gives extra semantic to the particular entity/model element. It is given with in the << >>. class A << Actor>> attributes methods. 24. Why does the function arguments are called as "signatures"? The arguments distinguish functions with the same name (functional polymorphism). The name alone does not necessarily identify a unique function. However, the name and its arguments (signatures) will uniquely identify a function. In real life we see suppose, in class there are two guys with same name, but they can be easily identified by their signatures. The same concept is applied here. ex: class person { public: char getsex(); void setsex(char);

void setsex(int); }; In the above example we see that there is a function setsex() with same name but with different signature.

Quantitative Aptitude
Quantitative Aptitude
Exercise 1 Solve the following and check with the answers given at the end. 1. It was calculated that 75 men could complete a piece of work in 20 days. When work was scheduled to commence, it was found necessary to send 25 men to another project. How much longer will it take to complete the work? A student divided a number by 2/3 when he required to multiply by 3/2. Calculate the percentage of error in his result. A dishonest shopkeeper professes to sell pulses at the cost price, but he uses a false weight of 950gm. for a kg. His gain is %. A software engineer has the capability of thinking 100 lines of code in five minutes and can type 100 lines of code in 10 minutes. He takes a break for five minutes after every ten minutes. How many lines of codes will he complete typing after an hour? A man was engaged on a job for 30 days on the condition that he would get a wage of Rs. 10 for the day he works, but he have to pay a fine of Rs. 2 for each day of his absence. If he gets Rs. 216 at the end, he was absent for work for ... days. A contractor agreeing to finish a work in 150 days, employed 75 men each working 8 hours daily. After 90 days, only 2/7 of the work was completed. Increasing the number of men by ________ each working now for 10 hours daily, the work can be completed in time. what is a percent of b divided by b percent of a? (a) a (b) b (c) 1

2.

3.

4.

5.

6.

7.

(d)

10

(d)

100

8.

A man bought a horse and a cart. If he sold the horse at 10 % loss and the cart at 20 % gain, he would not lose anything; but if he sold the horse at 5% loss and the cart at 5% gain, he would lose Rs. 10 in the bargain. The amount paid by him was Rs._______ for the horse and Rs.________ for the cart.

9.

A tennis marker is trying to put together a team of four players for a tennis tournament out of seven available. males - a, b and c; females m, n, o and p. All players are of equal ability and there must be at least two males in the team. For a team of four, all players must be able to play with each other under the following restrictions: b should not play with m, c should not play with p, and a should not play with o. Which of the following statements must be false? 1. b and p cannot be selected together 2. c and o cannot be selected together 3. c and n cannot be selected together. 10-12. The following figure depicts three views of a cube. Based on this, answer questions 10-12. 6 1 2 2 5 22 3 3 4 6

10. 11. 12.

The number on the face opposite to the face carrying 1 is _______ . The number on the faces adjacent to the face marked 5 are _______ . Which of the following pairs does not correctly give the numbers on the opposite faces. (1) 6,5 (2) 4,1 (3) 1,3 (4) 4,2 Five farmers have 7, 9, 11, 13 & 14 apple trees, respectively in their orchards. Last year, each of them discovered that every tree in their own orchard bore exactly the same number of apples. Further, if the third farmer gives one apple to the first, and the fifth gives three to each of the second and the fourth, they would all have exactly the same number of apples. What were the yields per tree in the orchards of the third and fourth farmers? Five boys were climbing a hill. J was following H. R was just ahead of G. K was between G & H. They were climbing up in a column. Who was the second?

13.

14.

15-18 John is undecided which of the four novels to buy. He is considering a spy thriller, a Murder mystery, a Gothic romance and a science fiction novel. The books are written by Rothko, Gorky, Burchfield and Hopper, not necessary in that order, and published by Heron, Piegon, Blueja and sparrow, not necessary in that order.

(1) The book by Rothko is published by Sparrow. (2) The Spy thriller is published by Heron. (3) The science fiction novel is by Burchfield and is not published by Blueja. (4)The Gothic romance is by Hopper. 15. 16. 17. Pigeon publishes ____________. The novel by Gorky ________________. John purchases books by the authors whose names come first and third in alphabetical order. He does not buy the books ______. On the basis of the first paragraph and statement (2), (3) and (4) only, it is possible to deduce that 1. Rothko wrote the murder mystery or the spy thriller 2. Sparrow published the murder mystery or the spy thriller 3. The book by Burchfield is published by Sparrow. If a light flashes every 6 seconds, how many times will it flash in of an hour? If point P is on line segment AB, then which of the following is always true? (1) AP = PB (2) AP > PB (3) PB > AP (4) AB > AP (5) AB > AP + PB All men are vertebrates. Some mammals are vertebrates. Which of the following conclusions drawn from the above statement is correct. All men are mammals All mammals are men Some vertebrates are mammals. None Which of the following statements drawn from the given statements are correct? Given: All watches sold in that shop are of high standard. Some of the HMT watches are sold in that shop. a) All watches of high standard were manufactured by HMT. b) Some of the HMT watches are of high standard. c) None of the HMT watches is of high standard. d) Some of the HMT watches of high standard are sold in that shop.

18.

19. 20.

21.

22.

23-27. 1. 2. 3. 4. 5. 6. Ashland is north of East Liverpool and west of Coshocton. Bowling green is north of Ashland and west of Fredericktown. Dover is south and east of Ashland. East Liverpool is north of Fredericktown and east of Dover. Fredericktown is north of Dover and west of Ashland. Coshocton is south of Fredericktown and west of Dover.

23.

Which of the towns mentioned is furthest of the north west (a) Ashland (b) Bowling green (c) Coshocton (d) East Liverpool (e) Fredericktown Which of the following must be both north and east of Fredericktown? (a) Ashland (b) Coshocton (c) East Liverpool I a only II b only III c only IV a & b Va&c Which of the following towns must be situated both south and west of at least one other town? A. Ashland only B. Ashland and Fredericktown C. Dover and Fredericktown D. Dover, Coshocton and Fredericktown E. Coshocton, Dover and East Liverpool. Which of the following statements, if true, would make the information in the numbered statements more specific? (a) Coshocton is north of Dover. (b) East Liverpool is north of Dover (c) Ashland is east of Bowling green. (d) Coshocton is east of Fredericktown (e) Bowling green is north of Fredericktown Which of the numbered statements gives information that can be deduced from one or more of the other statements? (A) 1 (B) 2 (C) 3 (D) 4 (E) 6 Eight friends Harsha, Fakis, Balaji, Eswar, Dhinesh, Chandra, Geetha, and Ahmed are sitting in a circle facing the center. Balaji is sitting between Geetha and Dhinesh. Harsha is third to the left of Balaji and second to the right of Ahmed. Chandra is sitting between Ahmed and Geetha and Balaji and Eshwar are not sitting opposite to each other. Who is third to the left of Dhinesh? If every alternative letter starting from B of the English alphabet is written in small letter, rest all are written in capital letters, how the month September be written. (1) SeptEMbEr (2) SEpTeMBEr (3) SeptembeR (4) SepteMber (5) None of the above. The length of the side of a square is represented by x+2. The length of the side of an equilateral triangle is 2x. If the square and the equilateral triangle have equal perimeter, then the value of x is _______.

24.

25.

26.

27.

28.

29.

30.

31.

It takes Mr. Karthik y hours to complete typing a manuscript. After 2 hours, he was called away. What fractional part of the assignment was left incomplete? Which of the following is larger than 3/5? (1) (2) 39/50 (3) 7/25

32.

(4)

3/10

(5)

59/100

33. 34.

The number that does not have a reciprocal is ____________. There are 3 persons Sudhir, Arvind, and Gauri. Sudhir lent cars to Arvind and Gauri as many as they had already. After some time Arvind gave as many cars to Sudhir and Gauri as many as they have. After sometime Gauri did the same thing. At the end of this transaction each one of them had 24. Find the cars each originally had. A man bought a horse and a cart. If he sold the horse at 10 % loss and the cart at 20 % gain, he would not lose anything; but if he sold the horse at 5% loss and the cart at 5% gain, he would lose Rs. 10 in the bargain. The amount paid by him was Rs._______ for the horse and Rs.________ for the cart.

35.

Answers: 1. Answer: 30 days. Explanation: Before: One day work One mans one day work Now: No. Of workers One day work

= = = =

1 / 20 1 / ( 20 * 75) 50 50 * 1 / ( 20 * 75)

The total no. of days required to complete the work = (75 * 20) / 50 = 30 2. Answer: 0% Explanation: Since 3x / 2 = x / (2 / 3) Answer: 5.3 % Explanation: He sells 950 grams of pulses and gains 50 grams. If he sells 100 grams of pulses then he will gain (50 / 950) *100 = 5.26 Answer: 250 lines of codes

3.

4.

5.

Answer: 7 days Explanation: The equation portraying the given problem is: 10 * x 2 * (30 x) = 216 where x is the number of working days. Solving this we get x = 23 Number of days he was absent was 7 (30-23) days. Answer: 150 men. Explanation: One days work One hours work One mans work

6.

= = =

2 / (7 * 90) 2 / (7 * 90 * 8) 2 / (7 * 90 * 8 * 75)

The remaining work (5/7) has to be completed within 60 days, because the total number of days allotted for the project is 150 days. So we get the equation (2 * 10 * x * 60) / (7 * 90 * 8 * 75) = 5/7 where x is the number of men working after the 90th day. We get x = 225 Since we have 75 men already, it is enough to add only 150 men. 7. Answer: (c) 1 Explanation: a percent of b : (a/100) * b b percent of a : (b/100) * a a percent of b divided by b percent of a : ((a / 100 )*b) / (b/100) * a )) = 1 Answer: Cost price of horse = Rs. 400 & the cost price of cart = 200. Explanation:Let x be the cost price of the horse and y be the cost price of the cart. In the first sale there is no loss or profit. (i.e.) The loss obtained is equal to the gain. Therefore (10/100) * x = (20/100) * y

8.

X = 2 * y -----------------(1) In the second sale, he lost Rs. 10. (i.e.) The loss is greater than the profit by Rs. 10.

Therefore (5 / 100) * x = (5 / 100) * y + 10 -------(2) Substituting (1) in (2) we get (10 / 100) * y = (5 / 100) * y + 10 (5 / 100) * y = 10 y = 200 From (1) 2 * 200 = x = 400 9. Answer: 3. Explanation: Since inclusion of any male player will reject a female from the team. Since there should be four member in the team and only three males are available, the girl, n should included in the team always irrespective of others selection. Answer: 5 Answer: 1,2,3 & 4 Answer: B Answer: 11 & 9 apples per tree. Explanation: Let a, b, c, d & e be the total number of apples bored per year in A, B, C, D & E s orchard. Given that a + 1 = b + 3 = c 1 = d + 3 = e 6 But the question is to find the number of apples bored per tree in C and D s orchard. If is enough to consider c 1 = d + 3. Since the number of trees in Cs orchard is 11 and that of Ds orchard is 13. Let x and y be the number of apples bored per tree in C & d s orchard respectively. Therefore 11 x 1 = 13 y + 3 By trial and error method, we get the value for x and y as 11 and 9 Answer: G. Explanation: The order in which they are climbing is R G K H J

10.

11.

12.

13.

14.

15 18 Answer: Novel Name Spy thriller Author Rathko Publisher Heron

Murder mystery Gothic romance Science fiction Explanation: Given Novel Name Spy thriller Murder mystery Gothic romance Science fiction

Gorky Burchfield Hopper

Piegon Blueja Sparrow

Author Rathko Gorky Burchfield Hopper

Publisher Heron Piegon Blueja Sparrow

Since Blueja doesnt publish the novel by Burchfield and Heron publishes the novel spy thriller, Piegon publishes the novel by Burchfield. Since Hopper writes Gothic romance and Heron publishes the novel spy thriller, Blueja publishes the novel by Hopper. Since Heron publishes the novel spy thriller and Heron publishes the novel by Gorky, Gorky writes Spy thriller and Rathko writes Murder mystery. 19. Answer: 451 times. Explanation: There are 60 minutes in an hour. In of an hour there are (60 * ) minutes = 45 minutes. In of an hour there are (60 * 45) seconds = 2700 seconds. Light flashed for every 6 seconds. In 2700 seconds 2700/6 = 450 times. The count start after the first flash, the light will flashes 451 times in of an hour. Answer: (4) Explanation: P A B Since p is a point on the line segment AB, AB > AP 21. 22. Answer: (c) Answer: (b) & (d).

20.

Ahmed 23 - 27.Answer: Fakis 28. Answer: Fakis Explanation: Harsha Eswar Balaji Chandra Geetha

Dhinesh 29. Answer: (5). Explanation: Since every alternative letter starting from B of the English alphabet is written in small letter, the letters written in small letter are b, d, f... In the first two answers the letter E is written in both small & capital letters, so they are not the correct answers. But in third and fourth answers the letter is written in small letter instead capital letter, so they are not the answers. Answer: x=4 Explanation: Since the side of the square is x + 2, its perimeter = 4 (x + 2) = 4x + 8 Since the side of the equilateral triangle is 2x, its perimeter = 3 * 2x = 6x Also, the perimeters of both are equal. (i.e.) 4x + 8 = 6x (i.e.) 2x = 8 x = 4. Answer: (y 2) / y. Explanation: To type a manuscript karthik took y hours. Therefore his speed in typing = 1/y. He was called away after 2 hours of typing. Therefore the work completed = 1/y * 2. Therefore the remaining work to be completed = 1 2/y. (i.e.) work to be completed = (y-2)/y Answer: (2) Answer: 1 Explanation:

30.

31.

32.

33.

One is the only number exists without reciprocal because the reciprocal of one is one itself. 34. Answer: Sudhir had 39 cars, Arvind had 21 cars and Gauri had 12 cars. Explanation: Sudhir Arvind Finally 24 Before Gauris transaction 12 Before Arvinds transaction 6 Before Sudhir s transaction 39 35. 24 12 42 21

Gauri 24 48 24 12

Answer: Cost price of horse: Rs. 400 & Cost price of cart: Rs. 200 Explanation: Let x be the cost of horse & y be the cost of the cart. 10 % of loss in selling horse = 20 % of gain in selling the cart Therefore (10 / 100) * x = (20 * 100) * y x = 2y -----------(1) 5 % of loss in selling the horse is 10 more than the 5 % gain in selling the cart. Therefore (5 / 100) * x - 10 = (5 / 100) * y 5x - 1000 = 5y Substituting (1) 10y - 1000 = 5y 5y = 1000 y = 200 x = 400 from (1)

Exercise 2.1 For the following, find the next term in the series 1. 6, 24, 60,120, 210 a) 336 b) 366 c) 330 d) 660

Answer : a) 336 Explanation : The series is 1.2.3, 2.3.4, 3.4.5, 4.5.6, 5.6.7, ..... 2. 1, 5, 13, 25 Answer : 41 Explanation : The series is of the form 0^2+1^2, 1^2+2^2,...

( '.' means product)

3. 0, 5, 8, 17 Answer : 24 Explanation : 1^2-1, 2^2+1, 3^2-1, 4^2+1, 5^2-1 4. 1, 8, 9, 64, 25 (Hint : Every successive terms are related)

Answer : 216 Explanation : 1^2, 2^3, 3^2, 4^3, 5^2, 6^3 5. 8,24,12,36,18,54 Answer : 27 6. 71,76,69,74,67,72 Answer : 67 7. 5,9,16,29,54 Answer : 103 Explanation : 5*2-1=9; 9*2-2=16; 16*2-3=29; 29*2-4=54; 54*2-5=103 8. 1,2,4,10,16,40,64 (Successive terms are related) Answer : 200 Explanation : The series is powers of 2 (2^0,2^1,..). All digits are less than 8. Every second number is in octal number system. 128 should follow 64. 128 base 10 = 200 base 8. Exercise 2.2 Find the odd man out. 1. 3,5,7,12,13,17,19 Answer : 12 Explanation : All but 12 are odd numbers 2. 2,5,10,17,26,37,50,64 Answer : 64 Explanation : 2+3=5; 5+5=10; 10+7=17; 17+9=26; 26+11=37; 37+13=50; 50+15=65; 3. 105,85,60,30,0,-45,-90 Answer : 0 Explanation : 105-20=85; 85-25=60; 60-30=30; 30-35=-5; -5-40=-45; -45-45=-90;

Exercise 3 Solve the following.

1. What is the number of zeros at the end of the product of the numbers from 1 to 100? Answer : 127 2. A fast typist can type some matter in 2 hours and a slow typist can type the same in 3 hours. If both type combinely, in how much time will they finish? Answer : 1 hr 12 min Explanation : The fast typist's work done in 1 hr = 1/2 The slow typist's work done in 1 hr = 1/3 If they work combinely, work done in 1 hr = 1/2+1/3 = 5/6 So, the work will be completed in 6/5 hours. i.e., 1+1/5 hours = 1hr 12 min 3. Gavaskar's average in his first 50 innings was 50. After the 51st innings, his average was 51. How many runs did he score in his 51st innings. (supposing that he lost his wicket in his 51st innings) Answer : 101 Explanation : Total score after 50 innings = 50*50 = 2500 Total score after 51 innings = 51*51 = 2601 So, runs made in the 51st innings = 2601-2500 = 101 If he had not lost his wicket in his 51st innings, he would have scored an unbeaten 50 in his 51st innings. 4. Out of 80 coins, one is counterfeit. What is the minimum number of weighings needed to find out the counterfeit coin? Answer : 4 5. What can you conclude from the statement : All green are blue, all blue are red. ? (i) some blue are green (ii) some red are green (iii) some green are not red (iv) all red are blue (a) i or ii but not both (b) i & ii only (c) iii or iv but not both (d) iii & iv Answer : (b) 6. A rectangular plate with length 8 inches, breadth 11 inches and thickness 2 inches is available. What is the length of the circular rod with diameter 8 inches and equal to the volume of the rectangular plate? Answer : 3.5 inches Explanation : Volume of the circular rod (cylinder) = Volume of the rectangular plate (22/7)*4*4*h = 8*11*2 h = 7/2 = 3.5

7. What is the sum of all numbers between 100 and 1000 which are divisible by 14 ? Answer : 35392 Explanation : The number closest to 100 which is greater than 100 and divisible by 14 is 112, which is the first term of the series which has to be summed. The number closest to 1000 which is less than 1000 and divisible by 14 is 994, which is the last term of the series. 112 + 126 + .... + 994 = 14(8+9+ ... + 71) = 35392 8. If s(a) denotes square root of a, find the value of s(12+s(12+s(12+ ...... upto infinity. Answer : 4 Explanation : Let x = s(12+s(12+s(12+..... We can write x = s(12+x). i.e., x^2 = 12 + x. Solving this quadratic equation, we get x = -3 or x=4. Sum cannot be -ve and hence sum = 4. 9. A cylindrical container has a radius of eight inches with a height of three inches. Compute how many inches should be added to either the radius or height to give the same increase in volume? Answer : 16/3 inches Explanation : Let x be the amount of increase. The volume will increase by the same amount if the radius increased or the height is increased. So, the effect on increasing height is equal to the effect on increasing the radius. i.e., (22/7)*8*8*(3+x) = (22/7)*(8+x)*(8+x)*3 Solving the quadratic equation we get the x = 0 or 16/3. The possible increase would be by 16/3 inches. 10. With just six weights and a balance scale, you can weigh any unit number of kgs from 1 to 364. What could be the six weights? Answer : 1, 3, 9, 27, 81, 243 (All powers of 3) 11. Diophantus passed one sixth of his life in childhood, one twelfth in youth, and one seventh more as a bachelor; five years after his marriage a son was born who died four years before his father at half his final age. How old is Diophantus? Answer : 84 years Explanation : x/6 + x/12 + x/7 + 5 + x/2 + 4 = x 12 . If time at this moment is 9 P.M., what will be the time 23999999992 hours later? Answer : 1 P.M. Explanation : 24 billion hours later, it would be 9 P.M. and 8 hours before that it would be 1 P.M. 13. How big will an angle of one and a half degree look through a glass that magnifies things three times? Answer : 1 1/2 degrees Explanation : The magnifying glass cannot increase the magnitude of an angle.

14. Divide 45 into four parts such that when 2 is added to the first part, 2 is subtracted from the second part, 2 is multiplied by the third part and the fourth part is divided by two, all result in the same number. Answer: 8, 12, 5, 20 Explanation: a + b + c + d =45; a+2 = b-2 = 2c = d/2; a=b-4; c = (b-2)/2; d = 2(b-2); b-4 + b + (b-2)/2 + 2(b-2) = 45; 15. I drove 60 km at 30 kmph and then an additional 60 km at 50 kmph. Compute my average speed over my 120 km. Answer : 37 1/2 Explanation : Time reqd for the first 60 km = 120 min.; Time reqd for the second 60 km = 72 min.; Total time reqd = 192 min Avg speed = (60*120)/192 = 37 1/2

Questions 16 and 17 are based on the following : Five executives of European Corporation hold a Conference in Rome Mr. A converses in Spanish & Italian Mr. B, a spaniard, knows English also Mr. C knows English and belongs to Italy Mr. D converses in French and Spanish Mr. E , a native of Italy knows French 16. Which of the following can act as interpreter if Mr. C & Mr. D wish to converse a) only Mr. A b) Only Mr. B c) Mr. A & Mr. B d) Any of the other three Answer : d) Any of the other three. Explanation : From the data given, we can infer the following. A knows Spanish, Italian B knows Spanish, English C knows Italian, English D knows Spanish, French E knows Italian, French To act as an interpreter between C and D, a person has to know one of the combinations Italian&Spanish, Italian&French, English&Spanish, English&French A, B, and E know atleast one of the combinations. 17. If a 6th executive is brought in, to be understood by maximum number of original five he should be fluent in a) English & French b) Italian & Spanish c) English & French d) French & Italian Answer : b) Italian & Spanish Explanation : No of executives who know i) English is 2 ii) Spanish is 3 iii) Italian is 3

iv) French is 2 Italian & Spanish are spoken by the maximum no of executives. So, if the 6th executive is fluent in Italian & Spanish, he can communicate with all the original five because everybody knows either Spanish or Italian. 18. What is the sum of the first 25 natural odd numbers? Answer : 625 Explanation : The sum of the first n natural odd nos is square(n). 1+3 = 4 = square(2) 1+3+5 = 9 = square(3) 19. The sum of any seven consecutive numbers is divisible by a) 2 b) 7 c) 3 d) 11

Exercise 3 Try the following. 1. There are seventy clerks working in a company, of which 30 are females. Also, 30 clerks are married; 24 clerks are above 25 years of age; 19 married clerks are above 25 years, of which 7 are males; 12 males are above 25 years of age; and 15 males are married. How many bachelor girls are there and how many of these are above 25? 2. A man sailed off from the North Pole. After covering 2,000 miles in one direction he turned West, sailed 2,000 miles, turned North and sailed ahead another 2,000 miles till he met his friend. How far was he from the North Pole and in what direction? 3. Here is a series of comments on the ages of three persons J, R, S by themselves. S : The difference between R's age and mine is three years. J : R is the youngest. R : Either I am 24 years old or J 25 or S 26. J : All are above 24 years of age. S : I am the eldest if and only if R is not the youngest. R : S is elder to me. J : I am the eldest. R : S is not 27 years old. S : The sum of my age and J's is two more than twice R's age. One of the three had been telling a lie throughout whereas others had spoken the truth. Determine the ages of S,J,R. 4. In a group of five people, what is the probability of finding two persons with the same month of birth? 5. A father and his son go out for a 'walk-and-run' every morning around a track formed by an equilateral triangle. The father's walking speed is 2 mph and his

running speed is 5 mph. The son's walking and running speeds are twice that of his father. Both start together from one apex of the triangle, the son going clockwise and the father anti-clockwise. Initially the father runs and the son walks for a certain period of time. Thereafter, as soon as the father starts walking, the son starts running. Both complete the course in 45 minutes. For how long does the father run? Where do the two cross each other? 6. The Director of Medical Services was on his annual visit to the ENT Hospital. While going through the out patients' records he came across the following data for a particular day : " Ear consultations 45; Nose 50; Throat 70; Ear and Nose 30; Nose and Throat 20; Ear and Throat 30; Ear, Nose and Throat 10; Total patients 100." Then he came to the conclusion that the records were bogus. Was he right? 7. Amongst Ram, Sham and Gobind are a doctor, a lawyer and a police officer. They are married to Radha, Gita and Sita (not in order). Each of the wives have a profession. Gobind's wife is an artist. Ram is not married to Gita. The lawyer's wife is a teacher. Radha is married to the police officer. Sita is an expert cook. Who's who? 8. What should come next? 1, 2, 4, 10, 16, 40, 64, Questions 9-12 are based on the following : Three adults Roberto, Sarah and Vicky will be traveling in a van with five children Freddy, Hillary, Jonathan, Lupe, and Marta. The van has a drivers seat and one passenger seat in the front, and two benches behind the front seats, one beach behind the other. Each bench has room for exactly three people. Everyone must sit in a seat or on a bench, and seating is subject to the following restrictions: An adult must sit on each bench. Either Roberto or Sarah must sit in the drivers seat. Jonathan must sit immediately beside Marta. 9. Of the following, who can sit in the front passenger seat ? (a) Jonathan (b) Lupe (c) Roberto (d) Sarah (e) Vicky 10. Which of the following groups of three can sit together on a bench? (a) Freddy, Jonathan and Marta (b) Freddy, Jonathan and Vicky (c) Freddy, Sarah and Vicky (d) Hillary, Lupe and Sarah (e) Lupe, Marta and Roberto 11. If Freddy sits immediately beside Vicky, which of the following cannot be true ? a. Jonathan sits immediately beside Sarah b. Lupe sits immediately beside Vicky c. Hillary sits in the front passenger seat d. Freddy sits on the same bench as Hillary

e. Hillary sits on the same bench as Roberto 12. If Sarah sits on a bench that is behind where Jonathan is sitting, which of the following must be true ? a. Hillary sits in a seat or on a bench that is in front of where Marta is sitting b. Lupe sits in a seat or on a bench that is in front of where Freddy is sitting c. Freddy sits on the same bench as Hillary d. Lupe sits on the same bench as Sarah e. Marta sits on the same bench as Vicky 13. Make six squares of the same size using twelve match-sticks. (Hint : You will need an adhesive to arrange the required figure) 14. A farmer has two rectangular fields. The larger field has twice the length and 4 times the width of the smaller field. If the smaller field has area K, then the are of the larger field is greater than the area of the smaller field by what amount? (a) 6K (b) 8K (c) 12K (d) 7K 15. Nine equal circles are enclosed in a square whose area is 36sq units. Find the area of each circle. 16. There are 9 cards. Arrange them in a 3*3 matrix. Cards are of 4 colors. They are red, yellow, blue, green. Conditions for arrangement: one red card must be in first row or second row. 2 green cards should be in 3rd column. Yellow cards must be in the 3 corners only. Two blue cards must be in the 2nd row. At least one green card in each row. 17. Is z less than w? z and w are real numbers. (I) z2 = 25 (II) w = 9 To answer the question, a) Either I or II is sufficient b) Both I and II are sufficient but neither of them is alone sufficient c) I & II are sufficient d) Both are not sufficient 18. A speaks truth 70% of the time; B speaks truth 80% of the time. What is the probability that both are contradicting each other? 19. In a family 7 children don't eat spinach, 6 don't eat carrot, 5 don't eat beans, 4 don't eat spinach & carrots, 3 don't eat carrot & beans, 2 don't eat beans & spinach. One doesn't eat all 3. Find the no. of children. 20. Anna, Bena, Catherina and Diana are at their monthly business meeting. Their occupations are author, biologist, chemist and doctor, but not necessarily in that order. Diana just told the neighbour, who is a biologist that Catherina was on her

way with doughnuts. Anna is sitting across from the doctor and next to the chemist. The doctor was thinking that Bena was a good name for parent's to choose, but didn't say anything. What is each person's occupation?

UNIX Concepts
UNIX Concepts
SECTION - I FILE MANAGEMENT IN UNIX 1. How are devices represented in UNIX? All devices are represented by files called special files that are located in/dev directory. Thus, device files and other files are named and accessed in the same way. A 'regular file' is just an ordinary data file in the disk. A 'block special file' represents a device with characteristics similar to a disk (data transfer in terms of blocks). A 'character special file' represents a device with characteristics similar to a keyboard (data transfer is by stream of bits in sequential order). 2. What is 'inode'? All UNIX files have its description stored in a structure called 'inode'. The inode contains info about the file-size, its location, time of last access, time of last modification, permission and so on. Directories are also represented as files and have an associated inode. In addition to descriptions about the file, the inode contains pointers to the data blocks of the file. If the file is large, inode has indirect pointer to a block of pointers to additional data blocks (this further aggregates for larger files). A block is typically 8k. Inode consists of the following fields: File owner identifier File type File access permissions File access times Number of links File size Location of the file data 3. Brief about the directory representation in UNIX A Unix directory is a file containing a correspondence between filenames and inodes. A directory is a special file that the kernel maintains. Only kernel modifies directories, but processes can read directories. The contents of a directory are a list of filename and inode number pairs. When new directories are created, kernel makes two entries named '.' (refers to the directory itself) and '..' (refers to parent directory). System call for creating directory is mkdir (pathname, mode). 4. What are the Unix system calls for I/O? open(pathname,flag,mode) - open file

creat(pathname,mode) - create file close(filedes) - close an open file read(filedes,buffer,bytes) - read data from an open file write(filedes,buffer,bytes) - write data to an open file lseek(filedes,offset,from) - position an open file dup(filedes) - duplicate an existing file descriptor dup2(oldfd,newfd) - duplicate to a desired file descriptor fcntl(filedes,cmd,arg) - change properties of an open file ioctl(filedes,request,arg) - change the behaviour of an open file The difference between fcntl anf ioctl is that the former is intended for any open file, while the latter is for device-specific operations. 5. How do you change File Access Permissions? Every file has following attributes: owner's user ID ( 16 bit integer ) owner's group ID ( 16 bit integer ) File access mode word 'r w x -r w x- r w x' (user permission-group permission-others permission) r-read, w-write, x-execute To change the access mode, we use chmod(filename,mode). Example 1: To change mode of myfile to 'rw-rw-r--' (ie. read, write permission for user read,write permission for group - only read permission for others) we give the args as: chmod(myfile,0664) . Each operation is represented by discrete values 'r' is 4 'w' is 2 'x' is 1 Therefore, for 'rw' the value is 6(4+2). Example 2: To change mode of myfile to 'rwxr--r--' we give the args as: chmod(myfile,0744). 6. What are links and symbolic links in UNIX file system? A link is a second name (not a file) for a file. Links can be used to assign more than one name to a file, but cannot be used to assign a directory more than one name or link filenames on different computers. Symbolic link 'is' a file that only contains the name of another file.Operation on the symbolic link is directed to the file pointed by the it.Both the limitations of links are eliminated in symbolic links. Commands for linking files are: Link ln filename1 filename2 Symbolic link ln -s filename1 filename2 7. What is a FIFO?

FIFO are otherwise called as 'named pipes'. FIFO (first-in-first-out) is a special file which is said to be data transient. Once data is read from named pipe, it cannot be read again. Also, data can be read only in the order written. It is used in interprocess communication where a process writes to one end of the pipe (producer) and the other reads from the other end (consumer). 8. How do you create special files like named pipes and device files? The system call mknod creates special files in the following sequence. 1. kernel assigns new inode, 2. sets the file type to indicate that the file is a pipe, directory or special file, 3. If it is a device file, it makes the other entries like major, minor device numbers. For example: If the device is a disk, major device number refers to the disk controller and minor device number is the disk. 9. Discuss the mount and unmount system calls The privileged mount system call is used to attach a file system to a directory of another file system; the unmount system call detaches a file system. When you mount another file system on to your directory, you are essentially splicing one directory tree onto a branch in another directory tree. The first argument to mount call is the mount point, that is , a directory in the current file naming system. The second argument is the file system to mount to that point. When you insert a cdrom to your unix system's drive, the file system in the cdrom automatically mounts to /dev/cdrom in your system. 10. How does the inode map to data block of a file? Inode has 13 block addresses. The first 10 are direct block addresses of the first 10 data blocks in the file. The 11th address points to a one-level index block. The 12th address points to a two-level (double in-direction) index block. The 13th address points to a three-level(triple in-direction)index block. This provides a very large maximum file size with efficient access to large files, but also small files are accessed directly in one disk read. 11. What is a shell? A shell is an interactive user interface to an operating system services that allows an user to enter commands as character strings or through a graphical user interface. The shell converts them to system calls to the OS or forks off a process to execute the command. System call results and other information from the OS are presented to the user through an interactive interface. Commonly used shells are sh,csh,ks etc. SECTION - II PROCESS MODEL and IPC 1. Brief about the initial process sequence while the system boots up. While booting, special process called the 'swapper' or 'scheduler' is created with Process-ID 0. The swapper manages memory allocation for processes and influences CPU allocation. The swapper inturn creates 3 children:

the process dispatcher, vhand and dbflush with IDs 1,2 and 3 respectively. This is done by executing the file /etc/init. Process dispatcher gives birth to the shell. Unix keeps track of all the processes in an internal data structure called the Process Table (listing command is ps -el). 2. What are various IDs associated with a process? Unix identifies each process with a unique integer called ProcessID. The process that executes the request for creation of a process is called the 'parent process' whose PID is 'Parent Process ID'. Every process is associated with a particular user called the 'owner' who has privileges over the process. The identification for the user is 'UserID'. Owner is the user who executes the process. Process also has 'Effective User ID' which determines the access privileges for accessing resources like files. getpid() -process id getppid() -parent process id getuid() -user id geteuid() -effective user id 3. Explain fork() system call. The `fork()' used to create a new process from an existing process. The new process is called the child process, and the existing process is called the parent. We can tell which is which by checking the return value from `fork()'. The parent gets the child's pid returned to him, but the child gets 0 returned to him. 4. Predict the output of the following program code main() { fork(); printf("Hello World!"); } Answer: Hello World!Hello World! Explanation: The fork creates a child that is a duplicate of the parent process. The child begins from the fork().All the statements after the call to fork() will be executed twice.(once by the parent process and other by child). The statement before fork() is executed only by the parent process. 5. Predict the output of the following program code main() { fork(); fork(); fork(); printf("Hello World!"); }

Answer: "Hello World" will be printed 8 times. Explanation: 2^n times where n is the number of calls to fork() 6. List the system calls used for process management: System calls Description fork() To create a new process exec() To execute a new program in a process wait() To wait until a created process completes its execution exit() To exit from a process execution getpid() To get a process identifier of the current process getppid() To get parent process identifier nice() To bias the existing priority of a process brk() To increase/decrease the data segment size of a process 7. How can you get/set an environment variable from a program? Getting the value of an environment variable is done by using `getenv()'. Setting the value of an environment variable is done by using `putenv()'. 8. How can a parent and child process communicate? A parent and child can communicate through any of the normal inter-process communication schemes (pipes, sockets, message queues, shared memory), but also have some special ways to communicate that take advantage of their relationship as a parent and child. One of the most obvious is that the parent can get the exit status of the child. 9. What is a zombie? When a program forks and the child finishes before the parent, the kernel still keeps some of its information about the child in case the parent might need it - for example, the parent may need to check the child's exit status. To be able to get this information, the parent calls `wait()'; In the interval between the child terminating and the parent calling `wait()', the child is said to be a `zombie' (If you do `ps', the child will have a `Z' in its status field to indicate this.) 10. What are the process states in Unix? As a process executes it changes state according to its circumstances. Unix processes have the following states: Running : The process is either running or it is ready to run . Waiting : The process is waiting for an event or for a resource. Stopped : The process has been stopped, usually by receiving a signal. Zombie : The process is dead but have not been removed from the process table. 11. What Happens when you execute a program? When you execute a program on your UNIX system, the system creates a special environment for that program. This environment contains everything needed for the system to run the program as if no other program were running on the system. Each

process has process context, which is everything that is unique about the state of the program you are currently running. Every time you execute a program the UNIX system does a fork, which performs a series of operations to create a process context and then execute your program in that context. The steps include the following: Allocate a slot in the process table, a list of currently running programs kept by UNIX. Assign a unique process identifier (PID) to the process. iCopy the context of the parent, the process that requested the spawning of the new process. Return the new PID to the parent process. This enables the parent process to examine or control the process directly. After the fork is complete, UNIX runs your program. 12. What Happens when you execute a command? When you enter 'ls' command to look at the contents of your current working directory, UNIX does a series of things to create an environment for ls and the run it: The shell has UNIX perform a fork. This creates a new process that the shell will use to run the ls program. The shell has UNIX perform an exec of the ls program. This replaces the shell program and data with the program and data for ls and then starts running that new program. The ls program is loaded into the new process context, replacing the text and data of the shell. The ls program performs its task, listing the contents of the current directory. 13. What is a Daemon? A daemon is a process that detaches itself from the terminal and runs, disconnected, in the background, waiting for requests and responding to them. It can also be defined as the background process that does not belong to a terminal session. Many system functions are commonly performed by daemons, including the sendmail daemon, which handles mail, and the NNTP daemon, which handles USENET news. Many other daemons may exist. Some of the most common daemons are: init: Takes over the basic running of the system when the kernel has finished the boot process. inetd: Responsible for starting network services that do not have their own standalone daemons. For example, inetd usually takes care of incoming rlogin, telnet, and ftp connections. cron: Responsible for running repetitive tasks on a regular schedule. 14. What is 'ps' command for? The ps command prints the process status for some or all of the running processes. The information given are the process identification number (PID),the amount of time that the process has taken to execute so far etc. 15. How would you kill a process? The kill command takes the PID as one argument; this identifies which process to terminate. The PID of a process can be got using 'ps' command.

16. What is an advantage of executing a process in background? The most common reason to put a process in the background is to allow you to do something else interactively without waiting for the process to complete. At the end of the command you add the special background symbol, &. This symbol tells your shell to execute the given command in the background. Example: cp *.* ../backup& (cp is for copy) 17. How do you execute one program from within another? The system calls used for low-level process creation are execlp() and execvp(). The execlp call overlays the existing program with the new one , runs that and exits. The original program gets back control only when an error occurs. execlp(path,file_name,arguments..); //last argument must be NULL A variant of execlp called execvp is used when the number of arguments is not known in advance. execvp(path,argument_array); //argument array should be terminated by NULL 18. What is IPC? What are the various schemes available? The term IPC (Inter-Process Communication) describes various ways by which different process running on some operating system communicate between each other. Various schemes available are as follows: Pipes: One-way communication scheme through which different process can communicate. The problem is that the two processes should have a common ancestor (parent-child relationship). However this problem was fixed with the introduction of named-pipes (FIFO). Message Queues : Message queues can be used between related and unrelated processes running on a machine. Shared Memory: This is the fastest of all IPC schemes. The memory to be shared is mapped into the address space of the processes (that are sharing). The speed achieved is attributed to the fact that there is no kernel involvement. But this scheme needs synchronization. Various forms of synchronisation are mutexes, condition-variables, read-write locks, record-locks, and semaphores. SECTION - III MEMORY MANAGEMENT 1. What is the difference between Swapping and Paging? Swapping: Whole process is moved from the swap device to the main memory for execution. Process size must be less than or equal to the available main memory. It is

easier to implementation and overhead to the system. Swapping systems does not handle the memory more flexibly as compared to the paging systems. Paging: Only the required memory pages are moved to main memory from the swap device for execution. Process size does not matter. Gives the concept of the virtual memory. It provides greater flexibility in mapping the virtual address space into the physical memory of the machine. Allows more number of processes to fit in the main memory simultaneously. Allows the greater process size than the available physical memory. Demand paging systems handle the memory more flexibly. 2. What is major difference between the Historic Unix and the new BSD release of Unix System V in terms of Memory Management? Historic Unix uses Swapping entire process is transferred to the main memory from the swap device, whereas the Unix System V uses Demand Paging only the part of the process is moved to the main memory. Historic Unix uses one Swap Device and Unix System V allow multiple Swap Devices. 3. What is the main goal of the Memory Management? It decides which process should reside in the main memory, Manages the parts of the virtual address space of a process which is non-core resident, Monitors the available main memory and periodically write the processes into the swap device to provide more processes fit in the main memory simultaneously. 4. What is a Map? A Map is an Array, which contains the addresses of the free space in the swap device that are allocatable resources, and the number of the resource units available there. Address 1 Units 10,000

This allows First-Fit allocation of contiguous blocks of a resource. Initially the Map contains one entry address (block offset from the starting of the swap area) and the total number of resources. Kernel treats each unit of Map as a group of disk blocks. On the allocation and freeing of the resources Kernel updates the Map for accurate information. 5. What scheme does the Kernel in Unix System V follow while choosing a swap device among the multiple swap devices? Kernel follows Round Robin scheme choosing a swap device among the multiple swap devices in Unix System V. 6. What is a Region?

A Region is a continuous area of a processs address space (such as text, data and stack). The kernel in a Region Table that is local to the process maintains region. Regions are sharable among the process. 7. What are the events done by the Kernel after a process is being swapped out from the main memory? When Kernel swaps the process out of the primary memory, it performs the following: Kernel decrements the Reference Count of each region of the process. If the reference count becomes zero, swaps the region out of the main memory, Kernel allocates the space for the swapping process in the swap device, Kernel locks the other swapping process while the current swapping operation is going on, The Kernel saves the swap address of the region in the region table. 8. Is the Process before and after the swap are the same? Give reason. Process before swapping is residing in the primary memory in its original form. The regions (text, data and stack) may not be occupied fully by the process, there may be few empty slots in any of the regions and while swapping Kernel do not bother about the empty slots while swapping the process out. After swapping the process resides in the swap (secondary memory) device. The regions swapped out will be present but only the occupied region slots but not the empty slots that were present before assigning. While swapping the process once again into the main memory, the Kernel referring to the Process Memory Map, it assigns the main memory accordingly taking care of the empty slots in the regions. 9. What do you mean by u-area (user area) or u-block? This contains the private data that is manipulated only by the Kernel. This is local to the Process, i.e. each process is allocated a u-area. 10. What are the entities that are swapped out of the main memory while swapping the process out of the main memory? All memory space occupied by the process, processs u-area, and Kernel stack are swapped out, theoretically. Practically, if the processs u-area contains the Address Translation Tables for the process then Kernel implementations do not swap the u-area. 11. What is Fork swap? fork() is a system call to create a child process. When the parent process calls fork() system call, the child process is created and if there is short of memory then the child process is sent to the read-to-run state in the swap device, and return to the user state without swapping the parent process. When the memory will be available the child process will be swapped into the main memory. 12. What is Expansion swap?

At the time when any process requires more memory than it is currently allocated, the Kernel performs Expansion swap. To do this Kernel reserves enough space in the swap device. Then the address translation mapping is adjusted for the new virtual address space but the physical memory is not allocated. At last Kernel swaps the process into the assigned space in the swap device. Later when the Kernel swaps the process into the main memory this assigns memory according to the new address translation mapping. 13. How the Swapper works? The swapper is the only process that swaps the processes. The Swapper operates only in the Kernel mode and it does not uses System calls instead it uses internal Kernel functions for swapping. It is the archetype of all kernel process. 14. What are the processes that are not bothered by the swapper? Give Reason. Zombie process: They do not take any up physical memory. Processes locked in memories that are updating the region of the process. Kernel swaps only the sleeping processes rather than the ready-to-run processes, as they have the higher probability of being scheduled than the Sleeping processes. 15. What are the requirements for a swapper to work? The swapper works on the highest scheduling priority. Firstly it will look for any sleeping process, if not found then it will look for the ready-to-run process for swapping. But the major requirement for the swapper to work the ready-to-run process must be core-resident for at least 2 seconds before swapping out. And for swapping in the process must have been resided in the swap device for at least 2 seconds. If the requirement is not satisfied then the swapper will go into the wait state on that event and it is awaken once in a second by the Kernel. 16. What are the criteria for choosing a process for swapping into memory from the swap device? The resident time of the processes in the swap device, the priority of the processes and the amount of time the processes had been swapped out. 17. What are the criteria for choosing a process for swapping out of the memory to the swap device? The processs memory resident time, Priority of the process and The nice value. 18. What do you mean by nice value? Nice value is the value that controls {increments or decrements} the priority of the process. This value that is returned by the nice () system call. The equation for using nice value is: Priority = (recent CPU usage/constant) + (base- priority) + (nice value)

Only the administrator can supply the nice value. The nice () system call works for the running process only. Nice value of one process cannot affect the nice value of the other process. 19. What are conditions on which deadlock can occur while swapping the processes? All processes in the main memory are asleep. All ready-to-run processes are swapped out. There is no space in the swap device for the new incoming process that are swapped out of the main memory. There is no space in the main memory for the new incoming process. 20. What are conditions for a machine to support Demand Paging? Memory architecture must based on Pages, The machine must support the restartable instructions. 21. What is the principle of locality? Its the nature of the processes that they refer only to the small subset of the total data space of the process. i.e. the process frequently calls the same subroutines or executes the loop instructions. 22. What is the working set of a process? The set of pages that are referred by the process in the last n, references, where n is called the window of the working set of the process. 23. What is the window of the working set of a process? The window of the working set of a process is the total number in which the process had referred the set of pages in the working set of the process. 24. What is called a page fault? Page fault is referred to the situation when the process addresses a page in the working set of the process but the process fails to locate the page in the working set. And on a page fault the kernel updates the working set by reading the page from the secondary device. 25. What are data structures that are used for Demand Paging? Kernel contains 4 data structures for Demand paging. They are, Page table entries, Disk block descriptors, Page frame data table (pfdata), Swap-use table. 26. What are the bits that support the demand paging? Valid, Reference, Modify, Copy on write, Age. These bits are the part of the page table entry, which includes physical address of the page and protection bits. Page address

Age Copy on write

Modify Reference

Valid Protection

27. How the Kernel handles the fork() system call in traditional Unix and in the System V Unix, while swapping? Kernel in traditional Unix, makes the duplicate copy of the parents address space and attaches it to the childs process, while swapping. Kernel in System V Unix, manipulates the region tables, page table, and pfdata table entries, by incrementing the reference count of the region table of shared regions. 28. Difference between the fork() and vfork() system call? During the fork() system call the Kernel makes a copy of the parent processs address space and attaches it to the child process. But the vfork() system call do not makes any copy of the parents address space, so it is faster than the fork() system call. The child process as a result of the vfork() system call executes exec() system call. The child process from vfork() system call executes in the parents address space (this can overwrite the parents data and stack ) which suspends the parent process until the child process exits. 29. What is BSS(Block Started by Symbol)? A data representation at the machine level, that has initial values when a program starts and tells about how much space the kernel allocates for the un-initialized data. Kernel initializes it to zero at run-time. 30. What is Page-Stealer process? This is the Kernel process that makes rooms for the incoming pages, by swapping the memory pages that are not the part of the working set of a process. Page-Stealer is created by the Kernel at the system initialization and invokes it throughout the lifetime of the system. Kernel locks a region when a process faults on a page in the region, so that page stealer cannot steal the page, which is being faulted in. 31. Name two paging states for a page in memory? The two paging states are: The page is aging and is not yet eligible for swapping, The page is eligible for swapping but not yet eligible for reassignment to other virtual address space. 32. What are the phases of swapping a page from the memory? Page stealer finds the page eligible for swapping and places the page number in the list of pages to be swapped. Kernel copies the page to a swap device when necessary and clears the valid bit in the page table entry, decrements the pfdata reference count, and places the pfdata table entry at the end of the free list if its reference count is 0. 33. What is page fault? Its types? Page fault refers to the situation of not having a page in the main memory when any process references it.

There are two types of page fault : Validity fault, Protection fault. 34. In what way the Fault Handlers and the Interrupt handlers are different? Fault handlers are also an interrupt handler with an exception that the interrupt handlers cannot sleep. Fault handlers sleep in the context of the process that caused the memory fault. The fault refers to the running process and no arbitrary processes are put to sleep. 35. What is validity fault? If a process referring a page in the main memory whose valid bit is not set, it results in validity fault. The valid bit is not set for those pages: that are outside the virtual address space of a process, that are the part of the virtual address space of the process but no physical address is assigned to it. 36. What does the swapping system do if it identifies the illegal page for swapping? If the disk block descriptor does not contain any record of the faulted page, then this causes the attempted memory reference is invalid and the kernel sends a Segmentation violation signal to the offending process. This happens when the swapping system identifies any invalid memory reference. 37. What are states that the page can be in, after causing a page fault? On a swap device and not in memory, On the free page list in the main memory, In an executable file, Marked demand zero, Marked demand fill. 38. In what way the validity fault handler concludes? It sets the valid bit of the page by clearing the modify bit. It recalculates the process priority. 39. At what mode the fault handler executes? At the Kernel Mode. 40. What do you mean by the protection fault? Protection fault refers to the process accessing the pages, which do not have the access permission. A process also incur the protection fault when it attempts to write a page whose copy on write bit was set during the fork() system call. 41. How the Kernel handles the copy on write bit of a page, when the bit is set? In situations like, where the copy on write bit of a page is set and that page is shared by more than one process, the Kernel allocates new page and copies the content to

the new page and the other processes retain their references to the old page. After copying the Kernel updates the page table entry with the new page number. Then Kernel decrements the reference count of the old pfdata table entry. In cases like, where the copy on write bit is set and no processes are sharing the page, the Kernel allows the physical page to be reused by the processes. By doing so, it clears the copy on write bit and disassociates the page from its disk copy (if one exists), because other process may share the disk copy. Then it removes the pfdata table entry from the page-queue as the new copy of the virtual page is not on the swap device. It decrements the swap-use count for the page and if count drops to 0, frees the swap space. 42. For which kind of fault the page is checked first? The page is first checked for the validity fault, as soon as it is found that the page is invalid (valid bit is clear), the validity fault handler returns immediately, and the process incur the validity page fault. Kernel handles the validity fault and the process will incur the protection fault if any one is present. 43. In what way the protection fault handler concludes? After finishing the execution of the fault handler, it sets the modify and protection bits and clears the copy on write bit. It recalculates the process-priority and checks for signals. 44. How the Kernel handles both the page stealer and the fault handler? The page stealer and the fault handler thrash because of the shortage of the memory. If the sum of the working sets of all processes is greater that the physical memory then the fault handler will usually sleep because it cannot allocate pages for a process. This results in the reduction of the system throughput because Kernel spends too much time in overhead, rearranging the memory in the frantic pace.

Computer Networks
Computer Networks
1. What are the two types of transmission technology available? (i) Broadcast and (ii) point-to-point 2. What is subnet? A generic term for section of a large networks usually separated by a bridge or router. 3. Difference between the communication and transmission. Transmission is a physical movement of information and concern issues like bit polarity, synchronisation, clock etc. Communication means the meaning full exchange of information between two communication media. 4. What are the possible ways of data exchange? (i) Simplex (ii) Half-duplex (iii) Full-duplex. 5. What is SAP? Series of interface points that allow other computers to communicate with the other layers of network protocol stack. 6. What do you meant by "triple X" in Networks? The function of PAD (Packet Assembler Disassembler) is described in a document known as X.3. The standard protocol has been defined between the terminal and the PAD, called X.28; another standard protocol exists between hte PAD and the network, called X.29. Together, these three recommendations are often called "triple X" 7. What is frame relay, in which layer it comes? Frame relay is a packet switching technology. It will operate in the data link layer. 8. What is terminal emulation, in which layer it comes? Telnet is also called as terminal emulation. It belongs to application layer. 9. What is Beaconing? The process that allows a network to self-repair networks problems. The stations on the network notify the other stations on the ring when they are not receiving the transmissions. Beaconing is used in Token ring and FDDI networks.

10. What is redirector? Redirector is software that intercepts file or prints I/O requests and translates them into network requests. This comes under presentation layer. 11. What is NETBIOS and NETBEUI? NETBIOS is a programming interface that allows I/O requests to be sent to and received from a remote computer and it hides the networking hardware from applications. NETBEUI is NetBIOS extended user interface. A transport protocol designed by microsoft and IBM for the use on small subnets. 12. What is RAID? A method for providing fault tolerance by using multiple hard disk drives. 13. What is passive topology? When the computers on the network simply listen and receive the signal, they are referred to as passive because they dont amplify the signal in any way. Example for passive topology - linear bus. 14. What is Brouter? Hybrid devices that combine the features of both bridges and routers. 15. What is cladding? A layer of a glass surrounding the center fiber of glass inside a fiber-optic cable. 16. What is point-to-point protocol A communications protocol used to connect computers to remote networking services including Internet service providers. 17. How Gateway is different from Routers? A gateway operates at the upper levels of the OSI model and translates information between two completely different network architectures or data formats 18. What is attenuation? The degeneration of a signal over distance on a network cable is called attenuation. 19. What is MAC address? The address for a device as it is identified at the Media Access Control (MAC) layer in the network architecture. MAC address is usually stored in ROM on the network adapter card and is unique. 20. Difference between bit rate and baud rate. Bit rate is the number of bits transmitted during one second whereas baud rate refers to the number of signal units per second that are required to represent those bits. baud rate = bit rate / N

where N is no-of-bits represented by each signal shift. 21. What is Bandwidth? Every line has an upper limit and a lower limit on the frequency of signals it can carry. This limited range is called the bandwidth. 22. What are the types of Transmission media? Signals are usually transmitted over some transmission media that are broadly classified in to two categories. a) Guided Media: These are those that provide a conduit from one device to another that include twisted-pair, coaxial cable and fiber-optic cable. A signal traveling along any of these media is directed and is contained by the physical limits of the medium. Twistedpair and coaxial cable use metallic that accept and transport signals in the form of electrical current. Optical fiber is a glass or plastic cable that accepts and transports signals in the form of light. b) Unguided Media: This is the wireless media that transport electromagnetic waves without using a physical conductor. Signals are broadcast either through air. This is done through radio communication, satellite communication and cellular telephony. 23. What is Project 802? It is a project started by IEEE to set standards to enable intercommunication between equipment from a variety of manufacturers. It is a way for specifying functions of the physical layer, the data link layer and to some extent the network layer to allow for interconnectivity of major LAN protocols. It consists of the following: 802.1 is an internetworking standard for compatibility of different LANs and MANs across protocols. 802.2 Logical link control (LLC) is the upper sublayer of the data link layer which is non-architecture-specific, that is remains the same for all IEEE-defined LANs. Media access control (MAC) is the lower sublayer of the data link layer that contains some distinct modules each carrying proprietary information specific to the LAN product being used. The modules are Ethernet LAN (802.3), Token ring LAN (802.4), Token bus LAN (802.5). 802.6 is distributed queue dual bus (DQDB) designed to be used in MANs. 24. What is Protocol Data Unit? The data unit in the LLC level is called the protocol data unit (PDU). The PDU contains of four fields a destination service access point (DSAP), a source service access point (SSAP), a control field and an information field. DSAP, SSAP are addresses used by the LLC to identify the protocol stacks on the receiving and sending machines that are generating and using the data. The control field specifies whether the PDU frame is a information frame (I - frame) or a supervisory frame (S - frame) or a unnumbered frame (U - frame).

25. What are the different type of networking / internetworking devices? Repeater: Also called a regenerator, it is an electronic device that operates only at physical layer. It receives the signal in the network before it becomes weak, regenerates the original bit pattern and puts the refreshed copy back in to the link. Bridges: These operate both in the physical and data link layers of LANs of same type. They divide a larger network in to smaller segments. They contain logic that allow them to keep the traffic for each segment separate and thus are repeaters that relay a frame only the side of the segment containing the intended recipent and control congestion. Routers: They relay packets among multiple interconnected networks (i.e. LANs of different type). They operate in the physical, data link and network layers. They contain software that enable them to determine which of the several possible paths is the best for a particular transmission. Gateways: They relay packets among networks that have different protocols (e.g. between a LAN and a WAN). They accept a packet formatted for one protocol and convert it to a packet formatted for another protocol before forwarding it. They operate in all seven layers of the OSI model. 26. What is ICMP? ICMP is Internet Control Message Protocol, a network layer protocol of the TCP/IP suite used by hosts and gateways to send notification of datagram problems back to the sender. It uses the echo test / reply to test whether a destination is reachable and responding. It also handles both control and error messages. 27. What are the data units at different layers of the TCP / IP protocol suite? The data unit created at the application layer is called a message, at the transport layer the data unit created is called either a segment or an user datagram, at the network layer the data unit created is called the datagram, at the data link layer the datagram is encapsulated in to a frame and finally transmitted as signals along the transmission media. 28. What is difference between ARP and RARP? The address resolution protocol (ARP) is used to associate the 32 bit IP address with the 48 bit physical address, used by a host or a router to find the physical address of another host on its network by sending a ARP query packet that includes the IP address of the receiver. The reverse address resolution protocol (RARP) allows a host to discover its Internet address when it knows only its physical address. 29. What is the minimum and maximum length of the header in the TCP segment and IP datagram?

The header should have a minimum length of 20 bytes and can have a maximum length of 60 bytes. 30. What is the range of addresses in the classes of internet addresses? Class A 0.0.0.0 127.255.255.255 Class B 128.0.0.0 191.255.255.255 Class C 192.0.0.0 223.255.255.255 Class D 224.0.0.0 239.255.255.255 Class E 240.0.0.0 247.255.255.255 31. What is the difference between TFTP and FTP application layer protocols? The Trivial File Transfer Protocol (TFTP) allows a local host to obtain files from a remote host but does not provide reliability or security. It uses the fundamental packet delivery services offered by UDP. The File Transfer Protocol (FTP) is the standard mechanism provided by TCP / IP for copying a file from one host to another. It uses the services offer by TCP and so is reliable and secure. It establishes two connections (virtual circuits) between the hosts, one for data transfer and another for control information. 32. What are major types of networks and explain? Server-based network Peer-to-peer network Peer-to-peer network, computers can act as both servers sharing resources and as clients using the resources. Server-based networks provide centralized control of network resources and rely on server computers to provide security and network administration 33. What are the important topologies for networks? BUS topology: In this each computer is directly connected to primary network cable in a single line. Advantages: Inexpensive, easy to install, simple to understand, easy to extend. STAR topology: In this all computers are connected using a central hub. Advantages: Can be inexpensive, easy to install and reconfigure and easy to trouble shoot physical problems. RING topology: In this all computers are connected in loop. Advantages: All computers have equal access to network media, installation can be simple, and signal does not degrade as much as in other topologies because each computer regenerates it.

34. What is mesh network? A network in which there are multiple network links between computers to provide multiple paths for data to travel. 35. What is difference between baseband and broadband transmission? In a baseband transmission, the entire bandwidth of the cable is consumed by a single signal. In broadband transmission, signals are sent on multiple frequencies, allowing multiple signals to be sent simultaneously. 36. Explain 5-4-3 rule? In a Ethernet network, between any two points on the network ,there can be no more than five network segments or four repeaters, and of those five segments only three of segments can be populated. 37. What MAU? In token Ring , hub is called Multistation Access Unit(MAU). 38. What is the difference between routable and non- routable protocols? Routable protocols can work with a router and can be used to build large networks. Non-Routable protocols are designed to work on small, local networks and cannot be used with a router 39. Why should you care about the OSI Reference Model? It provides a framework for discussing network operations and design. 40. What is logical link control? One of two sublayers of the data link layer of OSI reference model, as defined by the IEEE 802 standard. This sublayer is responsible for maintaining the link between computers when they are sending data across the physical network connection. 41. What is virtual channel? Virtual channel is normally a connection from one source to one destination, although multicast connections are also permitted. The other name for virtual channel is virtual circuit. 42. What is virtual path? Along any transmission path from a given source to a given destination, a group of virtual circuits can be grouped together into what is called path. 43. What is packet filter? Packet filter is a standard router equipped with some extra functionality. The extra functionality allows every incoming or outgoing packet to be inspected. Packets meeting some criterion are forwarded normally. Those that fail the test are dropped. 44. What is traffic shaping?

One of the main causes of congestion is that traffic is often busy. If hosts could be made to transmit at a uniform rate, congestion would be less common. Another open loop method to help manage congestion is forcing the packet to be transmitted at a more predictable rate. This is called traffic shaping. 45. What is multicast routing? Sending a message to a group is called multicasting, and its routing algorithm is called multicast routing. 46. What is region? When hierarchical routing is used, the routers are divided into what we will call regions, with each router knowing all the details about how to route packets to destinations within its own region, but knowing nothing about the internal structure of other regions. 47. What is silly window syndrome? It is a problem that can ruin TCP performance. This problem occurs when data are passed to the sending TCP entity in large blocks, but an interactive application on the receiving side reads 1 byte at a time. 48. What are Digrams and Trigrams? The most common two letter combinations are called as digrams. e.g. th, in, er, re and an. The most common three letter combinations are called as trigrams. e.g. the, ing, and, and ion. 49. Expand IDEA. IDEA stands for International Data Encryption Algorithm. 50. What is wide-mouth frog? Wide-mouth frog is the simplest known key distribution center (KDC) authentication protocol. 51. What is Mail Gateway? It is a system that performs a protocol translation between different electronic mail delivery protocols. 52. What is IGP (Interior Gateway Protocol)? It is any routing protocol used within an autonomous system. 53. What is EGP (Exterior Gateway Protocol)? It is the protocol the routers in neighboring autonomous systems use to identify the set of networks that can be reached within or via each autonomous system. 54. What is autonomous system? It is a collection of routers under the control of a single administrative authority and that uses a common Interior Gateway Protocol.

55. What is BGP (Border Gateway Protocol)? It is a protocol used to advertise the set of networks that can be reached with in an autonomous system. BGP enables this information to be shared with the autonomous system. This is newer than EGP (Exterior Gateway Protocol). 56. What is Gateway-to-Gateway protocol? It is a protocol formerly used to exchange routing information between Internet core routers. 57. What is NVT (Network Virtual Terminal)? It is a set of rules defining a very simple virtual terminal interaction. The NVT is used in the start of a Telnet session. 58. What is a Multi-homed Host? It is a host that has a multiple network interfaces and that requires multiple IP addresses is called as a Multi-homed Host. 59. What is Kerberos? It is an authentication service developed at the Massachusetts Institute of Technology. Kerberos uses encryption to prevent intruders from discovering passwords and gaining unauthorized access to files. 60. What is OSPF? It is an Internet routing protocol that scales well, can route traffic along multiple paths, and uses knowledge of an Internet's topology to make accurate routing decisions. 61. What is Proxy ARP? It is using a router to answer ARP requests. This will be done when the originating host believes that a destination is local, when in fact is lies beyond router.

62. What is SLIP (Serial Line Interface Protocol)? It is a very simple protocol used for transmission of IP datagrams across a serial line. 63. What is RIP (Routing Information Protocol)? It is a simple protocol used to exchange information between the routers. 64. What is source route? It is a sequence of IP addresses identifying the route a datagram must follow. A source route may optionally be included in an IP datagram header.

Operating Systems
Operating Systems
Following are a few basic questions that cover the essentials of OS: 1. Explain the concept of Reentrancy. It is a useful, memory-saving technique for multiprogrammed timesharing systems. A Reentrant Procedure is one in which multiple users can share a single copy of a program during the same period. Reentrancy has 2 key aspects: The program code cannot modify itself, and the local data for each user process must be stored separately. Thus, the permanent part is the code, and the temporary part is the pointer back to the calling program and local variables used by that program. Each execution instance is called activation. It executes the code in the permanent part, but has its own copy of local variables/parameters. The temporary part associated with each activation is the activation record. Generally, the activation record is kept on the stack. Note: A reentrant procedure can be interrupted and called by an interrupting program, and still execute correctly on returning to the procedure. 2. Explain Belady's Anomaly. Also called FIFO anomaly. Usually, on increasing the number of frames allocated to a process' virtual memory, the process execution is faster, because fewer page faults occur. Sometimes, the reverse happens, i.e., the execution time increases even when more frames are allocated to the process. This is Belady's Anomaly. This is true for certain page reference patterns. 3. What is a binary semaphore? What is its use? A binary semaphore is one, which takes only 0 and 1 as values. They are used to implement mutual exclusion and synchronize concurrent processes. 4. What is thrashing? It is a phenomenon in virtual memory schemes when the processor spends most of its time swapping pages, rather than executing instructions. This is due to an inordinate number of page faults. 5. List the Coffman's conditions that lead to a deadlock. Mutual Exclusion: Only one process may use a critical resource at a time. Hold & Wait: A process may be allocated some resources while waiting for others. No Pre-emption: No resource can be forcible removed from a process holding it. Circular Wait: A closed chain of processes exist such that each process holds at least one resource needed by another process in the chain.

6. What are short-, long- and medium-term scheduling? Long term scheduler determines which programs are admitted to the system for processing. It controls the degree of multiprogramming. Once admitted, a job becomes a process. Medium term scheduling is part of the swapping function. This relates to processes that are in a blocked or suspended state. They are swapped out of real-memory until they are ready to execute. The swapping-in decision is based on memorymanagement criteria. Short term scheduler, also know as a dispatcher executes most frequently, and makes the finest-grained decision of which process should execute next. This scheduler is invoked whenever an event occurs. It may lead to interruption of one process by preemption. 7. What are turnaround time and response time? Turnaround time is the interval between the submission of a job and its completion. Response time is the interval between submission of a request, and the first response to that request. 8. What are the typical elements of a process image? User data: Modifiable part of user space. May include program data, user stack area, and programs that may be modified. User program: The instructions to be executed. System Stack: Each process has one or more LIFO stacks associated with it. Used to store parameters and calling addresses for procedure and system calls. Process control Block (PCB): Info needed by the OS to control processes. 9. What is the Translation Lookaside Buffer (TLB)? In a cached system, the base addresses of the last few referenced pages is maintained in registers called the TLB that aids in faster lookup. TLB contains those page-table entries that have been most recently used. Normally, each virtual memory reference causes 2 physical memory accesses-- one to fetch appropriate page-table entry, and one to fetch the desired data. Using TLB in-between, this is reduced to just one physical memory access in cases of TLB-hit. 10. What is the resident set and working set of a process? Resident set is that portion of the process image that is actually in real-memory at a particular instant. Working set is that subset of resident set that is actually needed for execution. (Relate this to the variable-window size method for swapping techniques.) 11. When is a system in safe state? The set of dispatchable processes is in a safe state if there exists at least one temporal order in which all processes can be run to completion without resulting in a deadlock.

12. What is cycle stealing? We encounter cycle stealing in the context of Direct Memory Access (DMA). Either the DMA controller can use the data bus when the CPU does not need it, or it may force the CPU to temporarily suspend operation. The latter technique is called cycle stealing. Note that cycle stealing can be done only at specific break points in an instruction cycle. 13. What is meant by arm-stickiness? If one or a few processes have a high access rate to data on one track of a storage disk, then they may monopolize the device by repeated requests to that track. This generally happens with most common device scheduling algorithms (LIFO, SSTF, CSCAN, etc). High-density multisurface disks are more likely to be affected by this than low density ones. 14. What are the stipulations of C2 level security? C2 level security provides for: Discretionary Access Control Identification and Authentication Auditing Resource reuse 15. What is busy waiting? The repeated execution of a loop of code while waiting for an event to occur is called busy-waiting. The CPU is not engaged in any real productive activity during this period, and the process does not progress toward completion. 16. Explain the popular multiprocessor thread-scheduling strategies. Load Sharing: Processes are not assigned to a particular processor. A global queue of threads is maintained. Each processor, when idle, selects a thread from this queue. Note that load balancing refers to a scheme where work is allocated to processors on a more permanent basis. Gang Scheduling: A set of related threads is scheduled to run on a set of processors at the same time, on a 1-to-1 basis. Closely related threads / processes may be scheduled this way to reduce synchronization blocking, and minimize process switching. Group scheduling predated this strategy. Dedicated processor assignment: Provides implicit scheduling defined by assignment of threads to processors. For the duration of program execution, each program is allocated a set of processors equal in number to the number of threads in the program. Processors are chosen from the available pool. Dynamic scheduling: The number of thread in a program can be altered during the course of execution. 17. When does the condition 'rendezvous' arise? In message passing, it is the condition in which, both, the sender and receiver are blocked until the message is delivered.

18. What is a trap and trapdoor? Trapdoor is a secret undocumented entry point into a program used to grant access without normal methods of access authentication. A trap is a software interrupt, usually the result of an error condition. 19. What are local and global page replacements? Local replacement means that an incoming page is brought in only to the relevant process' address space. Global replacement policy allows any page frame from any process to be replaced. The latter is applicable to variable partitions model only. 20. Define latency, transfer and seek time with respect to disk I/O. Seek time is the time required to move the disk arm to the required track. Rotational delay or latency is the time it takes for the beginning of the required sector to reach the head. Sum of seek time (if any) and latency is the access time. Time taken to actually transfer a span of data is transfer time. 21. Describe the Buddy system of memory allocation. Free memory is maintained in linked lists, each of equal sized blocks. Any such block is of size 2^k. When some memory is required by a process, the block size of next higher order is chosen, and broken into two. Note that the two such pieces differ in address only in their kth bit. Such pieces are called buddies. When any used block is freed, the OS checks to see if its buddy is also free. If so, it is rejoined, and put into the original free-block linked-list. 22. What is time-stamping? It is a technique proposed by Lamport, used to order events in a distributed system without the use of clocks. This scheme is intended to order events consisting of the transmission of messages. Each system 'i' in the network maintains a counter Ci. Every time a system transmits a message, it increments its counter by 1 and attaches the time-stamp Ti to the message. When a message is received, the receiving system 'j' sets its counter Cj to 1 more than the maximum of its current value and the incoming timestamp Ti. At each site, the ordering of messages is determined by the following rules: For messages x from site i and y from site j, x precedes y if one of the following conditions holds....(a) if Ti<Tj or (b) if Ti=Tj and i<j. 23. How are the wait/signal operations for monitor different from those for semaphores? If a process in a monitor signal and no task is waiting on the condition variable, the signal is lost. So this allows easier program design. Whereas in semaphores, every operation affects the value of the semaphore, so the wait and signal operations should be perfectly balanced in the program.

24. In the context of memory management, what are placement and replacement algorithms? Placement algorithms determine where in available real-memory to load a program. Common methods are first-fit, next-fit, best-fit. Replacement algorithms are

used when memory is full, and one process (or part of a process) needs to be swapped out to accommodate a new program. The replacement algorithm determines which are the partitions to be swapped out. 25. In loading programs into memory, what is the difference between load-time dynamic linking and run-time dynamic linking? For load-time dynamic linking: Load module to be loaded is read into memory. Any reference to a target external module causes that module to be loaded and the references are updated to a relative address from the start base address of the application module. With run-time dynamic loading: Some of the linking is postponed until actual reference during execution. Then the correct module is loaded and linked. 26. What are demand- and pre-paging? With demand paging, a page is brought into memory only when a location on that page is actually referenced during execution. With pre-paging, pages other than the one demanded by a page fault are brought in. The selection of such pages is done based on common access patterns, especially for secondary memory devices. 27. Paging a memory management function, while multiprogramming a processor management function, are the two interdependent? Yes. 28. What is page cannibalizing? Page swapping or page replacements are called page cannibalizing. 29. What has triggered the need for multitasking in PCs? Increased speed and memory capacity of microprocessors together with the support fir virtual memory and Growth of client server computing 30. What are the four layers that Windows NT have in order to achieve independence? Hardware abstraction layer Kernel Subsystems System Services. 31. What is SMP? To achieve maximum efficiency and reliability a mode of operation known as symmetric multiprocessing is used. In essence, with SMP any process or threads can be assigned to any processor. 32. What are the key object oriented concepts used by Windows NT? Encapsulation Object class and instance

33. Is Windows NT a full blown object oriented operating system? Give reasons. No Windows NT is not so, because its not implemented in object oriented language and the data structures reside within one executive component and are not represented as objects and it does not support object oriented capabilities . 34. What is a drawback of MVT? It does not have the features like ability to support multiple processors virtual storage source level debugging 35. What is process spawning? When the OS at the explicit request of another process creates a process, this action is called process spawning. 36. How many jobs can be run concurrently on MVT? 15 jobs 37. List out some reasons for process termination. Normal completion Time limit exceeded Memory unavailable Bounds violation Protection error Arithmetic error Time overrun I/O failure Invalid instruction Privileged instruction Data misuse Operator or OS intervention Parent termination. 38. What are the reasons for process suspension? swapping interactive user request timing parent process request 39. What is process migration? It is the transfer of sufficient amount of the state of process from one machine to the target machine 40. What is mutant? In Windows NT a mutant provides kernel mode or user mode mutual exclusion with the notion of ownership.

41. What is an idle thread? The special thread a dispatcher will execute when no ready thread is found. 42. What is FtDisk? It is a fault tolerance disk driver for Windows NT. 43. What are the possible threads a thread can have? Ready Standby Running Waiting Transition Terminated. 44. What are rings in Windows NT? Windows NT uses protection mechanism called rings provides by the process to implement separation between the user mode and kernel mode. 45. What is Executive in Windows NT? In Windows NT, executive refers to the operating system code that runs in kernel mode. 46. What are the sub-components of I/O manager in Windows NT? Network redirector/ Server Cache manager. File systems Network driver Device driver 47. What are DDks? Name an operating system that includes this feature. DDks are device driver kits, which are equivalent to SDKs for writing device drivers. Windows NT includes DDks. 48. What level of security does Windows NT meets? C2 level security.

Linked List Basics


By Nick Parlante
Copyright 1998-2001, Nick Parlante

Abstract This document introduces the basic structures and techniques for building linked lists with a mixture of explanations, drawings, sample code, and exercises. The material is useful if you want to understand linked lists or if you want to see a realistic, applied example of pointer-intensive code. A separate document, Linked List Problems (http://cslibrary.stanford.edu/105/), presents 18 practice problems covering a wide range of difficulty. Linked lists are useful to study for two reasons. Most obviously, linked lists are a data structure which you may want to use in real programs. Seeing the strengths and weaknesses of linked lists will give you an appreciation of the some of the time, space, and code issues which are useful to thinking about any data structures in general. Somewhat less obviously, linked lists are great way to learn about pointers. In fact, you may never use a linked list in a real program, but you are certain to use lots of pointers. Linked list problems are a nice combination of algorithms and pointer manipulation. Traditionally, linked lists have been the domain where beginning programmers get the practice to really understand pointers. Audience The article assumes a basic understanding of programming and pointers. The article uses C syntax for its examples where necessary, but the explanations avoid C specifics as much as possible really the discussion is oriented towards the important concepts of pointer manipulation and linked list algorithms. Other Resources Link List Problems (http://cslibrary.stanford.edu/105/) Lots of linked list problems, with explanations, answers, and drawings. The "problems" article is a companion to this "explanation" article. Pointers and Memory (http://cslibrary.stanford.edu/102/) Explains all about how pointers and memory work. You need some understanding of pointers and memory before you can understand linked lists. Essential C (http://cslibrary.stanford.edu/101/) features of the C programming language. Explains all the basic

This is document #103, Linked List Basics, in the Stanford CS Education Library. This and other free educational materials are available at http://cslibrary.stanford.edu/. This document is free to be used, reproduced, or sold so long as this notice is clearly reproduced at its beginning.

2 Contents Section 1 Basic List Structures and Code Section 2 Basic List Building Section 3 Linked List Code Techniques Section 3 Code Examples

2 11 17 22

Edition Originally 1998 there was just one "Linked List" document that included a basic explanation and practice problems. In 1999, it got split into two documents: #103 (this document) focuses on the basic introduction, while #105 is mainly practice problems. This 4-12-2001 edition represents minor edits on the 1999 edition. Dedication This document is distributed for free for the benefit and education of all. That a person seeking knowledge should have the opportunity to find it. Thanks to Stanford and my boss Eric Roberts for supporing me in this project. Best regards, Nick -nick.parlante@cs.stanford.edu

Section 1 Linked List Basics


Why Linked Lists? Linked lists and arrays are similar since they both store collections of data. The terminology is that arrays and linked lists store "elements" on behalf of "client" code. The specific type of element is not important since essentially the same structure works to store elements of any type. One way to think about linked lists is to look at how arrays work and think about alternate approaches. Array Review Arrays are probably the most common data structure used to store collections of elements. In most languages, arrays are convenient to declare and the provide the handy [ ] syntax to access any element by its index number. The following example shows some typical array code and a drawing of how the array might look in memory. The code allocates an array int scores[100], sets the first three elements set to contain the numbers 1, 2, 3 and leaves the rest of the array uninitialized...
void ArrayTest() { int scores[100]; // operate on the elements of the scores array... scores[0] = 1; scores[1] = 2; scores[2] = 3; }

3 Here is a drawing of how the scores array might look like in memory. The key point is that the entire array is allocated as one block of memory. Each element in the array gets its own space in the array. Any element can be accessed directly using the [ ] syntax. scores

1 index 0 1

2 2

3 3

-3451

23142 99

Once the array is set up, access to any element is convenient and fast with the [ ] operator. (Extra for experts) Array access with expressions such as scores[i] is almost always implemented using fast address arithmetic: the address of an element is computed as an offset from the start of the array which only requires one multiplication and one addition. The disadvantages of arrays are... 1) The size of the array is fixed 100 elements in this case. Most often this size is specified at compile time with a simple declaration such as in the example above . With a little extra effort, the size of the array can be deferred until the array is created at runtime, but after that it remains fixed. (extra for experts) You can go to the trouble of dynamically allocating an array in the heap and then dynamically resizing it with realloc(), but that requires some real programmer effort. 2) Because of (1), the most convenient thing for programmers to do is to allocate arrays which seem "large enough" (e.g. the 100 in the scores example). Although convenient, this strategy has two disadvantages: (a) most of the time there are just 20 or 30 elements in the array and 70% of the space in the array really is wasted. (b) If the program ever needs to process more than 100 scores, the code breaks. A surprising amount of commercial code has this sort of naive array allocation which wastes space most of the time and crashes for special occasions. (Extra for experts) For relatively large arrays (larger than 8k bytes), the virtual memory system may partially compensate for this problem, since the "wasted" elements are never touched. 3) (minor) Inserting new elements at the front is potentially expensive because existing elements need to be shifted over to make room. Linked lists have their own strengths and weaknesses, but they happen to be strong where arrays are weak. The array's features all follow from its strategy of allocating the memory for all its elements in one block of memory. Linked lists use an entirely different strategy. As we will see, linked lists allocate memory for each element separately and only when necessary. Pointer Refresher Here is a quick review of the terminology and rules for pointers. The linked list code to follow will depend on these rules. (For much more detailed coverage of pointers and memory, see Pointers and Memory, http://cslibrary.stanford.edu/102/).

4 Pointer/Pointee A "pointer" stores a reference to another variable sometimes known as its "pointee". Alternately, a pointer may be set to the value NULL which encodes that it does not currently refer to a pointee. (In C and C++ the value NULL can be used as a boolean false). Dereference The dereference operation on a pointer accesses its pointee. A pointer may only be dereferenced after it has been set to refer to a specific pointee. A pointer which does not have a pointee is "bad" (below) and should not be dereferenced. Bad Pointer A pointer which does not have an assigned a pointee is "bad" and should not be dereferenced. In C and C++, a dereference on a bad sometimes crashes immediately at the dereference and sometimes randomly corrupts the memory of the running program, causing a crash or incorrect computation later. That sort of random bug is difficult to track down. In C and C++, all pointers start out with bad values, so it is easy to use bad pointer accidentally. Correct code sets each pointer to have a good value before using it. Accidentally using a pointer when it is bad is the most common bug in pointer code. In Java and other runtime oriented languages, pointers automatically start out with the NULL value, so dereferencing one is detected immediately. Java programs are much easier to debug for this reason. Pointer assignment An assignment operation between two pointers like p=q; makes the two pointers point to the same pointee. It does not copy the pointee memory. After the assignment both pointers will point to the same pointee memory which is known as a "sharing" situation. malloc() malloc() is a system function which allocates a block of memory in the "heap" and returns a pointer to the new block. The prototype for malloc() and other heap functions are in stdlib.h. The argument to malloc() is the integer size of the block in bytes. Unlike local ("stack") variables, heap memory is not automatically deallocated when the creating function exits. malloc() returns NULL if it cannot fulfill the request. (extra for experts) You may check for the NULL case with assert() if you wish just to be safe. Most modern programming systems will throw an exception or do some other automatic error handling in their memory allocator, so it is becoming less common that source code needs to explicitly check for allocation failures. free() free() is the opposite of malloc(). Call free() on a block of heap memory to indicate to the system that you are done with it. The argument to free() is a pointer to a block of memory in the heap a pointer which some time earlier was obtained via a call to malloc(). What Linked Lists Look Like An array allocates memory for all its elements lumped together as one block of memory. In contrast, a linked list allocates space for each element separately in its own block of memory called a "linked list element" or "node". The list gets is overall structure by using pointers to connect all its nodes together like the links in a chain. Each node contains two fields: a "data" field to store whatever element type the list holds for its client, and a "next" field which is a pointer used to link one node to the next node. Each node is allocated in the heap with a call to malloc(), so the node memory continues to exist until it is explicitly deallocated with a call to free(). The front of the list is a

5 pointer to the first node. Here is what a list containing the numbers 1, 2, and 3 might look like... The Drawing Of List {1, 2, 3}

Stack
BuildOneTwoThree() head

Heap
The overall list is built by connecting the nodes together by their next pointers. The nodes are all allocated in the heap.

A head pointer local to BuildOneTwoThree() keeps the whole list by storing a pointer to the first node.

Each node stores one data element (int in this example).

Each node stores one next pointer.

The next field of the last node is NULL.

This drawing shows the list built in memory by the function BuildOneTwoThree() (the full source code for this function is below). The beginning of the linked list is stored in a "head" pointer which points to the first node. The first node contains a pointer to the second node. The second node contains a pointer to the third node, ... and so on. The last node in the list has its .next field set to NULL to mark the end of the list. Code can access any node in the list by starting at the head and following the .next pointers. Operations towards the front of the list are fast while operations which access node farther down the list take longer the further they are from the front. This "linear" cost to access a node is fundamentally more costly then the constant time [ ] access provided by arrays. In this respect, linked lists are definitely less efficient than arrays. Drawings such as above are important for thinking about pointer code, so most of the examples in this article will associate code with its memory drawing to emphasize the habit. In this case the head pointer is an ordinary local pointer variable, so it is drawn separately on the left to show that it is in the stack. The list nodes are drawn on the right to show that they are allocated in the heap. The Empty List NULL The above is a list pointed to by head is described as being of "length three" since it is made of three nodes with the .next field of the last node set to NULL. There needs to be some representation of the empty list the list with zero nodes. The most common representation chosen for the empty list is a NULL head pointer. The empty list case is the one common weird "boundary case" for linked list code. All of the code presented in this article works correctly for the empty list case, but that was not without some effort. When working on linked list code, it's a good habit to remember to check the empty list case to verify that it works too. Sometimes the empty list case works the same as all the cases, but sometimes it requires some special case code. No matter what, it's a good case to at least think about.

6 Linked List Types: Node and Pointer Before writing the code to build the above list, we need two data types... Node The type for the nodes which will make up the body of the list. These are allocated in the heap. Each node contains a single client data element and a pointer to the next node in the list. Type: struct node
struct node { int struct node* }; data; next;

Node Pointer The type for pointers to nodes. This will be the type of the head pointer and the .next fields inside each node. In C and C++, no separate type declaration is required since the pointer type is just the node type followed by a '*'. Type: struct node* BuildOneTwoThree() Function Here is simple function which uses pointer operations to build the list {1, 2, 3}. The memory drawing above corresponds to the state of memory at the end of this function. This function demonstrates how calls to malloc() and pointer assignments (=) work to build a pointer structure in the heap.
/* Build the list {1, 2, 3} in the heap and store its head pointer in a local stack variable. Returns the head pointer to the caller. */ struct node* BuildOneTwoThree() { struct node* head = NULL; struct node* second = NULL; struct node* third = NULL; head = malloc(sizeof(struct node)); second = malloc(sizeof(struct node)); third = malloc(sizeof(struct node)); head->data = 1; head->next = second; second->data = 2; second->next = third; third->data = 3; third->next = NULL; // allocate 3 nodes in the heap

// setup first node // note: pointer assignment rule // setup second node

// setup third link

// At this point, the linked list referenced by "head" // matches the list in the drawing. return head; }

Exercise Q: Write the code with the smallest number of assignments (=) which will build the above memory structure. A: It requires 3 calls to malloc(). 3 int assignments (=) to setup the ints. 4 pointer assignments to setup head and the 3 next fields. With a little cleverness and knowledge of the C language, this can all be done with 7 assignment operations (=).

Length() Function
The Length() function takes a linked list and computes the number of elements in the list. Length() is a simple list function, but it demonstrates several concepts which will be used in later, more complex list functions...
/* Given a linked list head pointer, compute and return the number of nodes in the list. */ int Length(struct node* head) { struct node* current = head; int count = 0; while (current != NULL) { count++; current = current->next; } return count; }

There are two common features of linked lists demonstrated in Length()... 1) Pass The List By Passing The Head Pointer The linked list is passed in to Length() via a single head pointer. The pointer is copied from the caller into the "head" variable local to Length(). Copying this pointer does not duplicate the whole list. It only copies the pointer so that the caller and Length() both have pointers to the same list structure. This is the classic "sharing" feature of pointer code. Both the caller and length have copies of the head pointer, but they share the pointee node structure. 2) Iterate Over The List With A Local Pointer The code to iterate over all the elements is a very common idiom in linked list code....
struct node* current = head; while (current != NULL) { // do something with *current node current = current->next; }

The hallmarks of this code are... 1) The local pointer, current in this case, starts by pointing to the same node as the head pointer with current = head;. When the function exits, current is automatically deallocated since it is just an ordinary local, but the nodes in the heap remain. 2) The while loop tests for the end of the list with (current != NULL). This test smoothly catches the empty list case current will be NULL on the first iteration and the while loop will just exit before the first iteration. 3) At the bottom of the while loop, current = current->next; advances the local pointer to the next node in the list. When there are no more links, this sets the pointer to NULL. If you have some linked list

8 code which goes into an infinite loop, often the problem is that step (3) has been forgotten. Calling Length() Here's some typical code which calls Length(). It first calls BuildOneTwoThree() to make a list and store the head pointer in a local variable. It then calls Length() on the list and catches the int result in a local variable.
void LengthTest() { struct node* myList = BuildOneTwoThree(); int len = Length(myList); } // results in len == 3

Memory Drawings The best way to design and think about linked list code is to use a drawing to see how the pointer operations are setting up memory. There are drawings below of the state of memory before and during the call to Length() take this opportunity to practice looking at memory drawings and using them to think about pointer intensive code. You will be able to understand many of the later, more complex functions only by making memory drawings like this on your own. Start with the Length() and LengthTest() code and a blank sheet of paper. Trace through the execution of the code and update your drawing to show the state of memory at each step. Memory drawings should distinguish heap memory from local stack memory. Reminder: malloc() allocates memory in the heap which is only be deallocated by deliberate calls to free(). In contrast, local stack variables for each function are automatically allocated when the function starts and deallocated when it exits. Our memory drawings show the caller local stack variables above the callee, but any convention is fine so long as you realize that the caller and callee are separate. (See cslibrary.stanford.edu/102/, Pointers and Memory, for an explanation of how local memory works.)

9 Drawing 1 : Before Length() Below is the state of memory just before the call to Length() in LengthTest() above. BuildOneTwoThree() has built the {1, 2, 3} list in the heap and returned the head pointer. The head pointer has been caught by the caller and stored in its local variable myList. The local variable len has a random value it will only be given the value 3 when then call to Length() returns.

Stack
LengthTest() myList len -14231

Heap

1 The head pointer for the list is stored in the local variable myList.

len has a random value until it is assigned.

Nodes allocated in the heap via calls to malloc() in BuildOneTwoThree().

10 Drawing 2: Mid Length Here is the state of memory midway through the execution of Length(). Length()'s local variables head and current have been automatically allocated. The current pointer started out pointing to the first node, and then the first iteration of the while loop advanced it to point to the second node.

Stack
LengthTest() myList len -14231

Heap

1 Length() head current

Notice how the local variables in Length() (head and current) are separate from the local variables in LengthTest() (myList and len). The local variables head and current will be deallocated (deleted) automatically when Length() exits. This is fine the heap allocated links will remain even though stack allocated pointers which were pointing to them have been deleted. Exercise Q: What if we said head = NULL; at the end of Length() would that mess up the myList variable in the caller? A: No. head is a local which was initialized with a copy of the actual parameter, but changes do not automatically trace back to the actual parameter. Changes to the local variables in one function do not affect the locals of another function. Exercise Q: What if the passed in list contains no elements, does Length() handle that case properly? A: Yes. The representation of the empty list is a NULL head pointer. Trace Length() on that case to see how it handles it.

11

Section 2 List Building


BuildOneTwoThree() is a fine as example of pointer manipulation code, but it's not a general mechanism to build lists. The best solution will be an independent function which adds a single new node to any list. We can then call that function as many times as we want to build up any list. Before getting into the specific code, we can identify the classic 3-Step Link In operation which adds a single node to the front of a linked list. The 3 steps are... 1) Allocate Allocate the new node in the heap and set its .data to whatever needs to be stored. struct node* newNode; newNode = malloc(sizeof(struct node)); newNode->data = data_client_wants_stored; 2) Link Next Set the .next pointer of the new node to point to the current first node of the list. This is actually just a pointer assignment remember: "assigning one pointer to another makes them point to the same thing." newNode->next = head; 3) Link Head Change the head pointer to point to the new node, so it is now the first node in the list. head = newNode; 3-Step Link In Code The simple LinkTest() function demonstrates the 3-Step Link In...
void LinkTest() { struct node* head = BuildTwoThree(); // suppose this builds the {2, 3} list struct node* newNode; newNode= malloc(sizeof(struct node)); newNode->data = 1; newNode->next = head; head = newNode; // now head points to the list {1, 2, 3} } // allocate

// link next // link head

12 3-Step Link In Drawing The drawing of the above 3-Step Link like (overwritten pointer values are in gray)...

Stack
LinkTest() head newNode

Heap

Insert this node with the 3-Step Link In: 1) Allocate the new node 2) Set its .next to the old head 3) Set head to point to the new node Before: list = {2, 3} After: list = {1, 2, 3}

Push() Function
With the 3-Step Link In in mind, the problem is to write a general function which adds a single node to head end of any list. Historically, this function is called "Push()" since we're adding the link to the head end which makes the list look a bit like a stack. Alternately it could be called InsertAtFront(), but we'll use the name Push(). WrongPush() Unfortunately Push() written in C suffers from a basic problem: what should be the parameters to Push()? This is, unfortunately, a sticky area in C. There's a nice, obvious way to write Push() which looks right but is wrong. Seeing exactly how it doesn't work will provide an excuse for more practice with memory drawings, motivate the correct solution, and just generally make you a better programmer....
void WrongPush(struct node* head, int data) { struct node* newNode = malloc(sizeof(struct node)); newNode->data = data; newNode->next = head; head = newNode; // NO this line does not work! }

void WrongPushTest() { List head = BuildTwoThree(); WrongPush(head, 1); } // try to push a 1 on front -- doesn't work

13 WrongPush() is very close to being correct. It takes the correct 3-Step Link In and puts it an almost correct context. The problem is all in the very last line where the 3-Step Link In dictates that we change the head pointer to refer to the new node. What does the line head = newNode; do in WrongPush()? It sets a head pointer, but not the right one. It sets the variable named head local to WrongPush(). It does not in any way change the variable named head we really cared about which is back in the caller WrontPushTest(). Exercise Make the memory drawing tracing WrongPushTest() to see how it does not work. The key is that the line head = newElem; changes the head local to WrongPush() not the head back in WrongPushTest(). Remember that the local variables for WrongPush() and WrongPushTest() are separate (just like the locals for LengthTest() and Length() in the Length() example above). Reference Parameters In C We are bumping into a basic "feature" of the C language that changes to local parameters are never reflected back in the caller's memory. This is a traditional tricky area of C programming. We will present the traditional "reference parameter" solution to this problem, but you may want to consult another C resource for further information. (See Pointers and Memory (http://cslibrary.stanford.edu/102/) for a detailed explanation of reference parameters in C and C++.) We need Push() to be able to change some of the caller's memory namely the head variable. The traditional method to allow a function to change its caller's memory is to pass a pointer to the caller's memory instead of a copy. So in C, to change an int in the caller, pass a int* instead. To change a struct fraction, pass a struct fraction* intead. To change an X, pass an X*. So in this case, the value we want to change is struct node*, so we pass a struct node** instead. The two stars (**) are a little scary, but really it's just a straight application of the rule. It just happens that the value we want to change already has one star (*), so the parameter to change it has two (**). Or put another way: the type of the head pointer is "pointer to a struct node." In order to change that pointer, we need to pass a pointer to it, which will be a "pointer to a pointer to a struct node". Instead of defining WrongPush(struct node* head, int data); we define Push(struct node** headRef, int data);. The first form passes a copy of the head pointer. The second, correct form passes a pointer to the head pointer. The rule is: to modify caller memory, pass a pointer to that memory. The parameter has the word "ref" in it as a reminder that this is a "reference" (struct node**) pointer to the head pointer instead of an ordinary (struct node*) copy of the head pointer.

14 Correct Push() Code Here are Push() and PushTest() written correctly. The list is passed via a pointer to the head pointer. In the code, this amounts to use of '&' on the parameter in the caller and use of '*' on the parameter in the callee. Inside Push(), the pointer to the head pointer is named "headRef" instead of just "head" as a reminder that it is not just a simple head pointer..
/* Takes a list and a data value. Creates a new link with the given data and pushes it onto the front of the list. The list is not passed in by its head pointer. Instead the list is passed in as a "reference" pointer to the head pointer -- this allows us to modify the caller's memory. */ void Push(struct node** headRef, int data) { struct node* newNode = malloc(sizeof(struct node)); newNode->data = data; newNode->next = *headRef; *headRef = newNode; }

// The '*' to dereferences back to the real head // ditto

void PushTest() { struct node* head = BuildTwoThree();// suppose this returns the list {2, 3} Push(&head, 1); Push(&head, 13); // note the &

// head is now the list {13, 1, 2, 3} }

15 Correct Push() Drawing Here is a drawing of memory just before the first call to Push() exits. The original value of the head pointer is in gray. Notice how the headRef parameter inside Push() points back to the real head pointer back in PushTest(). Push() uses *headRef to access and change the real head pointer.

Stack

Heap

PushTest() head Push() headRef data 2 1 1 The key point: the headRef parameter to Push() is not the real head of the list. It is a pointer to the real head of the list back in the callers memory space. This node inserted by the call to Push(). Push follows its headRef to modify the real head. 3

Exercise The above drawing shows the state of memory at the end of the first call to Push() in PushTest(). Extend the drawing to trace through the second call to Push(). The result should be that the list is left with elements {13, 1, 2, 3}. Exercise The following function correctly builds a three element list using nothing but Push(). Make the memory drawing to trace its execution and show the final state of its list. This will also demonstrate that Push() works correctly for the empty list case.
void PushTest2() { struct node* head = NULL; Push(&head, 1); Push(&head, 2); Push(&head, 3); // head now points to the list {3, 2, 1} } // make a list with no elements

What About C++? (Just in case you were curious) C++ has its built in "& argument" feature to implement reference parameters for the programmer. The short story is, append an '&' to the type of a parameter, and the compiler will automatically make the parameter operate by reference for you. The type of the argument is not disturbed by this the types continue to act as

16 they appear in the source, which is the most convenient for the programmer. So In C++, Push() and PushTest() look like...
/* Push() in C++ -- we just add a '&' to the right hand side of the head parameter type, and the compiler makes that parameter work by reference. So this code changes the caller's memory, but no extra uses of '*' are necessary -we just access "head" directly, and the compiler makes that change reference back to the caller. */ void Push(struct node*& head, int data) { struct node* newNode = malloc(sizeof(struct node)); newNode->data = data; newNode->next = head; head = newNode; }

// No extra use of * necessary on head -- the compiler // just takes care of it behind the scenes.

void PushTest() { struct node* head = BuildTwoThree();// suppose this returns the list {2, 3} Push(head, 1); Push(head, 13); // No extra use & necessary -- the compiler takes // care of it here too. Head is being changed by // these calls.

// head is now the list {13, 1, 2, 3} }

The memory drawing for the C++ case looks the same as for the C case. The difference is that the C case, the *'s need to be taken care of in the code. In the C++ case, it's handled invisibly in the code.

17

Section 3 Code Techniques


This section summarizes, in list form, the main techniques for linked list code. These techniques are all demonstrated in the examples in the next section. 1) Iterate Down a List A very frequent technique in linked list code is to iterate a pointer over all the nodes in a list. Traditionally, this is written as a while loop. The head pointer is copied into a local variable current which then iterates down the list. Test for the end of the list with current!=NULL. Advance the pointer with current=current->next.
// Return the number of nodes in a list (while-loop version) int Length(struct node* head) { int count = 0; struct node* current = head; while (current != NULL) { count++; current = current->next } return(count); }

Alternately, some people prefer to write the loop as a for which makes the initialization, test, and pointer advance more centralized, and so harder to omit...
for (current = head; current != NULL; current = current->next) {

2) Changing a Pointer With A Reference Pointer Many list functions need to change the caller's head pointer. To do this in the C language, pass a pointer to the head pointer. Such a pointer to a pointer is sometimes called a "reference pointer". The main steps for this technique are... Design the function to take a pointer to the head pointer. This is the standard technique in C pass a pointer to the "value of interest" that needs to be changed. To change a struct node*, pass a struct node**. Use '&' in the caller to compute and pass a pointer to the value of interest. Use '*' on the parameter in the callee function to access and change the value of interest. The following simple function sets a head pointer to NULL by using a reference parameter....
// Change the passed in head pointer to be NULL // Uses a reference pointer to access the caller's memory void ChangeToNull(struct node** headRef) { // Takes a pointer to // the value of interest

18
*headRef = NULL; } // use '*' to access the value of interest

void ChangeCaller() { struct node* head1; struct node* head2; ChangeToNull(&head1); // use '&' to compute and pass a pointer to ChangeToNull(&head2); // the value of interest // head1 and head2 are NULL at this point }

Here is a drawing showing how the headRef pointer in ChangeToNull() points back to the variable in the caller...

Stack
ChangeCaller() head1

ChangToNull() headRef

See the use of Push() above and its implementation for another example of reference pointers. 3) Build At Head With Push() The easiest way to build up a list is by adding nodes at its "head end" with Push(). The code is short and it runs fast lists naturally support operations at their head end. The disadvantage is that the elements will appear in the list in the reverse order that they are added. If you don't care about order, then the head end is the best.
struct node* AddAtHead() { struct node* head = NULL; int i; for (i=1; i<6; i++) { Push(&head, i); } // head == {5, 4, 3, 2, 1}; return(head); }

4) Build With Tail Pointer What about adding nodes at the "tail end" of the list? Adding a node at the tail of a list most often involves locating the last node in the list, and then changing its .next field

19 from NULL to point to the new node, such as the tail variable in the following example of adding a "3" node to the end of the list {1, 2}...

Stack

Heap

head

tail newNode

This is just a special case of the general rule: to insert or delete a node inside a list, you need a pointer to the node just before that position, so you can change its .next field. Many list problems include the sub-problem of advancing a pointer to the node before the point of insertion or deletion. The one exception is if the node is the first in the list in that case the head pointer itself must be changed. The following examples show the various ways code can handle the single head case and all the interior cases... 5) Build Special Case + Tail Pointer Consider the problem of building up the list {1, 2, 3, 4, 5} by appending the nodes to the tail end. The difficulty is that the very first node must be added at the head pointer, but all the other nodes are inserted after the last node using a tail pointer. The simplest way to deal with both cases is to just have two separate cases in the code. Special case code first adds the head node {1}. Then there is a separate loop that uses a tail pointer to add all the other nodes. The tail pointer is kept pointing at the last node, and each new node is added at tail->next. The only "problem" with this solution is that writing separate special case code for the first node is a little unsatisfying. Nonetheless, this approach is a solid one for production code it is simple and runs fast.
struct node* BuildWithSpecialCase() { struct node* head = NULL; struct node* tail; int i; // Deal with the head node here, and set the tail pointer Push(&head, 1); tail = head; // Do all the other nodes using 'tail' for (i=2; i<6; i++) { Push(&(tail->next), i); // add node at tail->next tail = tail->next; // advance tail to point to last node } return(head); } // head == {1, 2, 3, 4, 5};

20 6) Build Dummy Node Another solution is to use a temporary dummy node at the head of the list during the computation. The trick is that with the dummy, every node appear to be added after the .next field of a node. That way the code for the first node is the same as for the other nodes. The tail pointer plays the same role as in the previous example. The difference is that it now also handles the first node.
struct node* BuildWithDummyNode() { struct node dummy; // Dummy node is temporarily the first node struct node* tail = &dummy; // Start the tail at the dummy. // Build the list on dummy.next (aka tail->next) int i; dummy.next = NULL; for (i=1; i<6; i++) { Push(&(tail->next), i); tail = tail->next; } // The real result list is now in dummy.next // dummy.next == {1, 2, 3, 4, 5}; return(dummy.next); }

Some linked list implementations keep the dummy node as a permanent part of the list. For this "permanent dummy" strategy, the empty list is not represented by a NULL pointer. Instead, every list has a dummy node at its head. Algorithms skip over the dummy node for all operations. That way the heap allocated dummy node is always present to provide the above sort of convenience in the code. Our dummy-in-the stack strategy is a little unusual, but it avoids making the dummy a permanent part of the list. Some of the solutions presented in this document will use the temporary dummy strategy. The code for the permanent dummy strategy is extremely similar, but is not shown. 7) Build Local References Finally, here is a tricky way to unifying all the node cases without using a dummy node. The trick is to use a local "reference pointer" which always points to the last pointer in the list instead of to the last node. All additions to the list are made by following the reference pointer. The reference pointer starts off pointing to the head pointer. Later, it points to the .next field inside the last node in the list. (A detailed explanation follows.)
struct node* BuildWithLocalRef() { struct node* head = NULL; struct node** lastPtrRef= &head; // Start out pointing to the head pointer int i; for (i=1; i<6; i++) { Push(lastPtrRef, i); // Add node at the last pointer in the list lastPtrRef= &((*lastPtrRef)->next); // Advance to point to the // new last pointer } // head == {1, 2, 3, 4, 5}; return(head); }

21 This technique is short, but the inside of the loop is scary. This technique is rarely used. (Actually, I'm the only person I've known to promote it. I think it has a sort of compact charm.) Here's how it works... 1) At the top of the loop, lastPtrRef points to the last pointer in the list. Initially it points to the head pointer itself. Later it points to the .next field inside the last node in the list. 2) Push(lastPtrRef, i); adds a new node at the last pointer. The new node becaomes the last node in the list. 3) lastPtrRef= &((*lastPtrRef)->next); Advance the lastPtrRef to now point to the .next field inside the new last node that .next field is now the last pointer in the list. Here is a drawing showing the state of memory for the above code just before the third node is added. The previous values of lastPtrRef are shown in gray...

Stack
LocalRef() head

Heap

lastPtrRef

This technique is never required to solve a linked list problem, but it will be one of the alternative solutions presented for some of the advanced problems. Both the temporary-dummy strategy and the reference-pointer strategy are a little unusual. They are good ways to make sure that you really understand pointers, since they use pointers in unusual ways.

22

Section 4 Examples
This section presents some complete list code to demonstrate all of the techniques above. For many more sample problems with solutions, see CS Education Library #105, -Linked List Problems (http://cslibrary.stanford.edu/105/).

AppendNode() Example
Consider a AppendNode() function which is like Push(), except it adds the new node at the tail end of the list instead of the head. If the list is empty, it uses the reference pointer to change the head pointer. Otherwise it uses a loop to locate the last node in the list. This version does not use Push(). It builds the new node directly.
struct node* AppendNode(struct node** headRef, int num) { struct node* current = *headRef; struct node* newNode; newNode = malloc(sizeof(struct node)); newNode->data = num; newNode->next = NULL; // special case for length 0 if (current == NULL) { *headRef = newNode; } else { // Locate the last node while (current->next != NULL) { current = current->next; } current->next = newNode; } }

AppendNode() With Push() This version is very similar, but relies on Push() to build the new node. Understanding this version requires a real understanding of reference pointers.
struct node* AppendNode(struct node** headRef, int num) { struct node* current = *headRef; // special case for the empty list if (current == NULL) { Push(headRef, num); } else { // Locate the last node while (current->next != NULL) { current = current->next; } // Build the node after the last node Push(&(current->next), num); } }

23

CopyList() Example
Consider a CopyList() function that takes a list and returns a complete copy of that list. One pointer can iterate over the original list in the usual way. Two other pointers can keep track of the new list: one head pointer, and one tail pointer which always points to the last node in the new list. The first node is done as a special case, and then the tail pointer is used in the standard way for the others...
struct node* CopyList(struct node* head) { struct node* current = head; // used to iterate over the original list struct node* newList = NULL; // head of the new list struct node* tail = NULL; // kept pointing to the last node in the new list while (current != NULL) { if (newList == NULL) { // special case for the first new node newList = malloc(sizeof(struct node)); newList->data = current->data; newList->next = NULL; tail = newList; } else { tail->next = malloc(sizeof(struct node)); tail = tail->next; tail->data = current->data; tail->next = NULL; } current = current->next; } return(newList); }

CopyList() Memory Drawing Here is the state of memory when CopyList() finishes copying the list {1, 2}...

Stack
CopyList() head current newList

Heap

tail

24 CopyList() With Push() Exercise The above implementation is a little unsatisfying because the 3-step-link-in is repeated once for the first node and once for all the other nodes. Write a CopyList2() which uses Push() to take care of allocating and inserting the new nodes, and so avoids repeating that code. CopyList() With Push() Answer
// Variant of CopyList() that uses Push() struct node* CopyList2(struct node* head) { struct node* current = head; // used to iterate over the original list struct node* newList = NULL; // head of the new list struct node* tail = NULL; // kept pointing to the last node in the new list while (current != NULL) { if (newList == NULL) { // special case for the first new node Push(&newList, current->data); tail = newList; } else { Push(&(tail->next), current->data); // add each node at the tail tail = tail->next; // advance the tail to the new last node } current = current->next; } return(newList); }

CopyList() With Dummy Node Anther strategy for CopyList() uses a temporary dummy node to take care of the first node case. The dummy node is temporarily the first node in the list, and the tail pointer starts off pointing to it. All nodes are added off the tail pointer.
// Dummy node variant struct node* CopyList(struct node* head) { struct node* current = head; // used to iterate over the original list struct node* tail; // kept pointing to the last node in the new list struct node dummy; // build the new list off this dummy node dummy.next = NULL; tail = &dummy;

// start the tail pointing at the dummy

while (current != NULL) { Push(&(tail->next), current->data); // add each node at the tail tail = tail->next; // advance the tail to the new last node } current = current->next; } return(dummy.next); }

CopyList() With Local References The final, and most unusual version uses the "local references" strategy instead of a tail pointer. The strategy is to keep a lastPtr that points to the last pointer in the list. All node additions are done at the lastPtr, and it always points to the last pointer in the

25 list. When the list is empty, it points to the head pointer itself. Later it points to the .next pointer inside the last node in the list.
// Local reference variant struct node* CopyList(struct node* head) { struct node* current = head; // used to iterate over the original list struct node* newList = NULL; struct node** lastPtr; lastPtr = &newList; // start off pointing to the head itself

while (current != NULL) { Push(lastPtr, current->data); lastPtr = &((*lastPtr)->next); current = current->next; } return(newList); }

// add each node at the lastPtr // advance lastPtr

CopyList() Recursive Finally, for completeness, here is the recursive version of CopyList(). It has the pleasing shortness that recursive code often has. However, it is probably not good for production code since it uses stack space proportional to the length of its list.
// Recursive variant struct node* CopyList(struct node* head) { if (head == NULL) return NULL; else { struct node* newList = malloc(sizeof(struct node)); newList->data = current->data; newList->next = CopyList(current->next); return(newList); } }

// make the one node

// recur for the rest

Appendix Other Implementations


There are a many variations on the basic linked list which have individual advantages over the basic linked list. It is probably best to have a firm grasp of the basic linked list and its code before worrying about the variations too much. Dummy Header Forbid the case where the head pointer is NULL. Instead, choose as a representation of the empty list a single "dummy" node whose .data field is unused. The advantage of this technique is that the pointer-to-pointer (reference parameter) case does not come up for operations such as Push(). Also, some of the iterations are now a little simpler since they can always assume the existence of the dummy header node. The disadvantage is that allocating an "empty" list now requires

26 allocating (and wasting) memory. Some of the algorithms have an ugliness to them since they have to realize that the dummy node "doesn't count." (editorial) Mainly the dummy header is for programmers to avoid the ugly reference parameter issues in functions such as Push(). Languages which don't allow reference parameters, such as Java, may require the dummy header as a workaround. (See the "temporary dummy" variant below.) Circular Instead of setting the .next field of the last node to NULL, set it to point back around to the first node. Instead of needing a fixed head end, any pointer into the list will do. Tail Pointer The list is not represented by a single head pointer. Instead the list is represented by a head pointer which points to the first node and a tail pointer which points to the last node. The tail pointer allows operations at the end of the list such as adding an end element or appending two lists to work efficiently. Head struct A variant I like better than the dummy header is to have a special "header" struct (a different type from the node type) which contains a head pointer, a tail pointer, and possibly a length to make many operations more efficient. Many of the reference parameter problems go away since most functions can deal with pointers to the head struct (whether it is heap allocated or not). This is probably the best approach to use in a language without reference parameters, such as Java. Doubly-Linked Instead of just a single .next field, each node incudes both .next and .previous pointers. Insertion and deletion now require more operations. but other operations are simplified. Given a pointer to a node, insertion and deletion can be performed directly whereas in the singly linked case, the iteration typically needs to locate the point just before the point of change in the list so the .next pointers can be followed downstream. Chunk List Instead of storing a single client element in each node, store a little constant size array of client elements in each node. Tuning the number of elements per node can provide different performance characteristics: many elements per node has performance more like an array, few elements per node has performance more like a linked list. The Chunk List is a good way to build a linked list with good performance. Dynamic Array Instead of using a linked list, elements may be stored in an array block allocated in the heap. It is possible to grow and shrink the size of the block as needed with calls to the system function realloc(). Managing a heap block in this way is a fairly complex, but can have excellent efficiency for storage and iteration., especially because modern memory systems are tuned for the access of contiguous areas of memory. In contrast, linked list can actually be a little inefficient, since they tend to iterate through memory areas that are not adjacent.

Linked List Problems


By Nick Parlante
Copyright 1998-2002, Nick Parlante

Abstract This document reviews basic linked list code techniques and then works through 18 linked list problems covering a wide range of difficulty. Most obviously, these problems are a way to learn about linked lists. More importantly, these problems are a way to develop your ability with complex pointer algorithms. Even though modern languages and tools have made linked lists pretty unimportant for day-to-day programming, the skills for complex pointer algorithms are very important, and linked lists are an excellent way to develop those skills. The problems use the C language syntax, so they require a basic understanding of C and its pointer syntax. The emphasis is on the important concepts of pointer manipulation and linked list algorithms rather than the features of the C language. For some of the problems we present multiple solutions, such as iteration vs. recursion, dummy node vs. local reference. The specific problems are, in rough order of difficulty: Count, GetNth, DeleteList, Pop, InsertNth, SortedInsert, InsertSort, Append, FrontBackSplit, RemoveDuplicates, MoveNode, AlternatingSplit, ShuffleMerge, SortedMerge, SortedIntersect, Reverse, and RecursiveReverse. Contents Section 1 Review of basic linked list code techniques Section 2 18 list problems in increasing order of difficulty Section 3 Solutions to all the problems 3 10 20

This is document #105, Linked List Problems, in the Stanford CS Education Library. This and other free educational materials are available at http://cslibrary.stanford.edu/. This document is free to be used, reproduced, or sold so long as this notice is clearly reproduced at its beginning. Related CS Education Library Documents Related Stanford CS Education library documents... Linked List Basics (http://cslibrary.stanford.edu/103/) Explains all the basic issues and techniques for building linked lists. Pointers and Memory (http://cslibrary.stanford.edu/102/) Explains how pointers and memory work in C and other languages. Starts with the very basics, and extends through advanced topics such as reference parameters and heap management. Binary Trees (http://cslibrary.stanford.edu/110/) Introduction to binary trees Essential C (http://cslibrary.stanford.edu/101/) Explains the basic features of the C programming language.

2 The Great Tree List Problem (http://cslibrary.stanford.edu/109/) Presents the greatest recursive pointer problem ever devised. Why Linked Lists Are Great To Study Linked lists hold a special place in the hearts of many programmers. Linked lists are great to study because... Nice Domain The linked list structure itself is simple. Many linked list operations such as "reverse a list" or "delete a list" are easy to describe and understand since they build on the simple purpose and structure of the linked list itself. Complex Algorithm Even though linked lists are simple, the algorithms that operate on them can be as complex and beautiful as you want (See problem #18). It's easy to find linked list algorithms that are complex, and pointer intensive. Pointer Intensive Linked list problems are really about pointers. The linked list structure itself is obviously pointer intensive. Furthermore, linked list algorithms often break and re-weave the pointers in a linked list as they go. Linked lists really test your understanding of pointers. Visualization Visualization is an important skill in programming and design. Ideally, a programmer can visualize the state of memory to help think through the solution. Even the most abstract languages such as Java and Perl have layered, reference based data structures that require visualization. Linked lists have a natural visual structure for practicing this sort of thinking. It's easy to draw the state of a linked list and use that drawing to think through the code. Not to appeal to your mercenary side, but for all of the above reasons, linked list problems are often used as interview and exam questions. They are short to state, and have complex, pointer intensive solutions. No one really cares if you can build linked lists, but they do want to see if you have programming agility for complex algorithms and pointer manipulation. Linked lists are the perfect source of such problems. How To Use This Document Try not to use these problems passively. Take some time to try to solveeach problem. Even if you do not succeed, you will think through the right issues in the attempt, and looking at the given solution will make more sense. Use drawings to think about the problems and work through the solutions. Linked lists are well-suited for memory drawings, so these problems are an excellent opportunity to develop your visualization skill. The problems in this document use regular linked lists, without simplifcations like dummy headers. Dedication This Jan-2002 revision includes many small edits. The first major release was Jan 17, 1999. Thanks to Negar Shamma for her many corrections. This document is distributed for the benefit and education of all. Thanks to the support of Eric Roberts and Stanford University. That someone seeking education should have the opportunity to find it. May you learn from it in the spirit of goodwill in which it is given. Best Regards, Nick Parlante -- nick.parlante@cs.stanford.edu

Section 1 Linked List Review


This section is a quick review of the concepts used in these linked list problems. For more detailed coverage, see Link List Basics (http://cslibrary.stanford.edu/103/) where all of this material is explained in much more detail. Linked List Ground Rules All of the linked list code in this document uses the "classic" singly linked list structure: A single head pointer points to the first node in the list. Each node contains a single .next pointer to the next node. The .next pointer of the last node is NULL. The empty list is represented by a NULL head pointer. All of the nodes are allocated in the heap. For a few of the problems, the solutions present the temporary "dummy node" variation (see below), but most of the code deals with linked lists in their plain form. In the text, brackets {} are used to describe lists the list containing the numbers 1, 2, and 3 is written as {1, 2, 3}. The node type used is...
struct node { int data; struct node* next; };

To keep thing ssimple, we will not introduce any intermediate typedefs. All pointers to nodes are declared simply as struct node*. Pointers to pointers to nodes are declared as struct node**. Such pointers to pointers are often called "reference pointers". Basic Utility Functions In a few places, the text assumes the existence of the following basic utility functions... int Length(struct node* head); Returns the number of nodes in the list. struct node* BuildOneTwoThree(); Allocates and returns the list {1, 2, 3}. Used by some of the example code to build lists to work on. void Push(struct node** headRef, int newData); Given an int and a reference to the head pointer (i.e. a struct node** pointer to the head pointer), add a new node at the head of the list with the standard 3-step-link-in: create the new node, set its .next to point to the current head, and finally change the head to point to the new node. (If you are not sure of how this function works, the first few problems may be helpful warm-ups.)

4 Use of the Basic Utility Functions This sample code demonstrates the basic utility functions being used. Their implementations are also given in the appendix at the end of the document.
void BasicsCaller() { struct node* head; int len; head = BuildOneTwoThree(); // Start with {1, 2, 3} Push(&head, 13); // Push 13 on the front, yielding {13, 1, 2, 3} // (The '&' is because head is passed // as a reference pointer.) // // // // // Push 42 into the second position yielding {13, 42, 1, 2, 3} Demonstrates a use of '&' on the .next field of a node. (See technique #2 below.)

Push(&(head->next), 42);

len = Length(head); }

// Computes that the length is 5.

If these basic functions do not make sense to you, you can (a) go see Linked List Basics (http://cslibrary.stanford.edu/103/) which explains the basics of linked lists in detail, or (b) do the first few problems, but avoid the intermediate and advanced ones.

Linked List Code Techniques


The following list presents the most common techniques you may want to use in solving the linked list problems. The first few are basic. The last few are only necessary for the more advanced problems. 1. Iterate Down a List A very frequent technique in linked list code is to iterate a pointer over all the nodes in a list. Traditionally, this is written as a while loop. The head pointer is copied into a local variable current which then iterates down the list. Test for the end of the list with current!=NULL. Advance the pointer with current=current->next.
// Return the number of nodes in a list (while-loop version) int Length(struct node* head) { int count = 0; struct node* current = head; while (current != NULL) { count++; current = current->next; } return(count); }

Alternately, some people prefer to write the loop as a for which makes the initialization, test, and pointer advance more centralized, and so harder to omit...
for (current = head; current != NULL; current = current->next) {

5 2. Changing a Pointer Using a Reference Pointer Many list functions need to change the caller's head pointer. In C++, you can just declare the pointer parameter as an & argument, and the compiler takes care of the details. To do this in the C language, pass a pointer to the head pointer. Such a pointer to a pointer is sometimes called a "reference pointer". The main steps for this technique are... Design the function to take a pointer to the head pointer. This is the standard technique in C pass a pointer to the "value of interest" that needs to be changed. To change a struct node*, pass a struct node**. Use '&' in the caller to compute and pass a pointer to the value of interest. Use '*' on the parameter in the callee function to access and change the value of interest. The following simple function sets a head pointer to NULL by using a reference parameter....
// Change the passed in head pointer to be NULL // Uses a reference pointer to access the caller's memory void ChangeToNull(struct node** headRef) { // Takes a pointer to // the value of interest *headRef = NULL; } // use '*' to access the value of interest

void ChangeCaller() { struct node* head1; struct node* head2; ChangeToNull(&head1); // use '&' to compute and pass a pointer to ChangeToNull(&head2); // the value of interest // head1 and head2 are NULL at this point }

Here is a drawing showing how the headRef pointer in ChangeToNull() points back to the variable in the caller...

Stack
ChangeCaller() head1

ChangeToNull(&head1) headRef

6 Many of the functions in this document use reference pointer parameters. See the use of Push() above and its implementation in the appendix for another example of reference pointers. See problem #8 and its solution for a complete example with drawings. For more detailed explanations, see the resources listed on page 1. 3. Build At Head With Push() The easiest way to build up a list is by adding nodes at its "head end" with Push(). The code is short and it runs fast lists naturally support operations at their head end. The disadvantage is that the elements will appear in the list in the reverse order that they are added. If you don't care about order, then the head end is the best.
struct node* AddAtHead() { struct node* head = NULL; int i; for (i=1; i<6; i++) { Push(&head, i); } // head == {5, 4, 3, 2, 1}; return(head); }

4. Build With Tail Pointer What about adding nodes at the "tail end" of the list? Adding a node at the tail of a list most often involves locating the last node in the list, and then changing its .next field from NULL to point to the new node, such as the tail variable in the following example of adding a "3" node to the end of the list {1, 2}...

Stack

Heap

head

tail newNode

This is just a special case of the general rule: to insert or delete a node inside a list, you need a pointer to the node just before that position, so you can change its .next field. Many list problems include the sub-problem of advancing a pointer to the node before the point of insertion or deletion. The one exception is if the operation falls on the first node in the list in that case the head pointer itself must be changed. The following examples show the various ways code can handle the single head case and all the interior cases...

7 5. Build Special Case + Tail Pointer Consider the problem of building up the list {1, 2, 3, 4, 5} by appending the nodes to the tail end. The difficulty is that the very first node must be added at the head pointer, but all the other nodes are inserted after the last node using a tail pointer. The simplest way to deal with both cases is to just have two separate cases in the code. Special case code first adds the head node {1}. Then there is a separate loop that uses a tail pointer to add all the other nodes. The tail pointer is kept pointing at the last node, and each new node is added at tail->next. The only "problem" with this solution is that writing separate special case code for the first node is a little unsatisfying. Nonetheless, this approach is a solid one for production code it is simple and runs fast.
struct node* BuildWithSpecialCase() { struct node* head = NULL; struct node* tail; int i; // Deal with the head node here, and set the tail pointer Push(&head, 1); tail = head; // Do all the other nodes using 'tail' for (i=2; i<6; i++) { Push(&(tail->next), i); // add node at tail->next tail = tail->next; // advance tail to point to last node } return(head); } // head == {1, 2, 3, 4, 5};

6. Build Temporary Dummy Node This is a slightly unusual technique that can be used to shorten the code: Use a temporary dummy node at the head of the list during the computation. The trick is that with the dummy, every node appears to be added after the .next field of some other node. That way the code for the first node is the same as for the other nodes. The tail pointer plays the same role as in the previous example. The difference is that now it also handles the first node as well.
struct node* BuildWithDummyNode() { struct node dummy; // Dummy node is temporarily the first node struct node* tail = &dummy; // Start the tail at the dummy. // Build the list on dummy.next (aka tail->next) int i; dummy.next = NULL; for (i=1; i<6; i++) { Push(&(tail->next), i); tail = tail->next; } // The real result list is now in dummy.next // dummy.next == {1, 2, 3, 4, 5}; return(dummy.next); }

8 Some linked list implementations keep the dummy node as a permanent part of the list. For this "permanent dummy" strategy, the empty list is not represented by a NULL pointer. Instead, every list has a heap allocated dummy node at its head. Algorithms skip over the dummy node for all operations. That way the dummy node is always present to provide the above sort of convenience in the code. I prefer the temporary strategy shown here, but it is a little peculiar since the temporary dummy node is allocated in the stack, while all the other nodes are allocated in the heap. For production code, I do not use either type of dummy node. The code should just cope with the head node boundary cases. 7. Build Local References Finally, here is a tricky way to unify all the node cases without using a dummy node at all. For this technique, we use a local "reference pointer" which always points to the last pointer in the list instead of to the last node. All additions to the list are made by following the reference pointer. The reference pointer starts off pointing to the head pointer. Later, it points to the .next field inside the last node in the list. (A detailed explanation follows.)
struct node* BuildWithLocalRef() { struct node* head = NULL; struct node** lastPtrRef= &head; // Start out pointing to the head pointer int i; for (i=1; i<6; i++) { Push(lastPtrRef, i); // Add node at the last pointer in the list lastPtrRef= &((*lastPtrRef)->next); // Advance to point to the // new last pointer } // head == {1, 2, 3, 4, 5}; return(head); }

This technique is short, but the inside of the loop is scary. This technique is rarely used, but it's a good way to see if you really understand pointers. Here's how it works... 1) At the top of the loop, lastPtrRef points to the last pointer in the list. Initially it points to the head pointer itself. Later it points to the .next field inside the last node in the list. 2) Push(lastPtrRef, i); adds a new node at the last pointer. The new node becomes the last node in the list. 3) lastPtrRef= &((*lastPtrRef)->next); Advance the lastPtrRef to now point to the .next field inside the new last node that .next field is now the last pointer in the list. Here is a drawing showing the state of memory for the above code just before the third node is added. The previous values of lastPtrRef are shown in gray...

Stack
LocalRef() head

Heap

lastPtrRef

This technique is never required to solve a linked list problem, but it will be one of the alternative solutions presented for some of the advanced problems. The code is shorter this way, but the performance is probably not any better. Unusual Techniques Both the temporary-stack-dummy and the local-reference-pointer techniques are a little unusual. They are cute, and they let us play around with yet another variantion in pointer intensive code. They use memory in unusual ways, so they are a nice way to see if you really understand what's going on. However, I probably would not use them in production code.

10

Section 2 Linked List Problems


Here are 18 linked list problems arranged in order of difficulty. The first few are quite basic and the last few are quite advanced. Each problem starts with a basic definition of what needs to be accomplished. Many of the problems also include hints or drawings to get you started. The solutions to all the problems are in the next section. It's easy to just passively sweep your eyes over the solution verifying its existence without lettings its details touch your brain. To get the most benefit from these problems, you need to make an effort to think them through. Whether or not you solve the problem, you will be thinking through the right issues, and the given solution will make more sense. Great programmers can visualize data structures to see how the code and memory will interact. Linked lists are well suited to that sort of visual thinking. Use these problems to develop your visualization skill. Make memory drawings to trace through the execution of code. Use drawings of the pre- and post-conditions of a problem to start thinking about a solution. "The will to win means nothing without the will to prepare." - Juma Ikangaa, marathoner (also attributed to Bobby Knight)

1 Count()
Write a Count() function that counts the number of times a given int occurs in a list. The code for this has the classic list traversal structure as demonstrated in Length().
void CountTest() { List myList = BuildOneTwoThree(); int count = Count(myList, 2); } // build {1, 2, 3} // returns 1 since there's 1 '2' in the list

/* Given a list and an int, return the number of times that int occurs in the list. */ int Count(struct node* head, int searchFor) { // Your code

11

2 GetNth()
Write a GetNth() function that takes a linked list and an integer index and returns the data value stored in the node at that index position. GetNth() uses the C numbering convention that the first node is index 0, the second is index 1, ... and so on. So for the list {42, 13, 666} GetNth() with index 1 should return 13. The index should be in the range [0..length1]. If it is not, GetNth() should assert() fail (or you could implement some other error case strategy).
void GetNthTest() { struct node* myList = BuildOneTwoThree(); int lastNode = GetNth(myList, 2); } // build {1, 2, 3} // returns the value 3

Essentially, GetNth() is similar to an array[i] operation the client can ask for elements by index number. However, GetNth() no a list is much slower than [ ] on an array. The advantage of the linked list is its much more flexible memory management we can Push() at any time to add more elements and the memory is allocated as needed.
// Given a list and an index, return the data // in the nth node of the list. The nodes are numbered from 0. // Assert fails if the index is invalid (outside 0..lengh-1). int GetNth(struct node* head, int index) { // Your code

3 DeleteList()
Write a function DeleteList() that takes a list, deallocates all of its memory and sets its head pointer to NULL (the empty list).
void DeleteListTest() { struct node* myList = BuildOneTwoThree(); // build {1, 2, 3}

DeleteList(&myList); // deletes the three nodes and sets myList to NULL }

Post DeleteList() Memory Drawing The following drawing shows the state of memory after DeleteList() executes in the above sample. Overwritten pointers are shown in gray and deallocated heap memory has an 'X' through it. Essentially DeleteList() just needs to call free() once for each node and set the head pointer to NULL.

12

Stack
DeleteListTest() myList

Heap

myList is overwritten with the value NULL.

The three heap blocks are deallocated by calls to free(). Their memory will appear to be intact for a while, but the memory should not be accessed. DeleteList() The DeleteList() implementation will need to use a reference parameter just like Push() so that it can change the caller's memory (myList in the above sample). The implementation also needs to be careful not to access the .next field in each node after the node has been deallocated.
void DeleteList(struct node** headRef) { // Your code

4 Pop()
Write a Pop() function that is the inverse of Push(). Pop() takes a non-empty list, deletes the head node, and returns the head node's data. If all you ever used were Push() and Pop(), then our linked list would really look like a stack. However, we provide more general functions like GetNth() which what make our linked list more than just a stack. Pop() should assert() fail if there is not a node to pop. Here's some sample code which calls Pop()....
void PopTest() { struct node* head = BuildOneTwoThree(); int a = Pop(&head); // deletes "1" node and int b = Pop(&head); // deletes "2" node and int c = Pop(&head); // deletes "3" node and int len = Length(head); // the list } // build {1, 2, 3} returns 1 returns 2 returns 3 is now empty, so len == 0

Pop() Unlink Pop() is a bit tricky. Pop() needs to unlink the front node from the list and deallocate it with a call to free(). Pop() needs to use a reference parameter like Push() so that it can change the caller's head pointer. A good first step to writing Pop() properly is making the memory drawing for what Pop() should do. Below is a drawing showing a Pop() of the first node of a list. The process is basically the reverse of the 3-Step-Link-In used by Push() (would that be "Ni Knil Pets-3"?). The overwritten pointer value is shown in gray, and the deallocated heap memory has a big 'X' drawn on it...

13

Stack
PopTest() head

Heap

The head pointer advances to refer to the node after the unlinked one.

The unlinked node is deallocated by a call to free(). Ironically, the unlinked node itself is not changed immediately. It is no longer appears in the list just because the head pointer no longer points to it. Pop()
/* The opposite of Push(). Takes a non-empty list and removes the front node, and returns the data which was in that node. */ int Pop(struct node** headRef) { // your code...

5 InsertNth()
A more difficult problem is to write a function InsertNth() which can insert a new node at any index within a list. Push() is similar, but can only insert a node at the head end of the list (index 0). The caller may specify any index in the range [0..length], and the new node should be inserted so as to be at that index.
void InsertNthTest() { struct node* head = NULL; InsertNth(&head, 0, 13); InsertNth(&head, 1, 42); InsertNth(&head, 1, 5); DeleteList(&head); } // start with the empty list // build {13) // build {13, 42} // build {13, 5, 42}

// clean up after ourselves

14 InsertNth() is complex you will want to make some drawings to think about your solution and afterwards, to check its correctness.
/* A more general version of Push(). Given a list, an index 'n' in the range 0..length, and a data element, add a new node to the list so that it has the given index. */ void InsertNth(struct node** headRef, int index, int data) { // your code...

6 SortedInsert()
Write a SortedInsert() function which given a list that is sorted in increasing order, and a single node, inserts the node into the correct sorted position in the list. While Push() allocates a new node to add to the list, SortedInsert() takes an existing node, and just rearranges pointers to insert it into the list. There are many possible solutions to this problem.
void SortedInsert(struct node** headRef, struct node* newNode) { // Your code...

7 InsertSort()
Write an InsertSort() function which given a list, rearranges its nodes so they are sorted in increasing order. It should use SortedInsert().
// Given a list, change it to be in sorted order (using SortedInsert()). void InsertSort(struct node** headRef) { // Your code

8 Append()
Write an Append() function that takes two lists, 'a' and 'b', appends 'b' onto the end of 'a', and then sets 'b' to NULL (since it is now trailing off the end of 'a'). Here is a drawing of a sample call to Append(a, b) with the start state in gray and the end state in black. At the end of the call, the 'a' list is {1, 2, 3, 4}, and 'b' list is empty.

Stack

Heap

a b

15 It turns out that both of the head pointers passed to Append(a, b) need to be reference parameters since they both may need to be changed. The second 'b' parameter is always set to NULL. When is 'a' changed? That case occurs when the 'a' list starts out empty. In that case, the 'a' head must be changed from NULL to point to the 'b' list. Before the call 'b' is {3, 4}. After the call, 'a' is {3, 4}.

Stack

Heap

a b

// Append 'b' onto the end of 'a', and then set 'b' to NULL. void Append(struct node** aRef, struct node** bRef) { // Your code...

9 FrontBackSplit()
Given a list, split it into two sublists one for the front half, and one for the back half. If the number of elements is odd, the extra element should go in the front list. So FrontBackSplit() on the list {2, 3, 5, 7, 11} should yield the two lists {2, 3, 5} and {7, 11}. Getting this right for all the cases is harder than it looks. You should check your solution against a few cases (length = 2, length = 3, length=4) to make sure that the list gets split correctly near the short-list boundary conditions. If it works right for length=4, it probably works right for length=1000. You will probably need special case code to deal with the (length <2) cases. Hint. Probably the simplest strategy is to compute the length of the list, then use a for loop to hop over the right number of nodes to find the last node of the front half, and then cut the list at that point. There is a trick technique that uses two pointers to traverse the list. A "slow" pointer advances one nodes at a time, while the "fast" pointer goes two nodes at a time. When the fast pointer reaches the end, the slow pointer will be about half way. For either strategy, care is required to split the list at the right point.
/* Split the nodes of the given list into front and back halves, and return the two lists using the reference parameters. If the length is odd, the extra node should go in the front list. */ void FrontBackSplit(struct node* source, struct node** frontRef, struct node** backRef) { // Your code...

16

10 RemoveDuplicates()
Write a RemoveDuplicates() function which takes a list sorted in increasing order and deletes any duplicate nodes from the list. Ideally, the list should only be traversed once.
/* Remove duplicates from a sorted list. */ void RemoveDuplicates(struct node* head) { // Your code...

11 MoveNode()
This is a variant on Push(). Instead of creating a new node and pushing it onto the given list, MoveNode() takes two lists, removes the front node from the second list and pushes it onto the front of the first. This turns out to be a handy utility function to have for several later problems. Both Push() and MoveNode() are designed around the feature that list operations work most naturally at the head of the list. Here's a simple example of what MoveNode() should do...
void MoveNodeTest() { struct node* a = BuildOneTwoThree(); struct node* b = BuildOneTwoThree(); MoveNode(&a, &b); // a == {1, 1, 2, 3} // b == {2, 3} } /* Take the node from the front of the source, and move it to the front of the dest. It is an error to call this with the source list empty. */ void MoveNode(struct node** destRef, struct node** sourceRef) { // Your code // the list {1, 2, 3}

12 AlternatingSplit()
Write a function AlternatingSplit() that takes one list and divides up its nodes to make two smaller lists. The sublists should be made from alternating elements in the original list. So if the original list is {a, b, a, b, a}, then one sublist should be {a, a, a} and the other should be {b, b}. You may want to use MoveNode() as a helper. The elements in the new lists may be in any order (for some implementations, it turns out to be convenient if they are in the reverse order from the original list.)
/* Given the source list, split its nodes into two shorter lists. If we number the elements 0, 1, 2, ... then all the even elements should go in the first list, and all the odd elements in the second. The elements in the new lists may be in any order. */ void AlternatingSplit(struct node* source, struct node** aRef, struct node** bRef) { // Your code

17

13 ShuffleMerge()
Given two lists, merge their nodes together to make one list, taking nodes alternately between the two lists. So ShuffleMerge() with {1, 2, 3} and {7, 13, 1} should yield {1, 7, 2, 13, 3, 1}. If either list runs out, all the nodes should be taken from the other list. The solution depends on being able to move nodes to the end of a list as discussed in the Section 1 review. You may want to use MoveNode() as a helper. Overall, many techniques are possible: dummy node, local reference, or recursion. Using this function and FrontBackSplit(), you could simulate the shuffling of cards.
/* Merge the nodes of the two lists into a single list taking a node alternately from each list, and return the new list. */ struct node* ShuffleMerge(struct node* a, struct node* b) { // Your code

14 SortedMerge()
Write a SortedMerge() function that takes two lists, each of which is sorted in increasing order, and merges the two together into one list which is in increasing order. SortedMerge() should return the new list. The new list should be made by splicing together the nodes of the first two lists (use MoveNode()). Ideally, Merge() should only make one pass through each list. Merge() is tricky to get right it may be solved iteratively or recursively. There are many cases to deal with: either 'a' or 'b' may be empty, during processing either 'a' or 'b' may run out first, and finally there's the problem of starting the result list empty, and building it up while going through 'a' and 'b'.
/* Takes two lists sorted in increasing order, and splices their nodes together to make one big sorted list which is returned. */ struct node* SortedMerge(struct node* a, struct node* b) { // your code...

15 MergeSort()
(This problem requires recursion) Given FrontBackSplit() and SortedMerge(), it's pretty easy to write a classic recursive MergeSort(): split the list into two smaller lists, recursively sort those lists, and finally merge the two sorted lists together into a single sorted list. Ironically, this problem is easier than either FrontBackSplit() or SortedMerge().
void MergeSort(struct node* headRef) { // Your code...

18

16 SortedIntersect()
Given two lists sorted in increasing order, create and return a new list representing the intersection of the two lists. The new list should be made with its own memory the original lists should not be changed. In other words, this should be Push() list building, not MoveNode(). Ideally, each list should only be traversed once. This problem along with Union() and Difference() form a family of clever algorithms that exploit the constraint that the lists are sorted to find common nodes efficiently.
/* Compute a new sorted list that represents the intersection of the two given sorted lists. */ struct node* SortedIntersect(struct node* a, struct node* b) { // Your code

17 Reverse()
Write an iterative Reverse() function that reverses a list by rearranging all the .next pointers and the head pointer. Ideally, Reverse() should only need to make one pass of the list. The iterative solution is moderately complex. It's not so difficult that it needs to be this late in the document, but it goes here so it can be next to #18 Recursive Reverse which is quite tricky. The efficient recursive solution is quite complex (see next problem). (A memory drawing and some hints for Reverse() are below.)
void ReverseTest() { struct node* head; head = BuildOneTwoThree(); Reverse(&head); // head now points to the list {3, 2, 1} DeleteList(&head); } // clean up after ourselves

Stack
ReverseTest() head

Heap
List reverse before and after. Before (in gray) the list is {1, 2, 3}. After (in black), the pointers have been rearranged so the list is {3, 2, 1}.

"Push" Reverse Hint Iterate through the main list. Move each node to the front of the result list as you go. It's like doing a Push() operation with each node, except you use pointer re-arrangement on

19 the existing node instead of allocating a new node. You can use MoveNode() to do most of the work, or hand code the pointer re-arrangement. "3 Pointers" Hint This strategy is not as good as the "Push" strategy, but it's the first one I thought of (thanks to Owen Astrachan for pointing out the better solution). Instead of running a single "current" pointer down the list, run three pointers (front, middle, back) down the list in order: front is on one node, middle is just behind it, and back in turn is one behind middle. Once the code to run the three pointers down the list is clear and tested in a drawing, add code to reverse the .next pointer of the middle node during the iteration. Add code to take care of the empty list and to adjust the head pointer itself.
/* Reverse the given linked list by changing its .next pointers and its head pointer. Takes a pointer (reference) to the head pointer. */ void Reverse(struct node** headRef) { // your code...

18 RecursiveReverse()
(This problem is difficult and is only possible if you are familiar with recursion.) There is a short and efficient recursive solution to this problem. As before, the code should only make a single pass over the list. Doing it with multiple passes is easier but very slow, so here we insist on doing it in one pass.. Solving this problem requires a real understanding of pointer code and recursion.
/* Recursively reverses the given linked list by changing its .next pointers and its head pointer in one pass of the list. */ void RecursiveReverse(struct node** headRef) { // your code...

The Tree-List Recursion Problem Once you are done with these problems, see the best and most complex list recursion problem of all time: The great Tree-List-Recursion problem at http://cslibrary.stanford.edu/109/

20

Section 3 Solutions
1 Count() Solution
A straightforward iteration down the list just like Length().
int Count(struct node* head, int searchFor) { struct node* current = head; int count = 0; while (current != NULL) { if (current->data == searchFor) count++; current = current->next; } return count; }

Alternately, the iteration may be coded with a for loop instead of a while...
int Count2(struct node* head, int searchFor) { struct node* current; int count = 0; for (current = head; current != NULL; current = current->next) { if (current->data == searchFor) count++; } return count; }

2 GetNth() Solution
Combine standard list iteration with the additional problem of counting over to find the right node. Off-by-one errors are common in this sort of code. Check it carefully against a simple case. If it's right for n=0, n=1, and n=2, it will probably be right for n=1000.
int GetNth(struct node* head, int index) { struct node* current = head; int count = 0; // the index of the node we're currently looking at while (current != NULL) { if (count == index) return(current->data); count++; current = current->next; } assert(0); } // if we get to this line, the caller was asking // for a non-existent element so we assert fail.

21

3 DeleteList() Solution
Delete the whole list and set the head pointer to NULL. There is a slight complication inside the loop, since we need extract the .next pointer before we delete the node, since after the delete it will be technically unavailable.
void DeleteList(struct node** headRef) { struct node* current = *headRef; // deref headRef to get the real head struct node* next; while (current != NULL) { next = current->next; free(current); current = next; } *headRef = NULL; }

// note the next pointer // delete the node // advance to the next node

// Again, deref headRef to affect the real head back // in the caller.

4 Pop() Solution
Extract the data from the head node, delete the node, advance the head pointer to point at the next node in line. Uses a reference parameter since it changes the head pointer.
int Pop(struct node** headRef) { struct node* head; int result; head = *headRef; assert(head != NULL); result = head->data; // pull out the data before the node is deleted *headRef = head->next; // unlink the head node for the caller // Note the * -- uses a reference-pointer // just like Push() and DeleteList(). free(head); return(result); } // free the head node // don't forget to return the data from the link

5 InsertNth() Solution
This code handles inserting at the very front as a special case. Otherwise, it works by running a current pointer to the node before where the new node should go. Uses a for loop to march the pointer forward. The exact bounds of the loop (the use of < vs <=, n vs. n-1) are always tricky the best approach is to get the general structure of the iteration correct first, and then make a careful drawing of a couple test cases to adjust the n vs. n-1 cases to be correct. (The so called "OBOB" Off By One Boundary cases.) The OBOB cases are always tricky and not that interesting. Write the correct basic structure and then use a test case to get the OBOB cases correct. Once the insertion point has been determined, this solution uses Push() to do the link in. Alternately, the 3-Step Link In code could be pasted here directly.

22
void InsertNth(struct node** headRef, int index, int data) { // position 0 is a special case... if (index == 0) Push(headRef, data); else { struct node* current = *headRef; int i; for (i=0; i<index-1; i++) { assert(current != NULL); current = current->next; } assert(current != NULL);

// if this fails, index was too big

// tricky: you have to check one last time

Push(&(current->next), data); // Tricky use of Push() -// The pointer being pushed on is not // in the stack. But actually this works // fine -- Push() works for any node pointer. } }

6 SortedInsert() Solution
The basic strategy is to iterate down the list looking for the place to insert the new node. That could be the end of the list, or a point just before a node which is larger than the new node. The three solutions presented handle the "head end" case in different ways...
// Uses special case code for the head end void SortedInsert(struct node** headRef, struct node* newNode) { // Special case for the head end if (*headRef == NULL || (*headRef)->data >= newNode->data) { newNode->next = *headRef; *headRef = newNode; } else { // Locate the node before the point of insertion struct node* current = *headRef; while (current->next!=NULL && current->next->data<newNode->data) { current = current->next; } newNode->next = current->next; current->next = newNode; } }

// Dummy node strategy for the head end void SortedInsert2(struct node** headRef, struct node* newNode) { struct node dummy; struct node* current = &dummy; dummy.next = *headRef; while (current->next!=NULL && current->next->data<newNode->data) { current = current->next; } newNode->next = current->next; current->next = newNode;

23
*headRef = dummy.next; }

// Local references strategy for the head end void SortedInsert3(struct node** headRef, struct node* newNode) { struct node** currentRef = headRef; while (*currentRef!=NULL && (*currentRef)->data<newNode->data) { currentRef = &((*currentRef)->next); } newNode->next = *currentRef; *currentRef = newNode; } // Bug: this line used to have // an incorrect (*currRef)->next

7 InsertSort() Solution
Start with an empty result list. Iterate through the source list and SortedInsert() each of its nodes into the result list. Be careful to note the .next field in each node before moving it into the result list.
// Given a list, change it to be in sorted order (using SortedInsert()). void InsertSort(struct node** headRef) { struct node* result = NULL; // build the answer here struct node* current = *headRef; // iterate over the original list struct node* next; while (current!=NULL) { next = current->next; // tricky - note the next pointer before we change it SortedInsert(&result, current); current = next; } *headRef = result; }

8 Append() Solution
The case where the 'a' list is empty is a special case handled first in that case the 'a' head pointer needs to be changed directly. Otherwise we iterate down the 'a' list until we find its last node with the test (current->next != NULL), and then tack on the 'b' list there. Finally, the original 'b' head is set to NULL. This code demonstrates extensive use of pointer reference parameters, and the common problem of needing to locate the last node in a list. (There is also a drawing of how Append() uses memory below.)
void Append(struct node** aRef, struct node** bRef) { struct node* current; if (*aRef == NULL) { // Special case if a is empty *aRef = *bRef; } else { // Otherwise, find the end of a, and append b there current = *aRef; while (current->next != NULL) { // find the last node current = current->next; }

24
current->next = *bRef; } *bRef=NULL; } // NULL the original b, since it has been appended above // hang the b list off the last node

Append() Test and Drawing The following AppendTest() code calls Append() to join two lists. What does memory look like just before the call to Append() exits?
void AppendTest() { struct node* a; struct node* b; // set a to {1, 2} // set b to {3, 4} Append(&a, &b); }

As an example of how reference parameters work, note how reference parameters in Append() point back to the head pointers in AppendTest()...

Stack
AppendTest() a b Append(&a, &b) aRef bRef current

Heap

9 FrontBackSplit() Solution
Two solutions are presented...
// Uses the "count the nodes" strategy void FrontBackSplit(struct node* source, struct node** frontRef, struct node** backRef) { int len = Length(source); int i; struct node* current = source;

25

if (len < 2) { *frontRef = source; *backRef = NULL; } else { int hopCount = (len-1)/2; //(figured these with a few drawings) for (i = 0; i<hopCount; i++) { current = current->next; } // Now cut at current *frontRef = source; *backRef = current->next; current->next = NULL; } }

// Uses the fast/slow pointer strategy void FrontBackSplit2(struct node* source, struct node** frontRef, struct node** backRef) { struct node* fast; struct node* slow; if (source==NULL || source->next==NULL) { *frontRef = source; *backRef = NULL; } else { slow = source; fast = source->next; // length < 2 cases

// Advance 'fast' two nodes, and advance 'slow' one node while (fast != NULL) { fast = fast->next; if (fast != NULL) { slow = slow->next; fast = fast->next; } } // 'slow' is before the midpoint in the list, so split it in two // at that point. *frontRef = source; *backRef = slow->next; slow->next = NULL; } }

10 RemoveDuplicates() Solution
Since the list is sorted, we can proceed down the list and compare adjacent nodes. When adjacent nodes are the same, remove the second one. There's a tricky case where the node after the next node needs to be noted before the deletion.
// Remove duplicates from a sorted list void RemoveDuplicates(struct node* head) { struct node* current = head;

26

if (current == NULL) return;

// do nothing if the list is empty

// Compare current node with next node while(current->next!=NULL) { if (current->data == current->next->data) { struct node* nextNext = current->next->next; free(current->next); current->next = nextNext; } else { current = current->next; // only advance if no deletion } } }

11 MoveNode() Solution
The MoveNode() code is most similar to the code for Push(). It's short just changing a couple pointers but it's complex. Make a drawing.
void MoveNode(struct node** destRef, struct node** sourceRef) { struct node* newNode = *sourceRef; // the front source node assert(newNode != NULL); *sourceRef = newNode->next; newNode->next = *destRef; *destRef = newNode; } // Advance the source pointer // Link the old dest off the new node // Move dest to point to the new node

12 AlternatingSplit() Solution
The simplest approach iterates over the source list and use MoveNode() to pull nodes off the source and alternately put them on 'a' and b'. The only strange part is that the nodes will be in the reverse order that they occurred in the source list. AlternatingSplit()
void AlternatingSplit(struct node* source, struct node** aRef, struct node** bRef) { struct node* a = NULL; // Split the nodes to these 'a' and 'b' lists struct node* b = NULL; struct node* current = source; while (current != NULL) { MoveNode(&a, &current); // Move a node to 'a' if (current != NULL) { MoveNode(&b, &current); // Move a node to 'b' } } *aRef = a; *bRef = b; }

27 AlternatingSplit() Using Dummy Nodes Here is an alternative approach which builds the sub-lists in the same order as the source list. The code uses a temporary dummy header nodes for the 'a' and 'b' lists as they are being built. Each sublist has a "tail" pointer which points to its current last node that way new nodes can be appended to the end of each list easily. The dummy nodes give the tail pointers something to point to initially. The dummy nodes are efficient in this case because they are temporary and allocated in the stack. Alternately, the "local references" technique could be used to get rid of the dummy nodes (see Section 1 for more details).
void AlternatingSplit2(struct node* source, struct node** aRef, struct node** bRef) { struct node aDummy; struct node* aTail = &aDummy; // points to the last node in 'a' struct node bDummy; struct node* bTail = &bDummy; // points to the last node in 'b' struct node* current = source; aDummy.next = NULL; bDummy.next = NULL; while (current != NULL) { MoveNode(&(aTail->next), &current); // add at 'a' tail aTail = aTail->next; // advance the 'a' tail if (current != NULL) { MoveNode(&(bTail->next), &current); bTail = bTail->next; } } *aRef = aDummy.next; *bRef = bDummy.next; }

13 SuffleMerge() Solution
There are four separate solutions included. See Section 1 for information on the various dummy node and reference techniques. SuffleMerge() Dummy Node Not Using MoveNode()
struct node* ShuffleMerge(struct node* a, struct node* b) { struct node dummy; struct node* tail = &dummy; dummy.next = NULL; while (1) { if (a==NULL) { tail->next = b; break; } else if (b==NULL) { tail->next = a; break; } else { tail->next = a; tail = a; a = a->next;

// empty list cases

// common case: move two nodes to tail

28
tail->next = b; tail = b; b = b->next; } } return(dummy.next); }

SuffleMerge() Dummy Node Using MoveNode() Basically the same as above, but use MoveNode().
struct node* ShuffleMerge(struct node* a, struct node* b) { struct node dummy; struct node* tail = &dummy; dummy.next = NULL; while (1) { if (a==NULL) { tail->next = b; break; } else if (b==NULL) { tail->next = a; break; } else { MoveNode(&(tail->next), &a); tail = tail->next; MoveNode(&(tail->next), &b); tail = tail->next; } } return(dummy.next); }

SuffleMerge() Local References Uses a local reference to get rid of the dummy nodes entirely.
struct node* ShuffleMerge(struct node* a, struct node* b) { struct node* result = NULL; struct node** lastPtrRef = &result; while (1) { if (a==NULL) { *lastPtrRef = b; break; } else if (b==NULL) { *lastPtrRef = a; break; } else { MoveNode(lastPtrRef, &a); lastPtrRef = &((*lastPtrRef)->next); MoveNode(lastPtrRef, &b); lastPtrRef = &((*lastPtrRef)->next);

29
} } return(result); }

SuffleMerge() Recursive The recursive solution is the most compact of all, but is probably not appropriate for production code since it uses stack space proportionate to the lengths of the lists.
struct node* ShuffleMerge(struct node* a, struct node* b) { struct node* result; struct node* recur; if (a==NULL) return(b); // see if either list is empty else if (b==NULL) return(a); else { // it turns out to be convenient to do the recursive call first -// otherwise a->next and b->next need temporary storage. recur = ShuffleMerge(a->next, b->next); result = a; a->next = b; b->next = recur; return(result); } } // one node from a // one from b // then the rest

14 SortedMerge() Solution
SortedMerge() Using Dummy Nodes The strategy here uses a temporary dummy node as the start of the result list. The pointer tail always points to the last node in the result list, so appending new nodes is easy. The dummy node gives tail something to point to initially when the result list is empty. This dummy node is efficient, since it is only temporary, and it is allocated in the stack. The loop proceeds, removing one node from either 'a' or 'b', and adding it to tail. When we are done, the result is in dummy.next.
struct node* SortedMerge(struct node* a, struct node* b) { struct node dummy; // a dummy first node to hang the result on struct node* tail = &dummy; // Points to the last result node -// so tail->next is the place to add // new nodes to the result. dummy.next = NULL; while (1) { if (a == NULL) { // if either list runs out, use the other list tail->next = b; break; } else if (b == NULL) { tail->next = a; break; }

30
if (a->data <= b->data) { MoveNode(&(tail->next), &a); } else { MoveNode(&(tail->next), &b); } tail = tail->next; } return(dummy.next); }

SortedMerge() Using Local References This solution is structurally very similar to the above, but it avoids using a dummy node. Instead, it maintains a struct node** pointer, lastPtrRef, that always points to the last pointer of the result list. This solves the same case that the dummy node did dealing with the result list when it is empty. If you are trying to build up a list at its tail, either the dummy node or the struct node** "reference" strategy can be used (see Section 1 for details).
struct node* SortedMerge2(struct node* a, struct node* b) { struct node* result = NULL; struct node** lastPtrRef = &result; // point to the last result pointer while (1) { if (a==NULL) { *lastPtrRef = b; break; } else if (b==NULL) { *lastPtrRef = a; break; } if (a->data <= b->data) { MoveNode(lastPtrRef, &a); } else { MoveNode(lastPtrRef, &b); } lastPtrRef = &((*lastPtrRef)->next);

// tricky: advance to point to // the next ".next" field

} return(result); }

SortedMerge() Using Recursion Merge() is one of those nice recursive problems where the recursive solution code is much cleaner than the iterative code. You probably wouldn't want to use the recursive version for production code however, because it will use stack space which is proportional to the length of the lists.
struct node* SortedMerge3(struct node* a, struct node* b) { struct node* result = NULL;

31
// Base cases if (a==NULL) return(b); else if (b==NULL) return(a); // Pick either a or b, and recur if (a->data <= b->data) { result = a; result->next = SortedMerge3(a->next, b); } else { result = b; result->next = SortedMerge3(a, b->next); } return(result); }

15 MergeSort() Solution
The MergeSort strategy is: split into sublists, sort the sublists recursively, merge the two sorted lists together to form the answer.
void MergeSort(struct node** headRef) { struct node* head = *headRef; struct node* a; struct node* b; // Base case -- length 0 or 1 if ((head == NULL) || (head->next == NULL)) { return; } FrontBackSplit(head, &a, &b); // Split head into 'a' and 'b' sublists // We could just as well use AlternatingSplit()

MergeSort(&a); // Recursively sort the sublists MergeSort(&b); *headRef } = SortedMerge(a, b); // answer = merge the two sorted lists together

(Extra for experts) Using recursive stack space proportional to the length of a list is not recommended. However, the recursion in this case is ok it uses stack space which is proportional to the log of the length of the list. For a 1000 node list, the recursion will only go about 10 deep. For a 2000 node list, it will go 11 deep. If you think about it, you can see that doubling the size of the list only increases the depth by 1.

16 SortedIntersect() Solution
The strategy is to advance up both lists and build the result list as we go. When the current point in both lists are the same, add a node to the result. Otherwise, advance whichever list is smaller. By exploiting the fact that both lists are sorted, we only traverse each list once. To build up the result list, both the dummy node and local reference strategy solutions are shown...
// This solution uses the temporary dummy to build up the result list struct node* SortedIntersect(struct node* a, struct node* b) { struct node dummy;

32
struct node* tail = &dummy; dummy.next = NULL; // Once one or the other list runs out -- we're done while (a!=NULL && b!=NULL) { if (a->data == b->data) { Push((&tail->next), a->data); tail = tail->next; a = a->next; b = b->next; } else if (a->data < b->data) { // advance the smaller list a = a->next; } else { b = b->next; } } return(dummy.next); }

// This solution uses the local reference struct node* SortedIntersect2(struct node* a, struct node* b) { struct node* result = NULL; struct node** lastPtrRef = &result; // Advance comparing the first nodes in both lists. // When one or the other list runs out, we're done. while (a!=NULL && b!=NULL) { if (a->data == b->data) { // found a node for the intersection Push(lastPtrRef, a->data); lastPtrRef = &((*lastPtrRef)->next); a=a->next; b=b->next; } else if (a->data < b->data) { // advance the smaller list a=a->next; } else { b=b->next; } } return(result); }

17 Reverse() Solution
This first solution uses the "Push" strategy with the pointer re-arrangement hand coded inside the loop. There's a slight trickyness in that it needs to save the value of the "current->next" pointer at the top of the loop since the body of the loop overwrites that pointer.
/* Iterative list reverse. Iterate through the list left-right.

33
Move/insert each node to the front of the result list -like a Push of the node. */ static void Reverse(struct node** headRef) { struct node* result = NULL; struct node* current = *headRef; struct node* next; while (current != NULL) { next = current->next; current->next = result; result = current; current = next; } *headRef = result; }

// tricky: note the next node // move the node onto the result

Here's the variation on the above that uses MoveNode() to do the work...
static void Reverse2(struct node** headRef) { struct node* result = NULL; struct node* current = *headRef; while (current != NULL) { MoveNode(&result, &current); } *headRef = result; }

Finally, here's the back-middle-front strategy...


// Reverses the given linked list by changing its .next pointers and // its head pointer. Takes a pointer (reference) to the head pointer. void Reverse(struct node** headRef) { if (*headRef != NULL) { // special case: skip the empty list /* Plan for down the down the For each three to */

this loop: move three pointers: front, middle, back list in order. Middle is the main pointer running list. Front leads it and Back trails it. step, reverse the middle pointer and then advance all get the next node.

struct node* middle = *headRef; struct node* front = middle->next; struct node* back = NULL;

// the main pointer // the two other pointers (NULL ok)

while (1) { middle->next = back; if (front == NULL) break;

// fix the middle node // test if done

34

back = middle; middle = front; front = front->next; } *headRef = middle; } }

// advance the three pointers

// fix the head pointer to point to the new front

18 RecursiveReverse() Solution
Probably the hardest part is accepting the concept that the RecursiveReverse(&rest) does in fact reverse the rest. Then then there's a trick to getting the one front node all the way to the end of the list. Make a drwaing to see how the trick works.
void RecursiveReverse(struct node** headRef) { struct node* first; struct node* rest; if (*headRef == NULL) return; first = *headRef; rest = first->next; // empty list base case

// suppose first = {1, 2, 3} // rest = {2, 3} // empty rest base case // Recursively reverse the smaller {2, 3} case // after: rest = {3, 2}

if (rest == NULL) return; RecursiveReverse(&rest);

first->next->next = first; // put the first elem on the end of the list first->next = NULL; // (tricky step -- make a drawing) *headRef = rest; } // fix the head pointer

The inefficient soluition is to reverse the last n-1 elements of the list, and then iterate all the way down to the new tail and put the old head node there. That solution is very slow compared to the above which gets the head node in the right place without extra iteration.

35

Appendix
Basic Utility Function Implementations Here is the source code for the basic utility functions.
Length() // Return the number of nodes in a list int Length(struct node* head) { int count = 0; struct node* current = head; while (current != NULL) { count++; current=current->next; } return(count); }

Push() // Given a reference (pointer to pointer) to the head // of a list and an int, push a new node on the front of the list. // Creates a new node with the int, links the list off the .next of the // new node, and finally changes the head to point to the new node. void Push(struct node** headRef, int newData) { struct node* newNode = (struct node*) malloc(sizeof(struct node)); // allocate node newNode->data = newData; // put in the data newNode->next = (*headRef); // link the old list off the new node (*headRef) = newNode; // move the head to point to the new node }

BuildOneTwoThree() // Build and return the list {1, 2, 3} struct node* BuildOneTwoThree() { struct node* head = NULL; // Start with the empty list Push(&head, 3); // Use Push() to add all the data Push(&head, 2); Push(&head, 1); return(head); }

Binary Trees

Page: 1

Binary Trees
by Nick Parlante This article introduces the basic concepts of binary trees, and then works through a series of practice problems with solution code in C/C++ and Java. Binary trees have an elegant recursive pointer structure, so they are a good way to learn recursive pointer algorithms.

Contents
Section 1. Binary Tree Structure -- a quick introduction to binary trees and the code that operates on them Section 2. Binary Tree Problems -- practice problems in increasing order of difficulty Section 3. C Solutions -- solution code to the problems for C and C++ programmers Section 4. Java versions -- how binary trees work in Java, with solution code

Stanford CS Education Library -- #110


This is article #110 in the Stanford CS Education Library. This and other free CS materials are available at the library (http://cslibrary.stanford.edu/). That people seeking education should have the opportunity to find it. This article may be used, reproduced, excerpted, or sold so long as this paragraph is clearly reproduced. Copyright 2000-2001, Nick Parlante, nick.parlante@cs.stanford.edu.

Related CSLibrary Articles


Linked List Problems (http://cslibrary.stanford.edu/105/) -- a large collection of linked list problems using various pointer techniques (while this binary tree article concentrates on recursion) Pointer and Memory (http://cslibrary.stanford.edu/102/) -- basic concepts of pointers and memory The Great Tree-List Problem (http://cslibrary.stanford.edu/109/) -- a great pointer recursion problem that uses both trees and lists

Section 1 -- Introduction To Binary Trees


A binary tree is made of nodes, where each node contains a "left" pointer, a "right" pointer, and a data element. The "root" pointer points to the topmost node in the tree. The left and right pointers recursively point to smaller "subtrees" on either side. A null pointer represents a binary tree with no elements -- the empty tree. The formal recursive definition is: a binary tree is either empty (represented by a null pointer), or is made of a single node, where the left and right pointers (recursive definition ahead) each point to a binary tree.

http://cslibrary.stanford.edu/110/ BinaryTrees.html

Binary Trees

Page: 2

A "binary search tree" (BST) or "ordered binary tree" is a type of binary tree where the nodes are arranged in order: for each node, all elements in its left subtree are less-or-equal to the node (<=), and all the elements in its right subtree are greater than the node (>). The tree shown above is a binary search tree -- the "root" node is a 5, and its left subtree nodes (1, 3, 4) are <= 5, and its right subtree nodes (6, 9) are > 5. Recursively, each of the subtrees must also obey the binary search tree constraint: in the (1, 3, 4) subtree, the 3 is the root, the 1 <= 3 and 4 > 3. Watch out for the exact wording in the problems -- a "binary search tree" is different from a "binary tree". The nodes at the bottom edge of the tree have empty subtrees and are called "leaf" nodes (1, 4, 6) while the others are "internal" nodes (3, 5, 9).

Binary Search Tree Niche


Basically, binary search trees are fast at insert and lookup. The next section presents the code for these two algorithms. On average, a binary search tree algorithm can locate a node in an N node tree in order lg(N) time (log base 2). Therefore, binary search trees are good for "dictionary" problems where the code inserts and looks up information indexed by some key. The lg(N) behavior is the average case -- it's possible for a particular tree to be much slower depending on its shape.

Strategy
Some of the problems in this article use plain binary trees, and some use binary search trees. In any case, the problems concentrate on the combination of pointers and recursion. (See the articles linked above for pointer articles that do not emphasize recursion.) For each problem, there are two things to understand... The node/pointer structure that makes up the tree and the code that manipulates it The algorithm, typically recursive, that iterates over the tree When thinking about a binary tree problem, it's often a good idea to draw a few little trees to think about the various cases.
http://cslibrary.stanford.edu/110/ BinaryTrees.html

Binary Trees

Page: 3

Typical Binary Tree Code in C/C++


As an introduction, we'll look at the code for the two most basic binary search tree operations -- lookup() and insert(). The code here works for C or C++. Java programers can read the discussion here, and then look at the Java versions in Section 4. In C or C++, the binary tree is built with a node type like this... struct node { int data; struct node* left; struct node* right; }

Lookup()
Given a binary search tree and a "target" value, search the tree to see if it contains the target. The basic pattern of the lookup() code occurs in many recursive tree algorithms: deal with the base case where the tree is empty, deal with the current node, and then use recursion to deal with the subtrees. If the tree is a binary search tree, there is often some sort of less-than test on the node to decide if the recursion should go left or right. /* Given a binary tree, return true if a node with the target data is found in the tree. Recurs down the tree, chooses the left or right branch by comparing the target to each node. */ static int lookup(struct node* node, int target) { // 1. Base case == empty tree // in that case, the target is not found so return false if (node == NULL) { return(false); } else { // 2. see if found here if (target == node->data) return(true); else { // 3. otherwise recur down the correct subtree if (target < node->data) return(lookup(node->left, target)); else return(lookup(node->right, target)); } } }

The lookup() algorithm could be written as a while-loop that iterates down the tree. Our version uses recursion to help prepare you for the problems below that require recursion.

Pointer Changing Code


There is a common problem with pointer intensive code: what if a function needs to change one of the pointer parameters passed to it? For example, the insert() function below may want to change the root pointer. In C and C++, one solution uses pointers-to-pointers (aka "reference parameters"). That's a fine technique, but here we will use the simpler technique that a function that wishes to change a pointer passed to it will return the new value of the pointer to the caller. The caller is responsible for using the new value. Suppose we have a change() function
http://cslibrary.stanford.edu/110/ BinaryTrees.html

Binary Trees

Page: 4

that may change the the root, then a call to change() will look like this... // suppose the variable "root" points to the tree root = change(root); We take the value returned by change(), and use it as the new value for root. This construct is a little awkward, but it avoids using reference parameters which confuse some C and C++ programmers, and Java does not have reference parameters at all. This allows us to focus on the recursion instead of the pointer mechanics. (For lots of problems that use reference parameters, see CSLibrary #105, Linked List Problems, http://cslibrary.stanford.edu/105/).

Insert()
Insert() -- given a binary search tree and a number, insert a new node with the given number into the tree in the correct place. The insert() code is similar to lookup(), but with the complication that it modifies the tree structure. As described above, insert() returns the new tree pointer to use to its caller. Calling insert() with the number 5 on this tree... 2 / \ 1 10

returns the tree... 2 / \ 1 / 5 The solution shown here introduces a newNode() helper function that builds a single node. The base-case/recursion structure is similar to the structure in lookup() -- each call checks for the NULL case, looks at the node at hand, and then recurs down the left or right subtree if needed. /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ struct node* NewNode(int data) { struct node* node = new(struct node); // "new" is like "malloc" node->data = data; node->left = NULL; node->right = NULL; return(node); } 10

/* Give a binary search tree and a number, inserts a new node with the given number in the correct place in the tree. Returns the new root pointer which the caller should then use (the standard trick to avoid using reference parameters). */ struct node* insert(struct node* node, int data) {
http://cslibrary.stanford.edu/110/ BinaryTrees.html

Binary Trees

Page: 5

// 1. If the tree is empty, return a new, single node if (node == NULL) { return(newNode(data)); } else { // 2. Otherwise, recur down the tree if (data <= node->data) node->left = insert(node->left, data); else node->right = insert(node->right, data); return(node); // return the (unchanged) node pointer } }

The shape of a binary tree depends very much on the order that the nodes are inserted. In particular, if the nodes are inserted in increasing order (1, 2, 3, 4), the tree nodes just grow to the right leading to a linked list shape where all the left pointers are NULL. A similar thing happens if the nodes are inserted in decreasing order (4, 3, 2, 1). The linked list shape defeats the lg(N) performance. We will not address that issue here, instead focusing on pointers and recursion.

Section 2 -- Binary Tree Problems


Here are 14 binary tree problems in increasing order of difficulty. Some of the problems operate on binary search trees (aka "ordered binary trees") while others work on plain binary trees with no special ordering. The next section, Section 3, shows the solution code in C/C++. Section 4 gives the background and solution code in Java. The basic structure and recursion of the solution code is the same in both languages -- the differences are superficial. Reading about a data structure is a fine introduction, but at some point the only way to learn is to actually try to solve some problems starting with a blank sheet of paper. To get the most out of these problems, you should at least attempt to solve them before looking at the solution. Even if your solution is not quite right, you will be building up the right skills. With any pointer-based code, it's a good idea to make memory drawings of a a few simple cases to see how the algorithm should work.

1. build123()
This is a very basic problem with a little pointer manipulation. (You can skip this problem if you are already comfortable with pointers.) Write code that builds the following little 1-2-3 binary search tree... 2 / \ 1 3

Write the code in three different ways... a: by calling newNode() three times, and using three pointer variables b: by calling newNode() three times, and using only one pointer variable c: by calling insert() three times passing it the root pointer to build up the tree (In Java, write a build123() method that operates on the receiver to change it to be the 1-2-3 tree with the given coding constraints. See Section 4.) struct node* build123() {

2. size()
http://cslibrary.stanford.edu/110/ BinaryTrees.html

Binary Trees

Page: 6

This problem demonstrates simple binary tree traversal. Given a binary tree, count the number of nodes in the tree. int size(struct node* node) {

3. maxDepth()
Given a binary tree, compute its "maxDepth" -- the number of nodes along the longest path from the root node down to the farthest leaf node. The maxDepth of the empty tree is 0, the maxDepth of the tree on the first page is 3. int maxDepth(struct node* node) {

4. minValue()
Given a non-empty binary search tree (an ordered binary tree), return the minimum data value found in that tree. Note that it is not necessary to search the entire tree. A maxValue() function is structurally very similar to this function. This can be solved with recursion or with a simple while loop. int minValue(struct node* node) {

5. printTree()
Given a binary search tree (aka an "ordered binary tree"), iterate over the nodes to print them out in increasing order. So the tree... 4 / \ 2 / \ 1 3 5

Produces the output "1 2 3 4 5". This is known as an "inorder" traversal of the tree. Hint: For each node, the strategy is: recur left, print the node data, recur right. void printTree(struct node* node) {

6. printPostorder()
Given a binary tree, print out the nodes of the tree according to a bottom-up "postorder" traversal -- both subtrees of a node are printed out completely before the node itself is printed, and each left subtree is printed before the right subtree. So the tree... 4 / \ 2 / \ 1 3 5

Produces the output "1 3 2 5 4". The description is complex, but the code is simple. This is the sort of bottom-up traversal that would be used, for example, to evaluate an expression tree where a node is an operation like '+' and its subtrees are, recursively, the two subexpressions for the '+'.
http://cslibrary.stanford.edu/110/ BinaryTrees.html

Binary Trees

Page: 7

void printPostorder(struct node* node) {

7. hasPathSum()
We'll define a "root-to-leaf path" to be a sequence of nodes in a tree starting with the root node and proceeding downward to a leaf (a node with no children). We'll say that an empty tree contains no root-to-leaf paths. So for example, the following tree has exactly four root-to-leaf paths: 5 / \ 4 / 11 / 7 \ 2 8 / \ 13 4 \ 1

Root-to-leaf paths: path 1: 5 4 11 7 path 2: 5 4 11 2 path 3: 5 8 13 path 4: 5 8 4 1 For this problem, we will be concerned with the sum of the values of such a path -- for example, the sum of the values on the 5-4-11-7 path is 5 + 4 + 11 + 7 = 27. Given a binary tree and a sum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. Return false if no such path can be found. (Thanks to Owen Astrachan for suggesting this problem.) int hasPathSum(struct node* node, int sum) {

8. printPaths()
Given a binary tree, print out all of its root-to-leaf paths as defined above. This problem is a little harder than it looks, since the "path so far" needs to be communicated between the recursive calls. Hint: In C, C++, and Java, probably the best solution is to create a recursive helper function printPathsRecur(node, int path[], int pathLen), where the path array communicates the sequence of nodes that led up to the current call. Alternately, the problem may be solved bottom-up, with each node returning its list of paths. This strategy works quite nicely in Lisp, since it can exploit the built in list and mapping primitives. (Thanks to Matthias Felleisen for suggesting this problem.) Given a binary tree, print out all of its root-to-leaf paths, one per line. void printPaths(struct node* node) {

9. mirror()
Change a tree so that the roles of the left and right pointers are swapped at every node. So the tree... 4 / \ 2 5 / \
http://cslibrary.stanford.edu/110/ BinaryTrees.html

Binary Trees

Page: 8

is changed to... 4 / \ 5 2 / \ 3 1 The solution is short, but very recursive. As it happens, this can be accomplished without changing the root node pointer, so the return-the-new-root construct is not necessary. Alternately, if you do not want to change the tree nodes, you may construct and return a new mirror tree based on the original tree. void mirror(struct node* node) {

10. doubleTree()
For each node in a binary search tree, create a new duplicate node, and insert the duplicate as the left child of the original node. The resulting tree should still be a binary search tree. So the tree... 2 / \ 1 3 is changed to... 2 / \ 2 3 / / 1 3 / 1 As with the previous problem, this can be accomplished without changing the root node pointer. void doubleTree(struct node* node) {

11. sameTree()
Given two binary trees, return true if they are structurally identical -- they are made of nodes with the same values arranged in the same way. (Thanks to Julie Zelenski for suggesting this problem.) int sameTree(struct node* a, struct node* b) {

12. countTrees()
This is not a binary tree programming problem in the ordinary sense -- it's more of a math/combinatorics recursion problem that happens to use binary trees. (Thanks to Jerry Cain for suggesting this problem.) Suppose you are building an N node binary search tree with the values 1..N. How many structurally different binary search trees are there that store those values? Write a recursive function that, given the number of distinct values, computes the number of structurally unique binary search trees that store those values. For example,
http://cslibrary.stanford.edu/110/ BinaryTrees.html

Binary Trees

Page: 9

countTrees(4) should return 14, since there are 14 structurally unique binary search trees that store 1, 2, 3, and 4. The base case is easy, and the recursion is short but dense. Your code should not construct any actual trees; it's just a counting problem. int countTrees(int numKeys) {

Binary Search Tree Checking (for problems 13 and 14)


This background is used by the next two problems: Given a plain binary tree, examine the tree to determine if it meets the requirement to be a binary search tree. To be a binary search tree, for every node, all of the nodes in its left tree must be <= the node, and all of the nodes in its right subtree must be > the node. Consider the following four examples... a. 2 5 / \ 7 -> TRUE

b. 6

5 / \ 7

-> FALSE, because the 6 is not ok to the left of the 5

c.

5 -> TRUE / \ 2 7 /

1 d. 5 -> FALSE, the 6 is ok with the 2, but the 6 is not ok with the 5 / \ 2 7 / \ 1 6

For the first two cases, the right answer can be seen just by comparing each node to the two nodes immediately below it. However, the fourth case shows how checking the BST quality may depend on nodes which are several layers apart -- the 5 and the 6 in that case.

13 isBST() -- version 1
Suppose you have helper functions minValue() and maxValue() that return the min or max int value from a non-empty tree (see problem 3 above). Write an isBST() function that returns true if a tree is a binary search tree and false otherwise. Use the helper functions, and don't forget to check every node in the tree. It's ok if your solution is not very efficient. (Thanks to Owen Astrachan for the idea of having this problem, and comparing it to problem 14) Returns true if a binary tree is a binary search tree. int isBST(struct node* node) {

14. isBST() -- version 2


http://cslibrary.stanford.edu/110/ BinaryTrees.html

Binary Trees

Page: 10

Version 1 above runs slowly since it traverses over some parts of the tree many times. A better solution looks at each node only once. The trick is to write a utility helper function isBSTRecur(struct node* node, int min, int max) that traverses down the tree keeping track of the narrowing min and max allowed values as it goes, looking at each node only once. The initial values for min and max should be INT_MIN and INT_MAX -- they narrow from there. /* Returns true if the given tree is a binary search tree (efficient version). */ int isBST2(struct node* node) { return(isBSTRecur(node, INT_MIN, INT_MAX)); } /* Returns true if the given tree is a BST and its values are >= min and <= max. */ int isBSTRecur(struct node* node, int min, int max) {

15. Tree-List
The Tree-List problem is one of the greatest recursive pointer problems ever devised, and it happens to use binary trees as well. CLibarary #109 http://cslibrary.stanford.edu/109/ works through the Tree-List problem in detail and includes solution code in C and Java. The problem requires an understanding of binary trees, linked lists, recursion, and pointers. It's a great problem, but it's complex.

Section 3 -- C/C++ Solutions


Make an attempt to solve each problem before looking at the solution -- it's the best way to learn.

1. Build123() Solution (C/C++)


// call newNode() three times struct node* build123a() { struct node* root = newNode(2); struct node* lChild = newNode(1); struct node* rChild = newNode(3); root->left = lChild; root->right= rChild; return(root); } // call newNode() three times, and use only one local variable struct node* build123b() { struct node* root = newNode(2); root->left = newNode(1); root->right = newNode(3); return(root); }
http://cslibrary.stanford.edu/110/ BinaryTrees.html

Binary Trees

Page: 11

/* Build 123 by calling insert() three times. Note that the '2' must be inserted first. */ struct node* build123c() { struct node* root = NULL; root = insert(root, 2); root = insert(root, 1); root = insert(root, 3); return(root); }

2. size() Solution (C/C++)


/* Compute the number of nodes in a tree. */ int size(struct node* node) { if (node==NULL) { return(0); } else { return(size(node->left) + 1 + size(node->right)); } }

3. maxDepth() Solution (C/C++)


/* Compute the "maxDepth" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node. */ int maxDepth(struct node* node) { if (node==NULL) { return(0); } else { // compute the depth of each subtree int lDepth = maxDepth(node->left); int rDepth = maxDepth(node->right); // use the larger one if (lDepth > rDepth) return(lDepth+1); else return(rDepth+1); } }

4. minValue() Solution (C/C++)


/* Given a non-empty binary search tree, return the minimum data value found in that tree.
http://cslibrary.stanford.edu/110/ BinaryTrees.html

Binary Trees

Page: 12

Note that the entire tree does not need to be searched. */ int minValue(struct node* node) { struct node* current = node; // loop down to find the leftmost leaf while (current->left != NULL) { current = current->left; } return(current->data); }

5. printTree() Solution (C/C++)


/* Given a binary search tree, print out its data elements in increasing sorted order. */ void printTree(struct node* node) { if (node == NULL) return; printTree(node->left); printf("%d ", node->data); printTree(node->right); }

6. printPostorder() Solution (C/C++)


/* Given a binary tree, print its nodes according to the "bottom-up" postorder traversal. */ void printPostorder(struct node* node) { if (node == NULL) return; // first recur on both subtrees printTree(node->left); printTree(node->right); // then deal with the node printf("%d ", node->data); }

7. hasPathSum() Solution (C/C++)


/* Given a tree and a sum, return true if there is a path from the root down to a leaf, such that adding up all the values along the path equals the given sum.
http://cslibrary.stanford.edu/110/ BinaryTrees.html

Binary Trees

Page: 13

Strategy: subtract the node value from the sum when recurring down, and check to see if the sum is 0 when you run out of tree. */ int hasPathSum(struct node* node, int sum) { // return true if we run out of tree and sum==0 if (node == NULL) { return(sum == 0); } else { // otherwise check both subtrees int subSum = sum - node->data; return(hasPathSum(node->left, subSum) || hasPathSum(node->right, subSum)); } }

8. printPaths() Solution (C/C++)


/* Given a binary tree, print out all of its root-to-leaf paths, one per line. Uses a recursive helper to do the work. */ void printPaths(struct node* node) { int path[1000]; printPathsRecur(node, path, 0); } /* Recursive helper function -- given a node, and an array containing the path from the root node up to but not including this node, print out all the root-leaf paths. */ void printPathsRecur(struct node* node, int path[], int pathLen) { if (node==NULL) return; // append this node to the path array path[pathLen] = node->data; pathLen++; // it's a leaf, so print the path that led to here if (node->left==NULL && node->right==NULL) { printArray(path, pathLen); } else { // otherwise try both subtrees printPathsRecur(node->left, path, pathLen); printPathsRecur(node->right, path, pathLen); } } // Utility that prints out an array on a line. void printArray(int ints[], int len) { int i; for (i=0; i<len; i++) {
http://cslibrary.stanford.edu/110/ BinaryTrees.html

Binary Trees

Page: 14

printf("%d ", ints[i]); } printf("\n"); }

9. mirror() Solution (C/C++)


/* Change a tree so that the roles of the left and right pointers are swapped at every node. So the tree... 4 / \ 2 5 / \ 1 3 is changed to... 4 / \ 5 2 / \ 3 1 */ void mirror(struct node* node) { if (node==NULL) { return; } else { struct node* temp; // do the subtrees mirror(node->left); mirror(node->right); // swap the pointers in this node temp = node->left; node->left = node->right; node->right = temp; } }

10. doubleTree() Solution (C/C++)


/* For each node in a binary search tree, create a new duplicate node, and insert the duplicate as the left child of the original node. The resulting tree should still be a binary search tree. So the tree... 2 / \
http://cslibrary.stanford.edu/110/ BinaryTrees.html

Binary Trees

Page: 15

Is changed to... 2 / \ 2 3 / / 1 3 / 1 */ void doubleTree(struct node* node) { struct node* oldLeft; if (node==NULL) return; // do the subtrees doubleTree(node->left); doubleTree(node->right); // duplicate this node to its left oldLeft = node->left; node->left = newNode(node->data); node->left->left = oldLeft; }

11. sameTree() Solution (C/C++)


/* Given two trees, return true if they are structurally identical. */ int sameTree(struct node* a, struct node* b) { // 1. both empty -> true if (a==NULL && b==NULL) return(true); // 2. both non-empty -> compare them else if (a!=NULL && b!=NULL) { return( a->data == b->data && sameTree(a->left, b->left) && sameTree(a->right, b->right) ); } // 3. one empty, one not -> false else return(false); }

12. countTrees() Solution (C/C++)


/* For the key values 1...numKeys, how many structurally unique
http://cslibrary.stanford.edu/110/ BinaryTrees.html

Binary Trees

Page: 16

binary search trees are possible that store those keys. Strategy: consider that each value could be the root. Recursively find the size of the left and right subtrees. */ int countTrees(int numKeys) { if (numKeys <=1) { return(1); } else { // there will be one value at the root, with whatever remains // on the left and right each forming their own subtrees. // Iterate through all the values that could be the root... int sum = 0; int left, right, root; for (root=1; root<=numKeys; root++) { left = countTrees(root - 1); right = countTrees(numKeys - root); // number of possible trees with this root == left*right sum += left*right; } return(sum); } }

13. isBST1() Solution (C/C++)


/* Returns true if a binary tree is a binary search tree. */ int isBST(struct node* node) { if (node==NULL) return(true); // false if the min of the left is > than us if (node->left!=NULL && minValue(node->left) > node->data) return(false); // false if the max of the right is <= than us if (node->right!=NULL && maxValue(node->right) <= node->data) return(false); // false if, recursively, the left or right is not a BST if (!isBST(node->left) || !isBST(node->right)) return(false); // passing all that, it's a BST return(true); }

http://cslibrary.stanford.edu/110/ BinaryTrees.html

Binary Trees

Page: 17

14. isBST2() Solution (C/C++)


/* Returns true if the given tree is a binary search tree (efficient version). */ int isBST2(struct node* node) { return(isBSTUtil(node, INT_MIN, INT_MAX)); } /* Returns true if the given tree is a BST and its values are >= min and <= max. */ int isBSTUtil(struct node* node, int min, int max) { if (node==NULL) return(true); // false if this node violates the min/max constraint if (node->data<min || node->data>max) return(false); // otherwise check the subtrees recursively, // tightening the min or max constraint return isBSTUtil(node->left, min, node->data) && isBSTUtil(node->right, node->data+1, max) ); }

15. TreeList Solution (C/C++)


The solution code in C and Java to the great Tree-List recursion problem is in CSLibrary #109 http://cslibrary.stanford.edu/109/

Section 4 -- Java Binary Trees and Solutions


In Java, the key points in the recursion are exactly the same as in C or C++. In fact, I created the Java solutions by just copying the C solutions, and then making the syntactic changes. The recursion is the same, however the outer structure is slightly different. In Java, we will have a BinaryTree object that contains a single root pointer. The root pointer points to an internal Node class that behaves just like the node struct in the C/C++ version. The Node class is private -- it is used only for internal storage inside the BinaryTree and is not exposed to clients. With this OOP structure, almost every operation has two methods: a one-line method on the BinaryTree that starts the computation, and a recursive method that works on the Node objects. For the lookup() operation, there is a BinaryTree.lookup() method that the client uses to start a lookup operation. Internal to the BinaryTree class, there is a private recursive lookup(Node) method that implements the recursion down the Node structure. This second, private recursive method is basically the same as the recursive C/C++ functions above -- it takes a Node argument and uses recursion to iterate over the pointer structure.

Java Binary Tree Structure


To get started, here are the basic definitions for the Java BinaryTree class, and the lookup() and insert() methods as examples...
http://cslibrary.stanford.edu/110/ BinaryTrees.html

Binary Trees

Page: 18

// BinaryTree.java public class BinaryTree { // Root node pointer. Will be null for an empty tree. private Node root;

/* --Node-The binary tree is built using this nested node class. Each node stores one data element, and has left and right sub-tree pointer which may be null. The node is a "dumb" nested class -- we just use it for storage; it does not have any methods. */ private static class Node { Node left; Node right; int data; Node(int newData) { left = null; right = null; data = newData; } } /** Creates an empty binary tree -- a null root pointer. */ public void BinaryTree() { root = null; }

/** Returns true if the given target is in the binary tree. Uses a recursive helper. */ public boolean lookup(int data) { return(lookup(root, data)); }

/** Recursive lookup -- given a node, recur down searching for the given data. */ private boolean lookup(Node node, int data) { if (node==null) { return(false); } if (data==node.data) { return(true); } else if (data<node.data) {
http://cslibrary.stanford.edu/110/ BinaryTrees.html

Binary Trees

Page: 19

return(lookup(node.left, data)); } else { return(lookup(node.right, data)); } }

/** Inserts the given data into the binary tree. Uses a recursive helper. */ public void insert(int data) { root = insert(root, data); }

/** Recursive insert -- given a node pointer, recur down and insert the given data into the tree. Returns the new node pointer (the standard way to communicate a changed pointer back to the caller). */ private Node insert(Node node, int data) { if (node==null) { node = new Node(data); } else { if (data <= node.data) { node.left = insert(node.left, data); } else { node.right = insert(node.right, data); } } return(node); // in any case, return the new pointer to the caller }

OOP Style vs. Recursive Style


From the client point of view, the BinaryTree class demonstrates good OOP style -- it encapsulates the binary tree state, and the client sends messages like lookup() and insert() to operate on that state. Internally, the Node class and the recursive methods do not demonstrate OOP style. The recursive methods like insert(Node) and lookup (Node, int) basically look like recursive functions in any language. In particular, they do not operate against a "receiver" in any special way. Instead, the recursive methods operate on the arguments that are passed in which is the classical way to write recursion. My sense is that the OOP style and the recursive style do not be combined nicely for binary trees, so I have left them separate. Merging the two styles would be especially awkward for the "empty" tree (null) case, since you can't send a message to the null pointer. It's possible to get around that by having a special object to represent the null tree, but that seems like a distraction to me. I prefer to keep the recursive methods simple, and use different examples to teach OOP.

Java Solutions
Here are the Java solutions to the 14 binary tree problems. Most of the solutions use two methods:a one-line OOP
http://cslibrary.stanford.edu/110/ BinaryTrees.html

Binary Trees

Page: 20

method that starts the computation, and a recursive method that does the real operation. Make an attempt to solve each problem before looking at the solution -- it's the best way to learn.

1. Build123() Solution (Java)


/** Build */ public root Node Node 123 using three pointer variables. void build123a() { = new Node(2); lChild = new Node(1); rChild = new Node(3);

root.left = lChild; root.right= rChild; } /** Build 123 using only one pointer variable. */ public void build123b() { root = new Node(2); root.left = new Node(1); root.right = new Node(3); }

/** Build 123 by calling insert() three times. Note that the '2' must be inserted first. */ public void build123c() { root = null; root = insert(root, 2); root = insert(root, 1); root = insert(root, 3); }

2. size() Solution (Java)


/** Returns the number of nodes in the tree. Uses a recursive helper that recurs down the tree and counts the nodes. */ public int size() { return(size(root)); } private int size(Node node) { if (node == null) return(0); else { return(size(node.left) + 1 + size(node.right)); } }
http://cslibrary.stanford.edu/110/ BinaryTrees.html

Binary Trees

Page: 21

3. maxDepth() Solution (Java)


/** Returns the max root-to-leaf depth of the tree. Uses a recursive helper that recurs down to find the max depth. */ public int maxDepth() { return(maxDepth(root)); } private int maxDepth(Node node) { if (node==null) { return(0); } else { int lDepth = maxDepth(node.left); int rDepth = maxDepth(node.right); // use the larger + 1 return(Math.max(lDepth, rDepth) + 1); } }

4. minValue() Solution (Java)


/** Returns the min value in a non-empty binary search tree. Uses a helper method that iterates to the left to find the min value. */ public int minValue() { return( minValue(root) ); }

/** Finds the min value in a non-empty binary search tree. */ private int minValue(Node node) { Node current = node; while (current.left != null) { current = current.left; } return(current.data); }

5. printTree() Solution (Java)


/** Prints the node values in the "inorder" order. Uses a recursive helper to do the traversal.
http://cslibrary.stanford.edu/110/ BinaryTrees.html

Binary Trees

Page: 22

*/ public void printTree() { printTree(root); System.out.println(); } private void printTree(Node node) { if (node == null) return; // left, node itself, right printTree(node.left); System.out.print(node.data + " printTree(node.right); }

");

6. printPostorder() Solution (Java)


/** Prints the node values in the "postorder" order. Uses a recursive helper to do the traversal. */ public void printPostorder() { printPostorder(root); System.out.println(); } public void printPostorder(Node node) { if (node == null) return; // first recur on both subtrees printPostorder(node.left); printPostorder(node.right); // then deal with the node System.out.print(node.data + " }

");

7. hasPathSum() Solution (Java)


/** Given a tree and a sum, returns true if there is a path from the root down to a leaf, such that adding up all the values along the path equals the given sum. Strategy: subtract the node value from the sum when recurring down, and check to see if the sum is 0 when you run out of tree. */ public boolean hasPathSum(int sum) { return( hasPathSum(root, sum) ); } boolean hasPathSum(Node node, int sum) { // return true if we run out of tree and sum==0 if (node == null) {
http://cslibrary.stanford.edu/110/ BinaryTrees.html

Binary Trees

Page: 23

return(sum == 0); } else { // otherwise check both subtrees int subSum = sum - node.data; return(hasPathSum(node.left, subSum) || hasPathSum(node.right, subSum)); } }

8. printPaths() Solution (Java)


/** Given a binary tree, prints out all of its root-to-leaf paths, one per line. Uses a recursive helper to do the work. */ public void printPaths() { int[] path = new int[1000]; printPaths(root, path, 0); } /** Recursive printPaths helper -- given a node, and an array containing the path from the root node up to but not including this node, prints out all the root-leaf paths. */ private void printPaths(Node node, int[] path, int pathLen) { if (node==null) return; // append this node to the path array path[pathLen] = node.data; pathLen++; // it's a leaf, so print the path that led to here if (node.left==null && node.right==null) { printArray(path, pathLen); } else { // otherwise try both subtrees printPaths(node.left, path, pathLen); printPaths(node.right, path, pathLen); } } /** Utility that prints ints from an array on one line. */ private void printArray(int[] ints, int len) { int i; for (i=0; i<len; i++) { System.out.print(ints[i] + " "); } System.out.println(); }

http://cslibrary.stanford.edu/110/ BinaryTrees.html

Binary Trees

Page: 24

9. mirror() Solution (Java)


/** Changes the tree into its mirror image. So the tree... 4 / \ 2 5 / \ 1 3 is changed to... 4 / \ 5 2 / \ 3 1 Uses a recursive helper that recurs over the tree, swapping the left/right pointers. */ public void mirror() { mirror(root); } private void mirror(Node node) { if (node != null) { // do the sub-trees mirror(node.left); mirror(node.right); // swap the left/right pointers Node temp = node.left; node.left = node.right; node.right = temp; } }

10. doubleTree() Solution (Java)


/** Changes the tree by inserting a duplicate node on each nodes's .left.

So the tree... 2 / \ 1 3 Is changed to... 2


http://cslibrary.stanford.edu/110/ BinaryTrees.html

Binary Trees

Page: 25

/ \ 2 / 1 / 1 Uses a recursive helper to recur over the tree and insert the duplicates. */ public void doubleTree() { doubleTree(root); } private void doubleTree(Node node) { Node oldLeft; if (node == null) return; // do the subtrees doubleTree(node.left); doubleTree(node.right); // duplicate this node to its left oldLeft = node.left; node.left = new Node(node.data); node.left.left = oldLeft; } 3 / 3

11. sameTree() Solution (Java)


/* Compares the receiver to another tree to see if they are structurally identical. */ public boolean sameTree(BinaryTree other) { return( sameTree(root, other.root) ); } /** Recursive helper -- recurs down two trees in parallel, checking to see if they are identical. */ boolean sameTree(Node a, Node b) { // 1. both empty -> true if (a==null && b==null) return(true); // 2. both non-empty -> compare them else if (a!=null && b!=null) { return( a.data == b.data && sameTree(a.left, b.left) && sameTree(a.right, b.right) ); }
http://cslibrary.stanford.edu/110/ BinaryTrees.html

Binary Trees

Page: 26

// 3. one empty, one not -> false else return(false); }

12. countTrees() Solution (Java)


/** For the key values 1...numKeys, how many structurally unique binary search trees are possible that store those keys? Strategy: consider that each value could be the root. Recursively find the size of the left and right subtrees. */ public static int countTrees(int numKeys) { if (numKeys <=1) { return(1); } else { // there will be one value at the root, with whatever remains // on the left and right each forming their own subtrees. // Iterate through all the values that could be the root... int sum = 0; int left, right, root; for (root=1; root<=numKeys; root++) { left = countTrees(root-1); right = countTrees(numKeys - root); // number of possible trees with this root == left*right sum += left*right; } return(sum); } }

13. isBST1() Solution (Java)


/** Tests if a tree meets the conditions to be a binary search tree (BST). */ public boolean isBST() { return(isBST(root)); } /** Recursive helper -- checks if a tree is a BST using minValue() and maxValue() (not efficient). */ private boolean isBST(Node node) { if (node==null) return(true); // do the subtrees contain values that do not
http://cslibrary.stanford.edu/110/ BinaryTrees.html

Binary Trees

Page: 27

// agree with the node? if (node.left!=null && maxValue(node.left) > node.data) return(false); if (node.right!=null && minValue(node.right) <= node.data) return(false); // check that the subtrees themselves are ok return( isBST(node.left) && isBST(node.right) ); }

14. isBST2() Solution (Java)


/** Tests if a tree meets the conditions to be a binary search tree (BST). Uses the efficient recursive helper. */ public boolean isBST2() { return( isBST2(root, Integer.MIN_VALUE, Integer.MAX_VALUE) ); } /** Efficient BST helper -- Given a node, and min and max values, recurs down the tree to verify that it is a BST, and that all its nodes are within the min..max range. Works in O(n) time -visits each node only once. */ private boolean isBST2(Node node, int min, int max) { if (node==null) { return(true); } else { // left should be in range min...node.data boolean leftOk = isBST2(node.left, min, node.data); // if the left is not ok, bail out if (!leftOk) return(false); // right should be in range node.data+1..max boolean rightOk = isBST2(node.right, node.data+1, max); return(rightOk); } }

http://cslibrary.stanford.edu/110/ BinaryTrees.html

Tree List Recursion Problem

Page: 1

The Great Tree-List Recursion Problem


by Nick Parlante nick.parlante@cs.stanford.edu Copyright 2000, Nick Parlante

This article presents one of the neatest recursive pointer problems ever devised. This an advanced problem that uses pointers, binary trees, linked lists, and some significant recursion. This article includes the problem statement, a few explanatory diagrams, and sample solution code in Java and C. Thanks to Stuart Reges for originally showing me the problem.

Stanford CS Education Library Doc #109


This is article #109 in the Stanford CS Education Library -- http://cslibrary.stanford.edu/109/. This and other free educational materials are available at http://cslibrary.stanford.edu/. Permission is given for this article to be used, reproduced, or sold so long this paragraph and the copyright are clearly reproduced. Related articles in the library include Linked List Basics (#103), Linked List Problems (#105), and Binary Trees (#110).

Contents
1. 2. 3. 4. 5. Ordered binary tree Circular doubly linked list The Challenge Problem Statement Lessons and Solution Code

Introduction
The problem will use two data structures -- an ordered binary tree and a circular doubly linked list. Both data structures store sorted elements, but they look very different.

1. Ordered Binary Tree


In the ordered binary tree, each node contains a single data element and "small" and "large" pointers to sub-trees (sometimes the two pointers are just called "left" and "right"). Here's an ordered binary tree of the numbers 1 through 5...

http://cslibrary.stanford.edu/109/ TreeListRecursion.html

Tree List Recursion Problem

Page: 2

Figure-1 -- ordered binary tree All the nodes in the "small" sub-tree are less than or equal to the data in the parent node. All the nodes in the "large" sub-tree are greater than the parent node. So in the example above, all the nodes in the "small" sub-tree off the 4 node are less than or equal to 4, and all the nodes in "large" sub-tree are greater than 4. That pattern applies for each node in the tree. A null pointer effectively marks the end of a branch in the tree. Formally, a null pointer represents a tree with zero elements. The pointer to the topmost node in a tree is called the "root".

2. Circular Doubly Linked List


Here's a circular doubly linked list of the numbers 1 through 5...

http://cslibrary.stanford.edu/109/ TreeListRecursion.html

Tree List Recursion Problem

Page: 3

Figure-2 -- doubly linked circular list The circular doubly linked list is a standard linked list with two additional features... "Doubly linked" means that each node has two pointers -- the usual "next" pointer that points to the next node in the list and a "previous" pointer to the previous node. "Circular" means that the list does not terminate at the first and last nodes. Instead, the "next" from the last node wraps around to the first node. Likewise, the "previous" from the first node wraps around to the last node. We'll use the convention that a null pointer represents a list with zero elements. It turns out that a length-1 list looks a little silly...

Figure-3 -- a length-1 circular doubly linked list The single node in a length-1 list is both the first and last node, so its pointers point to itself. Fortunately, the length-1 case obeys the rules above so no special case is required.

The Trick -- Separated at Birth?


Here's the trick that underlies the Great Tree-List Problem: look at the nodes that make up the ordered binary tree. Now look at the nodes that make up the linked list. The nodes have the same type structure -- they each contain an element and two pointers. The only difference is that in the tree, the two pointers are labeled "small"
http://cslibrary.stanford.edu/109/ TreeListRecursion.html

Tree List Recursion Problem

Page: 4

and "large" while in the list they are labeled "previous" and "next". Ignoring the labeling, the two node types are the same.

3. The Challenge
The challenge is to take an ordered binary tree and rearrange the internal pointers to make a circular doubly linked list out of it. The "small" pointer should play the role of "previous" and the "large" pointer should play the role of "next". The list should be arranged so that the nodes are in increasing order...

Figure-4 -- original tree with list "next" arrows added This drawing shows the original tree drawn with plain black lines with the "next" pointers for the desired list structure drawn as arrows. The "previous" pointers are not shown.

Complete Drawing
http://cslibrary.stanford.edu/109/ TreeListRecursion.html

Tree List Recursion Problem

Page: 5

Figure-5 -- original tree with "next" and "previous" list arrows added This drawing shows the all of the problem state -- the original tree is drawn with plain black lines and the desired next/previous pointers are added in as arrows. Notice that starting with the head pointer, the structure of next/previous pointers defines a list of the numbers 1 through 5 with exactly the same structure as the list in figure-2. Although the nodes appear to have different spatial arrangement between the two drawings, that's just an artifact of the drawing. The structure defined by the the pointers is what matters.

4. Problem Statement
Here's the formal problem statement: Write a recursive function treeToList(Node root) that takes an ordered binary tree and rearranges the internal pointers to make a circular doubly linked list out of the tree nodes. The "previous" pointers should be stored in the "small" field and the "next" pointers should be stored in the "large" field. The list should be arranged so that the nodes are in increasing order. Return the head pointer to the new list. The operation can be done in O(n) time -- essentially operating on each node once. Basically take figure-1 as input and rearrange the pointers to make figure-2. Try the problem directly, or see the hints below.

Hints
http://cslibrary.stanford.edu/109/ TreeListRecursion.html

Tree List Recursion Problem

Page: 6

Hint #1
The recursion is key. Trust that the recursive call on each sub-tree works and concentrate on assembling the outputs of the recursive calls to build the result. It's too complex to delve into how each recursive call is going to work -trust that it did work and assemble the answer from there.

Hint #2
The recursion will go down the tree, recursively changing the small and large sub-trees into lists, and then append those lists together with the parent node to make larger lists. Separate out a utility function append(Node a, Node b) that takes two circular doubly linked lists and appends them together to make one list which is returned. Writing a separate utility function helps move some of the complexity out of the recursive function.

5. Lessons and Solution Code


The solution code is given below in Java and C. The most important method is treeToList() and the helper methods join() and append(). Here are the lessons I see in the two solutions... Trust that the recursive calls return correct output when fed correct input -- make the leap of faith. Look at the partial results that the recursive calls give you, and construct the full result from them. If you try to step into the recursive calls to think how they are working, you'll go crazy. Decomposing out well defined helper functions is a good idea. Writing the list-append code separately helps you concentrate on the recursion which is complex enough on its own.

Java Solution Code


// TreeList.java /* Demonstrates the greatest recursive pointer problem ever -recursively changing an ordered binary tree into a circular doubly linked list. See http://cslibrary.stanford.edu/109/ This code is not especially OOP. This code is free for any purpose. Feb 22, 2000 Nick Parlante nick.parlante@cs.stanford.edu */

/* This is the simple Node class from which the tree and list are built. This does not have any methods -- it's just used as dumb storage by TreeList. The code below tries to be clear where it treats a Node pointer as a tree vs. where it is treated as a list. */ class Node { int data; Node small; Node large; public Node(int data) {
http://cslibrary.stanford.edu/109/ TreeListRecursion.html

Tree List Recursion Problem

Page: 7

this.data = data; small = null; large = null; } }

/* TreeList main methods: -join() -- utility to connect two list nodes -append() -- utility to append two lists -treeToList() -- the core recursive function -treeInsert() -- used to build the tree */ class TreeList { /* helper function -- given two list nodes, join them together so the second immediately follow the first. Sets the .next of the first and the .previous of the second. */ public static void join(Node a, Node b) { a.large = b; b.small = a; }

/* helper function -- given two circular doubly linked lists, append them and return the new list. */ public static Node append(Node a, Node b) { // if either is null, return the other if (a==null) return(b); if (b==null) return(a); // find the last node in each using the .previous pointer Node aLast = a.small; Node bLast = b.small; // join the two together to make it connected and circular join(aLast, b); join(bLast, a); return(a); }

/* --Recursion-Given an ordered binary tree, recursively change it into a circular doubly linked list which is returned. */ public static Node treeToList(Node root) { // base case: empty tree -> empty list if (root==null) return(null); // Recursively do the subtrees (leap of faith!) Node aList = treeToList(root.small); Node bList = treeToList(root.large); // Make the single root node into a list length-1 // in preparation for the appending
http://cslibrary.stanford.edu/109/ TreeListRecursion.html

Tree List Recursion Problem

Page: 8

root.small = root; root.large = root; // At this point we have three lists, and it's // just a matter of appending them together // in the right order (aList, root, bList) aList = append(aList, root); aList = append(aList, bList); return(aList); }

/* Given a non-empty tree, insert a new node in the proper place. The tree must be non-empty because Java's lack of reference variables makes that case and this method messier than they should be. */ public static void treeInsert(Node root, int newData) { if (newData<=root.data) { if (root.small!=null) treeInsert(root.small, newData); else root.small = new Node(newData); } else { if (root.large!=null) treeInsert(root.large, newData); else root.large = new Node(newData); } }

// Do an inorder traversal to print a tree // Does not print the ending "\n" public static void printTree(Node root) { if (root==null) return; printTree(root.small); System.out.print(Integer.toString(root.data) + " "); printTree(root.large); }

// Do a traversal of the list and print it out public static void printList(Node head) { Node current = head; while (current != null) { System.out.print(Integer.toString(current.data) + " "); current = current.large; if (current == head) break; } System.out.println(); }

// Demonstrate tree->list with the list 1..5 public static void main(String[] args) { // first build the tree shown in the problem document // http://cslibrary.stanford.edu/109/ Node root = new Node(4); treeInsert(root, 2);
http://cslibrary.stanford.edu/109/ TreeListRecursion.html

Tree List Recursion Problem

Page: 9

treeInsert(root, 1); treeInsert(root, 3); treeInsert(root, 5); System.out.println("tree:"); printTree(root); // 1 2 3 4 5 System.out.println(); System.out.println("list:"); Node head = treeToList(root); printList(head); // 1 2 3 4 5 } }

yay!

C Solution Code
/* TreeList.c C code version of the great Tree-List recursion problem. See http://cslibrary.stanford.edu/109/ for the full discussion and the Java solution. This code is free for any purpose. Feb 22, 2000 Nick Parlante nick.parlante@cs.stanford.edu */

#include <stdio.h> #include <stddef.h> #include <stdlib.h> /* The node type from which both the tree and list are built */ struct node { int data; struct node* small; struct node* large; }; typedef struct node* Node;

/* helper function -- given two list nodes, join them together so the second immediately follow the first. Sets the .next of the first and the .previous of the second. */ static void join(Node a, Node b) { a->large = b; b->small = a; }

/* helper function -- given two circular doubly linked lists, append them and return the new list. */ static Node append(Node a, Node b) {
http://cslibrary.stanford.edu/109/ TreeListRecursion.html

Tree List Recursion Problem

Page: 10

Node aLast, bLast; if (a==NULL) return(b); if (b==NULL) return(a); aLast = a->small; bLast = b->small; join(aLast, b); join(bLast, a); return(a); }

/* --Recursion-Given an ordered binary tree, recursively change it into a circular doubly linked list which is returned. */ static Node treeToList(Node root) { Node aList, bList; if (root==NULL) return(NULL); /* recursively solve subtrees -- leap of faith! */ aList = treeToList(root->small); bList = treeToList(root->large); /* Make a length-1 list ouf of the root */ root->small = root; root->large = root; /* Append everything together in sorted order */ aList = append(aList, root); aList = append(aList, bList); return(aList);

/* Create a new node */ static Node newNode(int data) { Node node = (Node) malloc(sizeof(struct node)); node->data = data; node->small = NULL; node->large = NULL; return(node); }

/* Add a new node into a tree */ static void treeInsert(Node* rootRef, int data) { Node root = *rootRef; if (root == NULL) *rootRef = newNode(data); else { if (data <= root->data) treeInsert(&(root->small), data); else treeInsert(&(root->large), data); } }
http://cslibrary.stanford.edu/109/ TreeListRecursion.html

Tree List Recursion Problem

Page: 11

static void printList(Node head) { Node current = head; while(current != NULL) { printf("%d ", current->data); current = current->large; if (current == head) break; } printf("\n"); }

/* Demo that the code works */ int main() { Node root = NULL; Node head; treeInsert(&root, treeInsert(&root, treeInsert(&root, treeInsert(&root, treeInsert(&root, 4); 2); 1); 3); 5);

head = treeToList(root); printList(head); return(0); } /* prints: 1 2 3 4 5 */

http://cslibrary.stanford.edu/109/ TreeListRecursion.html

First Job. Dream Job. Freshersworld.com


1.The Java interpreter is used for the execution of the source code. True False Ans: a. 2) On successful compilation a file with the class extension is created. a) True b) False Ans: a. 3) The Java source code can be created in a Notepad editor. a) True b) False Ans: a. 4) The Java Program is enclosed in a class definition. a) True b) False Ans: a. 5) What declarations are required for every Java application? Ans: A class and the main( ) method declarations. 6) What are the two parts in executing a Java program and their purposes? Ans: Two parts in executing a Java program are: Java Compiler and Java Interpreter. The Java Compiler is used for compilation and the Java Interpreter is used for execution of the application. 7) What are the three OOPs principles and define them? Ans : Encapsulation, Inheritance and Polymorphism are the three OOPs Principles. Encapsulation: Is the Mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse. Inheritance: Is the process by which one object acquires the properties of another object. Polymorphism: Is a feature that allows one interface to be used for a general class of actions.

8) What is a compilation unit? Ans : Java source code file. 9) What output is displayed as the result of executing the following statement? System.out.println("// Looks like a comment."); // Looks like a comment The statement results in a compilation error Looks like a comment No output is displayed Ans : a. 10) In order for a source code file, containing the public class Test, to successfully compile, which of the following must be true? It must have a package statement It must be named Test.java It must import java.lang It must declare a public class named Test Ans : b 11) What are identifiers and what is naming convention? Ans : Identifiers are used for class names, method names and variable names. An identifier may be any descriptive sequence of upper case & lower case letters,numbers or underscore or dollar sign and must not begin with numbers. 12) What is the return type of programs main( ) method?
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com


Ans : void 13) What is the argument type of programs main( ) method? Ans : string array. 14) Which characters are as first characters of an identifier? Ans : A Z, a z, _ ,$ 15) What are different comments? Ans : 1) // -- single line comment 2) /* -*/ multiple line comment 3) /** -*/ documentation 16) What is the difference between constructor method and method? Ans : Constructor will be automatically invoked when an object is created. Whereas method has to be call explicitly. 17) What is the use of bin and lib in JDK? Ans : Bin contains all tools such as javac, applet viewer, awt tool etc., whereas Lib contains all packages and variables.

Data types,variables and Arrays 1) What is meant by variable? Ans: Variables are locations in memory that can hold values. Before assigning any value to a variable, it must be declared. 2) What are the kinds of variables in Java? What are their uses? Ans: Java has three kinds of variables namely, the instance variable, the local variable and the class variable. Local variables are used inside blocks as counters or in methods as temporary variables and are used to store information needed by a single method. Instance variables are used to define attributes or the state of a particular object and are used to store information needed by multiple methods in the objects. Class variables are global to a class and to all the instances of the class and are useful for communicating between different objects of all the same class or keeping track of global states. 3) How are the variables declared? Ans: Variables can be declared anywhere in the method definition and can be initialized during their declaration.They are commonly declared before usage at the beginning of the definition. Variables with the same data type can be declared together. Local variables must be given a value before usage. 4) What are variable types? Ans: Variable types can be any data type that java supports, which includes the eight primitive data types, the name of a class or interface and an array. 5) How do you assign values to variables? Ans: Values are assigned to variables using the assignment operator =. 6) What is a literal? How many types of literals are there? Ans: A literal represents a value of a certain type where the type describes how that value behaves. There are different types of literals namely number literals, character literals, boolean literals, string literals,etc. 7) What is an array? Ans: An array is an object that stores a list of items. 8) How do you declare an array? Ans: Array variable indicates the type of object that the array holds. Ex: int arr[]; 9) Java supports multidimensional arrays. a)True b)False Ans: a. 10) An array of arrays can be created.
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com


a)True b)False Ans: a. 11) What is a string? Ans: A combination of characters is called as string. 12) Strings are instances of the class String. a)True b)False Ans: a. 13) When a string literal is used in the program, Java automatically creates instances of the string class. a)True b)False Ans: a. 14) Which operator is to create and concatenate string? Ans: Addition operator(+). 15) Which of the following declare an array of string objects? String[ ] s; String [ ]s: String[ s]: String s[ ]: Ans : a, b and d 16) What is the value of a[3] as the result of the following array declaration? 1 2 3 4 Ans : d 17) Which of the following are primitive types? byte String integer Float Ans : a. 18) What is the range of the char type? 0 to 216 0 to 215 0 to 216-1 0 to 215-1 Ans. d 19) What are primitive data types? Ans : byte, short, int, long float, double boolean char 20) What are default values of different primitive types? Ans : int - 0 short - 0 byte - 0 long - 0 l float - 0.0 f double - 0.0 d boolean - false char - null 21) Converting of primitive types to objects can be explicitly. a)True b)False
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com


Ans: b. 22) How do we change the values of the elements of the array? Ans : The array subscript expression can be used to change the values of the elements of the array. 23) What is final varaible? Ans : If a variable is declared as final variable, then you can not change its value. It becomes constant. 24) What is static variable? Ans : Static variables are shared by all instances of a class.

Operators 1) What are operators and what are the various types of operators available in Java? Ans: Operators are special symbols used in expressions. The following are the types of operators: Arithmetic operators, Assignment operators, Increment & Decrement operators, Logical operators, Biwise operators, Comparison/Relational operators and Conditional operators 2) The ++ operator is used for incrementing and the -- operator is used for decrementing. a)True b)False Ans: a. 3) Comparison/Logical operators are used for testing and magnitude. a)True b)False Ans: a. 4) Character literals are stored as unicode characters. a)True b)False Ans: a. 5) What are the Logical operators? Ans: OR(|), AND(&), XOR(^) AND NOT(~). 6) What is the % operator? Ans : % operator is the modulo operator or reminder operator. It returns the reminder of dividing the first operand by second operand. 7) What is the value of 111 % 13? 3 5 7 9 Ans : c. 8) Is &&= a valid operator? Ans : No. 9) Can a double value be cast to a byte? Ans : Yes 10) Can a byte object be cast to a double value ? Ans : No. An object cannot be cast to a primitive value. 11) What are order of precedence and associativity? Ans : Order of precedence the order in which operators are evaluated in expressions. Associativity determines whether an expression is evaluated left-right or right-left. 12) Which Java operator is right associativity? Ans : = operator.
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com


13) What is the difference between prefix and postfix of -- and ++ operators? Ans : The prefix form returns the increment or decrement operation and returns the value of the increment or decrement operation. The postfix form returns the current value of all of the expression and then performs the increment or decrement operation on that value. 14) What is the result of expression 5.45 + "3,2"? The double value 8.6 The string ""8.6" The long value 8. The String "5.453.2" Ans : d 15) What are the values of x and y ? x = 5; y = ++x; Ans : x = 6; y = 6 16) What are the values of x and z? x = 5; z = x++; Ans : x = 6; z = 5

Control Statements 1) What are the programming constructs? Ans: a) Sequential b) Selection -- if and switch statements c) Iteration -- for loop, while loop and do-while loop 2) class conditional { public static void main(String args[]) { int i = 20; int j = 55; int z = 0; z = i < j ? i : j; // ternary operator System.out.println("The value assigned is " + z); } } What is output of the above program? Ans: The value assigned is 20 3) The switch statement does not require a break. a)True b)False Ans: b. 4) The conditional operator is otherwise known as the ternary operator. a)True b)False Ans: a. 5) The while loop repeats a set of code while the condition is false. a)True b)False Ans: b. 6) The do-while loop repeats a set of code atleast once before the condition is tested. a)True b)False Ans: a. 7) What are difference between break and continue?
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com


Ans: The break keyword halts the execution of the current loop and forces control out of the loop. The continue is similar to break, except that instead of halting the execution of the loop, it starts the next iteration. 8) The for loop repeats a set of statements a certain number of times until a condition is matched. a)True b)False Ans: a. 9) Can a for statement loop indefintely? Ans : Yes. 10) What is the difference between while statement and a do statement/ Ans : A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.

Introduction to Classes and Methods 1) Which is used to get the value of the instance variables? Ans: Dot notation. 2) The new operator creates a single instance named class and returns a reference to that object. a)True b)False Ans: a. 3) A class is a template for multiple objects with similar features. a)True b)False Ans: a. 4) What is mean by garbage collection? Ans: When an object is no longer referred to by any variable, Java automatically reclaims memory used by that object. This is known as garbage collection. 5) What are methods and how are they defined? Ans: Methods are functions that operate on instances of classes in which they are defined.Objects can communicate with each other using methods and can call methods in other classes. Method definition has four parts. They are name of the method, type of object or primitive type the method returns, a list of parameters and the body of the method. A method's signature is a combination of the first three parts mentioned above. 6) What is calling method? Ans: Calling methods are similar to calling or referring to an instance variable. These methods are accessed using dot notation. Ex: obj.methodname(param1,param2) 7) Which method is used to determine the class of an object? Ans: getClass( ) method can be used to find out what class the belongs to. This class is defined in the object class and is available to all objects. 8) All the classes in java.lang package are automatically imported when a program is compiled. a)True b)False Ans: a. 9) How can class be imported to a program? Ans: To import a class, the import keyword should be used as shown.; import classname; 10) How can class be imported from a package to a program? Ans: import java . packagename . classname (or) import java.package name.*; 11) What is a constructor?
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com


Ans: A constructor is a special kind of method that determines how an object is initialized when created. 12) Which keyword is used to create an instance of a class? Ans: new. 13) Which method is used to garbage collect an object? Ans: finalize (). 14) Constructors can be overloaded like regular methods. a)True b)False Ans: a. 15) What is casting? Ans: Casting is bused to convert the value of one type to another.

16) Casting between primitive types allows conversion of one primitive type to another. a)True b)False Ans: a. 17) Casting occurs commonly between numeric types. a)True b)False Ans: a. 18) Boolean values can be cast into any other primitive type. a)True b)False Ans: b. 19) Casting does not affect the original object or value. a)True b)False Ans: a. 20) Which cast must be used to convert a larger value into a smaller one? Ans: Explicit cast. 21) Which cast must be used to cast an object to another class? Ans: Specific cast. 22) Which of the following features are common to both Java & C++? A.The class declaration b.The access modifiers c.The encapsulation of data & methods with in objects d.The use of pointers Ans: a,b,c. 23) Which of the following statements accurately describe the use of access modifiers within a class definition? a.They can be applied to both data & methods b.They must precede a class's data variables or methods c.They can follow a class's data variables or methods d.They can appear in any order e.They must be applied to data variables first and then to methods Ans: a,b,d. 24) Suppose a given instance variable has been declared private. Can this instance variable be manipulated by methods out side its class? a.yes b.no Ans: b. 25) Which of the following statements can be used to describe a public method? a.It is accessible to all other classes in the hierarchy
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com


b.It is accessablde only to subclasses of its parent class c.It represents the public interface of its class d.The only way to gain access to this method is by calling one of the public class methods Ans: a,c. 26) Which of the following types of class members can be part of the internal part of a class? a.Public instance variables b.Private instance variables c.Public methods d.Private methods Ans: b,d. 27) You would use the ____ operator to create a single instance of a named class. a.new b.dot Ans: a. 28) Which of the following statements correctly describes the relation between an object and the instance variable it stores? a.Each new object has its own distinctive set of instance variables b.Each object has a copy of the instance variables of its class c.the instance variable of each object are seperate from the variables of other objects d.The instance variables of each object are stored together with the variables of other objects Ans: a,b,c. 29) If no input parameters are specified in a method declaration then the declaration will include __. a.an empty set of parantheses b.the term void Ans: a. 30) What are the functions of the dot(.) operator? a.It enables you to access instance variables of any objects within a class b.It enables you to store values in instance variables of an object c.It is used to call object methods d.It is to create a new object Ans: a,b,c. 31) Which of the following can be referenced by this variable? a.The instance variables of a class only b.The methods of a class only c.The instance variables and methods of a class Ans: c. 32) The this reference is used in conjunction with ___methods. a.static b.non-static Ans: b. 33) Which of the following operators are used in conjunction with the this and super references? a.The new operator b.The instanceof operator c.The dot operator Ans: c. 34) A constructor is automatically called when an object is instantiated a. true b. false Ans: a. 35) When may a constructor be called without specifying arguments? a. When the default constructor is not called b. When the name of the constructor differs from that of the class c. When there are no constructors for the class Ans: c. 36) Each class in java can have a finalizer method
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com


a. true b.false Ans: a. 37) When an object is referenced, does this mean that it has been identified by the finalizer method for garbage collection? a.yes b.no Ans: b. 38) Because finalize () belongs to the java.lang.Object class, it is present in all ___. a.objects b.classes c.methods Ans: b. 39) Identify the true statements about finalization. a.A class may have only one finalize method b.Finalizers are mostly used with simple classes c.Finalizer overloading is not allowed Ans: a,c. 40) When you write finalize() method for your class, you are overriding a finalizer inherited from a super class. a.true b.false Ans: a. 41) Java memory management mechanism garbage collects objects which are no longer referenced a true b.false Ans: a. 42) are objects referenced by a variable candidates for garbage collection when the variable goes out of scope? a yes b. no Ans: a. 43) Java's garbage collector runs as a ___ priority thread waiting for __priority threads to relinquish the processor. a.high b.low Ans: a,b. 44) The garbage collector will run immediately when the system is out of memory a.true b.false Ans: a. 45) You can explicitly drop a object reference by setting the value of a variable whose data type is a reference type to ___ Ans: null 46) When might your program wish to run the garbage collecter? a. before it enters a compute-intense section of code b. before it enters a memory-intense section of code c. before objects are finalized d. when it knows there will be some idle time Ans: a,b,d 47) For externalizable objects the class is solely responsible for the external format of its contents a.true b.false Ans: a 48) When an object is stored, are all of the objects that are reachable from that object stored as well? a.true
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com


b.false Ans: a 49) The default__ of objects protects private and trancient data, and supports the __ of the classes a.evolution b.encoding Ans: b,a. 50) Which are keywords in Java? a) NULL b) sizeof c) friend d) extends e) synchronized Ans : d and e 51) When must the main class and the file name coincide? Ans :When class is declared public. 52) What are different modifiers? Ans : public, private, protected, default, static, trancient, volatile, final, abstract. 53) What are access modifiers? Ans : public, private, protected, default. 54) What is meant by "Passing by value" and " Passing by reference"? Ans : objects pass by referrence Methods - pass by value 55) Is a class a subclass of itself? Ans : A class is a subclass itself. 56) What modifiers may be used with top-level class? Ans : public, abstract, final. 57) What is an example of polymorphism? Inner class Anonymous classes Method overloading Method overriding Ans : c

Packages and interface 1) What are packages ? what is use of packages ? Ans :The package statement defines a name space in which classes are stored.If you omit the package, the classes are put into the default package. Signature... package pkg; Use: * It specifies to which package the classes defined in a file belongs to. * Package is both naming and a visibility control mechanism. 2) What is difference between importing "java.applet.Applet" and "java.applet.*;" ? Ans :"java.applet.Applet" will import only the class Applet from the package java.applet Where as "java.applet.*" will import all the classes from java.applet package. 3) What do you understand by package access specifier? Ans : public: Anything declared as public can be accessed from anywhere private: Anything declared in the private cant be seen outside of its class. default: It is visible to subclasses as well as to other classes in the same package. 4) What is interface? What is use of interface? Ans : It is similar to class which may contain methods signature only but not bodies. Methods declared in interface are abstract methods. We can implement many interfaces on a class which support the multiple inheritance. 5) Is it is necessary to implement all methods in an interface? Ans : Yes. All the methods have to be implemented. 6) Which is the default access modifier for an interface method?
Freshersworld.com Resource Center

10

First Job. Dream Job. Freshersworld.com


Ans : public. 7) Can we define a variable in an interface ?and what type it should be ? Ans : Yes we can define a variable in an interface. They are implicitly final and static. 8) What is difference between interface and an abstract class? Ans : All the methods declared inside an Interface are abstract. Where as abstract class must have at least one abstract method and others may be concrete or abstract. In Interface we need not use the keyword abstract for the methods. 9) By default, all program import the java.lang package. True/False Ans : True 10) Java compiler stores the .class files in the path specified in CLASSPATH environmental variable. True/False Ans : False 11) User-defined package can also be imported just like the standard packages. True/False Ans : True 12) When a program does not want to handle exception, the ______class is used. Ans : Throws 13) The main subclass of the Exception class is _______ class. Ans : RuntimeException 14) Only subclasses of ______class may be caught or thrown. Ans : Throwable 15) Any user-defined exception class is a subclass of the _____ class. Ans : Exception 16) The catch clause of the user-defined exception class should ______ its Base class catch clause. Ans : Exception 17) A _______ is used to separate the hierarchy of the class while declaring an Import statement. Ans : Package 18) All standard classes of Java are included within a package called _____. Ans : java.lang 19) All the classes in a package can be simultaneously imported using ____. Ans : * 20) Can you define a variable inside an Interface. If no, why? If yes, how? Ans.: YES. final and static 21) How many concrete classes can you have inside an interface? Ans.: None 22) Can you extend an interface? Ans.: Yes 23) Is it necessary to implement all the methods of an interface while implementing the interface? Ans.: No 24) If you do not implement all the methods of an interface while implementing , what specifier should you use for the class ? Ans.: abstract 25) How do you achieve multiple inheritance in Java? Ans: Using interfaces. 26) How to declare an interface example? Ans : access class classname implements interface. 27) Can you achieve multiple interface through interface? a)True b) false Ans : a.
Freshersworld.com Resource Center

11

First Job. Dream Job. Freshersworld.com


28) Can variables be declared in an interface ? If so, what are the modifiers? Ans : Yes. final and static are the modifiers can be declared in an interface. 29) What are the possible access modifiers when implementing interface methods? Ans : public. 30) Can anonymous classes be implemented an interface? Ans : Yes. 31) Interfaces cant be extended. a)True b)False Ans : b. 32) Name interfaces without a method? Ans : Serializable, Cloneble & Remote. 33) Is it possible to use few methods of an interface in a class ? If so, how? Ans : Yes. Declare the class as abstract.

Exception Handling 1) What is the difference between throw and throws ?And its application? Ans : Exceptions that are thrown by java runtime systems can be handled by Try and catch blocks. With throw exception we can handle the exceptions thrown by the program itself. If a method is capable of causing an exception that it does not handle, it must specify this behavior so the callers of the method can guard against that exception. 2) What is the difference between Exception and error in java? Ans : Exception and Error are the subclasses of the Throwable class. Exception class is used for exceptional conditions that user program should catch. With exception class we can subclass to create our own custom exception. Error defines exceptions that are not excepted to be caught by you program. Example is Stack Overflow. 3) What is Resource leak? Ans : Freeing up other resources that might have been allocated at the beginning of a method. 4)What is the finally block? Ans : Finally block will execute whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement match the exception. Any time a method is about to return to the caller from inside try/catch block, via an uncaught exception or an explicit return statement, the finally clause is also execute. 5) Can we have catch block with out try block? If so when? Ans : No. Try/Catch or Try/finally form a unit. 6) What is the difference between the following statements? Catch (Exception e), Catch (Error err), Catch (Throwable t) Ans :

7) What will happen to the Exception object after exception handling? Ans : It will go for Garbage Collector. And frees the memory. 8) How many Exceptions we can define in throws clause? Ans : We can define multiple exceptions in throws clause. Signature is.. type method-name (parameter-list) throws exception-list 9) The finally block is executed when an exception is thrown, even if no catch matches it. True/False
Freshersworld.com Resource Center

12

First Job. Dream Job. Freshersworld.com


Ans : True 10) The subclass exception should precede the base class exception when used within the catch clause. True/False Ans : True 11) Exceptions can be caught or rethrown to a calling method. True/False Ans : True 12) The statements following the throw keyword in a program are not executed. True/False Ans : True 13) The toString ( ) method in the user-defined exception class is overridden. True/False Ans : True

MULTI THREADING 1) What are the two types of multitasking? Ans : 1.process-based 2.Thread-based 2) What are the two ways to create the thread? Ans : 1.by implementing Runnable 2.by extending Thread 3) What is the signature of the constructor of a thread class? Ans : Thread(Runnable threadob,String threadName) 4) What are all the methods available in the Runnable Interface? Ans : run() 5) What is the data type for the method isAlive() and this method is available in which class? Ans : boolean, Thread 6) What are all the methods available in the Thread class? Ans : 1.isAlive() 2.join() 3.resume() 4.suspend() 5.stop() 6.start() 7.sleep() 8.destroy() 7) What are all the methods used for Inter Thread communication and what is the class in which these methods are defined? Ans :1. wait(),notify() & notifyall() 2. Object class 8) What is the mechanisam defind by java for the Resources to be used by only one Thread at a time? Ans : Synchronisation 9) What is the procedure to own the moniter by many threads? Ans : not possible
Freshersworld.com Resource Center

13

First Job. Dream Job. Freshersworld.com


10) What is the unit for 1000 in the below statement? ob.sleep(1000) Ans : long milliseconds 11) What is the data type for the parameter of the sleep() method? Ans : long 12) What are all the values for the following level? max-priority min-priority normal-priority Ans : 10,1,5 13) What is the method available for setting the priority? Ans : setPriority() 14) What is the default thread at the time of starting the program? Ans : main thread 15) The word synchronized can be used with only a method. True/ False Ans : False 16) Which priority Thread can prompt the lower primary Thread? Ans : Higher Priority 17) How many threads at a time can access a monitor? Ans : one 18) What are all the four states associated in the thread? Ans : 1. new 2. runnable 3. blocked 4. dead 19) The suspend()method is used to teriminate a thread? True /False Ans : False 20) The run() method should necessary exists in clases created as subclass of thread? True /False Ans : True 21) When two threads are waiting on each other and can't proceed the programe is said to be in a deadlock? True/False Ans : True 22) Which method waits for the thread to die ? Ans : join() method 23) Which of the following is true? 1) wait(),notify(),notifyall() are defined as final & can be called only from with in a synchronized method 2) Among wait(),notify(),notifyall() the wait() method only throws IOException 3) wait(),notify(),notifyall() & sleep() are methods of object class 1 2 3 1&2 1,2 & 3 Ans : D 24) Garbage collector thread belongs to which priority? Ans : low-priority 25) What is meant by timeslicing or time sharing? Ans : Timeslicing is the method of allocating CPU time to individual threads in a priority schedule. 26) What is meant by daemon thread? In java runtime, what is it's role? Ans : Daemon thread is a low priority thread which runs intermittently in the background doing the garbage collection operation for the java runtime system.

Freshersworld.com Resource Center

14

First Job. Dream Job. Freshersworld.com

Inheritance 1) What is the difference between superclass & subclass? Ans : A super class is a class that is inherited whereas subclass is a class that does the inheriting. 2) Which keyword is used to inherit a class? Ans : extends 3) Subclasses methods can access superclass members/ attributes at all times? True/False Ans : False 4) When can subclasses not access superclass members? Ans : When superclass is declared as private. 5) Which class does begin Java class hierarchy? Ans : Object class 6) Object class is a superclass of all other classes? True/False Ans : True 7) Java supports multiple inheritance? True/False Ans : False 8) What is inheritance? Ans : Deriving an object from an existing class. In the other words, Inheritance is the process of inheriting all the features from a class 9) What are the advantages of inheritance? Ans : Reusability of code and accessibility of variables and methods of the superclass by subclasses. 10) Which method is used to call the constructors of the superclass from the subclass? Ans : super(argument) 11) Which is used to execute any method of the superclass from the subclass? Ans : super.method-name(arguments) 12) Which methods are used to destroy the objects created by the constructor methods? Ans : finalize() 13) What are abstract classes? Ans : Abstract classes are those for which instances cant be created. 14) What must a class do to implement an interface? Ans: It must provide all of the methods in the interface and identify the interface in its implements clause. 15) Which methods in the Object class are declared as final? Ans : getClass(), notify(), notifyAll(), and wait() 16) Final methods can be overridden. True/False Ans : False 17) Declaration of methods as final results in faster execution of the program? True/False Ans: True 18) Final variables should be declared in the beginning? True/False Ans : True 19) Can we declare variable inside a method as final variables? Why? Ans : Cannot because, local variable cannot be declared as final variables. 20) Can an abstract class may be final? Ans : An abstract class may not be declared as final. 21) Does a class inherit the constructors of it's super class? Ans: A class does not inherit constructors from any of it's super classes. 22) What restrictions are placed on method overloading? Ans: Two methods may not have the same name and argument list but different return types.
Freshersworld.com Resource Center

15

First Job. Dream Job. Freshersworld.com


23) What restrictions are placed on method overriding? Ans : Overridden methods must have the same name , argument list , and return type. The overriding method may not limit the access of the method it overridees.The overriding method may not throw any exceptions that may not be thrown by the overridden method. 24) What modifiers may be used with an inner class that is a member of an outer class? Ans : a (non-local) inner class may be declared as public, protected, private, static, final or abstract. 25) How this() is used with constructors? Ans: this() is used to invoke a constructor of the same class 26) How super() used with constructors? Ans : super() is used to invoke a super class constructor 27) Which of the following statements correctly describes an interface? a)It's a concrete class b)It's a superclass c)It's a type of abstract class Ans: c 28) An interface contains __ methods a)Non-abstract b)Implemented c)unimplemented Ans:c

STRING HANDLING Which package does define String and StringBuffer classes? Ans : java.lang package. Which method can be used to obtain the length of the String? Ans : length( ) method. How do you concatenate Strings? Ans : By using " + " operator. Which method can be used to compare two strings for equality? Ans : equals( ) method. Which method can be used to perform a comparison between strings that ignores case differences? Ans : equalsIgnoreCase( ) method. What is the use of valueOf( ) method? Ans : valueOf( ) method converts data from its internal format into a human-readable form. What are the uses of toLowerCase( ) and toUpperCase( ) methods? Ans : The method toLowerCase( ) converts all the characters in a string from uppercase to lowercase. The method toUpperCase( ) converts all the characters in a string from lowercase to uppercase. Which method can be used to find out the total allocated capacity of a StrinBuffer? Ans : capacity( ) method. Which method can be used to set the length of the buffer within a StringBuffer object? Ans : setLength( ). What is the difference between String and StringBuffer? Ans : String objects are constants, whereas StringBuffer objects are not. String class supports constant strings, whereas StringBuffer class supports growable, modifiable strings. What are wrapper classes?
Freshersworld.com Resource Center

16

First Job. Dream Job. Freshersworld.com


Ans : Wrapper classes are classes that allow primitive types to be accessed as objects. Which of the following is not a wrapper class? String Integer Boolean Character Ans : a. What is the output of the following program? public class Question { public static void main(String args[]) { String s1 = "abc"; String s2 = "def"; String s3 = s1.concat(s2.toUpperCase( ) ); System.out.println(s1+s2+s3); } } abcdefabcdef abcabcDEFDEF abcdefabcDEF None of the above ANS : c. Which of the following methods are methods of the String class? delete( ) append( ) reverse( ) replace( ) Ans : d. Which of the following methods cause the String object referenced by s to be changed? s.concat( ) s.toUpperCase( ) s.replace( ) s.valueOf( ) Ans : a and b. String is a wrapper class? True False Ans : b. 17) If you run the code below, what gets printed out? String s=new String("Bicycle"); int iBegin=1; char iEnd=3; System.out.println(s.substring(iBegin,iEnd)); Bic ic c) icy d) error: no method matching substring(int,char) Ans : b. 18) Given the following declarations String s1=new String("Hello") String s2=new String("there"); String s3=new String();
Freshersworld.com Resource Center

17

First Job. Dream Job. Freshersworld.com


Which of the following are legal operations? s3=s1 + s2; s3=s1 - s2; c) s3=s1 & s2 d) s3=s1 && s2 Ans : a. 19) Which of the following statements are true? The String class is implemented as a char array, elements are addressed using the stringname[] convention b) Strings are a primitive type in Java that overloads the + operator for concatenation c) Strings are a primitive type in Java and the StringBuffer is used as the matching wrapper type d) The size of a string can be retrieved using the length property. Ans : b.

EXPLORING JAVA.LANG java.lang package is automatically imported into all programs. True False Ans : a What are the interfaces defined by java.lang? Ans : Cloneable, Comparable and Runnable. What are the constants defined by both Flaot and Double classes? Ans : MAX_VALUE, MIN_VALUE, NaN, POSITIVE_INFINITY, NEGATIVE_INFINITY and TYPE. What are the constants defined by Byte, Short, Integer and Long? Ans : MAX_VALUE, MIN_VALUE and TYPE. What are the constants defined by both Float and Double classes? Ans : MAX_RADIX, MIN_RADIX, MAX_VALUE, MIN_VALUE and TYPE. What is the purpose of the Runtime class? Ans : The purpose of the Runtime class is to provide access to the Java runtime system. What is the purpose of the System class? Ans : The purpose of the System class is to provide access to system resources. Which class is extended by all other classes? Ans : Object class is extended by all other classes. Which class can be used to obtain design information about an object? Ans : The Class class can be used to obtain information about an objects design. Which method is used to calculate the absolute value of a number? Ans : abs( ) method. What are E and PI? Ans : E is the base of the natural logarithm and PI is the mathematical value pi. Which of the following classes is used to perform basic console I/O? System SecurityManager Math
Freshersworld.com Resource Center

18

First Job. Dream Job. Freshersworld.com


Runtime Ans : a. Which of the following are true? The Class class is the superclass of the Object class. The Object class is final. The Class class can be used to load other classes. The ClassLoader class can be used to load other classes. Ans : c and d. Which of the following methods are methods of the Math class? absolute( ) log( ) cosine( ) sine( ) Ans : b. Which of the following are true about the Error and Exception classes? Both classes extend Throwable. The Error class is final and the Exception class is not. The Exception class is final and the Error is not. Both classes implement Throwable. Ans : a. Which of the following are true? The Void class extends the Class class. The Float class extends the Double class. The System class extends the Runtime class. The Integer class extends the Number class. Ans : d.

17) Which of the following will output -4.0 System.out.println(Math.floor(-4.7)); System.out.println(Math.round(-4.7)); System.out.println(Math.ceil(-4.7)); d) System.out.println(Math.Min(-4.7)); Ans : c. 18) Which of the following are valid statements a) public class MyCalc extends Math b) Math.max(s); c) Math.round(9.99,1); d) Math.mod(4,10); e) None of the above. Ans : e. 19) What will happen if you attempt to compile and run the following code? Integer ten=new Integer(10); Long nine=new Long (9); System.out.println(ten + nine); int i=1; System.out.println(i + ten); 19 followed by 20 19 followed by 11 Error: Can't convert java lang Integer d) 10 followed by 1
Freshersworld.com Resource Center

19

First Job. Dream Job. Freshersworld.com


Ans : c. INPUT / OUTPUT : EXPLORING JAVA.IO What is meant by Stream and what are the types of Streams and classes of the Streams? Ans : A Stream is an abstraction that either produces or consumes information. There are two types of Streams. They are: Byte Streams : Byte Streams provide a convenient means for handling input and output of bytes. Character Streams : Character Streams provide a convenient means for handling input and output of characters. Byte Stream classes : Byte Streams are defined by using two abstract classes. They are:InputStream and OutputStream. Character Stream classes : Character Streams are defined by using two abstract classes. They are : Reader and Writer. Which of the following statements are true? UTF characters are all 8-bits. UTF characters are all 16-bits. UTF characters are all 24-bits. Unicode characters are all 16-bits. Bytecode characters are all 16-bits. Ans : d. Which of the following statements are true? When you construct an instance of File, if you do not use the filenaming semantics of the local machine, the constructor will throw an IOException. When you construct an instance of File, if the corresponding file does not exist on the local file system, one will be created. When an instance of File is garbage collected, the corresponding file on the local file system is deleted. None of the above. Ans : a,b and c. The File class contains a method that changes the current working directory. True False Ans : b. It is possible to use the File class to list the contents of the current working directory. True False Ans : a. Readers have methods that can read and return floats and doubles. True False Ans : b. You execute the code below in an empty directory. What is the result? File f1 = new File("dirname"); File f2 = new File(f1, "filename"); A new directory called dirname is created in the current working directory. A new directory called dirname is created in the current working directory. A new file called filename is created in directory dirname. A new directory called dirname and a new file called filename are created, both in the current working directory. A new file called filename is created in the current working directory. No directory is created, and no file is created. Ans : e. What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy? Ans : The Reader/Writer class hierarchy is character-oriented and the InputStream/OutputStream class hierarchy is byte-oriented. What is an I/O filter?
Freshersworld.com Resource Center

20

First Job. Dream Job. Freshersworld.com


Ans : An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another. What is the purpose of the File class? Ans : The File class is used to create objects that provide access to the files and directories of a local file system. What interface must an object implement before it can be written to a stream as an object? Ans : An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object. What is the difference between the File and RandomAccessFile classes? Ans : The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file. What class allows you to read objects directly from a stream? Ans : The ObjectInputStream class supports the reading of objects from input streams. What value does read( ) return when it has reached the end of a file? Ans : The read( ) method returns 1 when it has reached the end of a file. What value does readLine( ) return when it has reached the end of a file? Ans : The readLine( ) method returns null when it has reached the end of a file. How many bits are used to represent Unicode, ASCII, UTF-16 and UTF-8 characters? Ans : Unicode requires 16-bits and ASCII requires 8-bits. Although the ASCII character set uses only 1-bits, it is usually represented as 8-bits. UTF-8 represents characters using 8, 16 and 18-bit patterns. UTF-16 uses 16-bit and larger bit patterns. Which of the following are true? The InputStream and OutputStream classes are byte-oriented. The ObjectInputStream and ObjectOutputStream do not support serialized object input and output. The Reader and Writer classes are character-oriented. The Reader and Writer classes are the preferred solution to serialized object output. Ans : a and c. Which of the following are true about I/O filters? Filters are supported on input, but not on output. Filters are supported by the InputStream/OutputStream class hierarchy, but not by the Reader/Writer class hierarchy. Filters read from one stream and write to another. A filter may alter data that is read from one stream and written to another. Ans : c and d. Which of the following are true? Any Unicode character is represented using 16-bits. 7-bits are needed to represent any ASCII character. UTF-8 characters are represented using only 8-bits. UTF-16 characters are represented using only 16-bits. Ans : a and b. Which of the following are true? The Serializable interface is used to identify objects that may be written to an output stream. The Externalizable interface is implemented by classes that control the way in which their objects are serialized. The Serializable interface extends the Externalizable interface. The Externalizable interface extends the Serializable interface. Ans : a, b and d. Which of the following are true about the File class? A File object can be used to change the current working directory. A File object can be used to access the files in the current directory. When a File object is created, a corresponding directory or file is created in the local file system. File objects are used to access files and directories on the local file system. File objects can be garbage collected. When a File object is garbage collected, the corresponding file or directory is deleted. Ans : b, d and e.
Freshersworld.com Resource Center

21

First Job. Dream Job. Freshersworld.com


How do you create a Reader object from an InputStream object? Use the static createReader( ) method of InputStream class. Use the static createReader( ) method of Reader class. Create an InputStreamReader object, passing the InputStream object as an argument to the InputStreamReader constructor. Create an OutputStreamReader object, passing the InputStream object as an argument to the OutputStreamReader constructor. Ans : c. Which of the following are true? Writer classes can be used to write characters to output streams using different character encodings. Writer classes can be used to write Unicode characters to output streams. Writer classes have methods that support the writing of the values of any Java primitive type to output streams. Writer classes have methods that support the writing of objects to output streams. Ans : a and b. The isFile( ) method returns a boolean value depending on whether the file object is a file or a directory. True. False. Ans : a. Reading or writing can be done even after closing the input/output source. True. False. Ans : b. The ________ method helps in clearing the buffer. Ans : flush( ). The System.err method is used to print error message. True. False. Ans : a. What is meant by StreamTokenizer? Ans : StreamTokenizer breaks up InputStream into tokens that are delimited by sets of characters. It has the constructor : StreamTokenizer(Reader inStream). Here inStream must be some form of Reader. What is Serialization and deserialization? Ans : Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects. 30) Which of the following can you perform using the File class? a) Change the current directory b) Return the name of the parent directory c) Delete a file d) Find if a file contains text or binary information Ans : b and c. 31)How can you change the current working directory using an instance of the File class called FileName? FileName.chdir("DirName"). FileName.cd("DirName"). FileName.cwd("DirName"). The File class does not support directly changing the current directory. Ans : d.

Freshersworld.com Resource Center

22

First Job. Dream Job. Freshersworld.com

EVENT HANDLING The event delegation model, introduced in release 1.1 of the JDK, is fully compatible with the event model. True False Ans : b.
Freshersworld.com Resource Center

23

First Job. Dream Job. Freshersworld.com


A component subclass that has executed enableEvents( ) to enable processing of a certain kind of event cannot also use an adapter as a listener for the same kind of event. True False Ans : b. What is the highest-level event class of the event-delegation model? Ans : The java.util.eventObject class is the highest-level class in the event-delegation hierarchy. What interface is extended by AWT event listeners? Ans : All AWT event listeners extend the java.util.EventListener interface. What class is the top of the AWT event hierarchy? Ans : The java.awt.AWTEvent class is the highest-level class in the AWT event class hierarchy. What event results from the clicking of a button? Ans : The ActionEvent event is generated as the result of the clicking of a button. What is the relationship between an event-listener interface and an event-adapter class? Ans : An event-listener interface defines the methods that must be implemented by an event handler for a particular kind of event. An event adapter provides a default implementation of an event-listener interface. In which package are most of the AWT events that support the event-delegation model defined? Ans : Most of the AWTrelated events of the event-delegation model are defined in the java.awt.event package. The AWTEvent class is defined in the java.awt package. What is the advantage of the event-delegation model over the earlier event-inheritance model? Ans : The event-delegation has two advantages over the event-inheritance model. They are : It enables event handling by objects other than the ones that generate the events. This allows a clean separation between a components design and its use. It performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events, as is the case of the event-inheritance model. What is the purpose of the enableEvents( ) method? Ans :The enableEvents( ) method is used to enable an event for a particular object. Which of the following are true? The event-inheritance model has replaced the event-delegation model. The event-inheritance model is more efficient than the event-delegation model. The event-delegation model uses event listeners to define the methods of event-handling classes. The event-delegation model uses the handleEvent( ) method to support event handling. Ans : c. Which of the following is the highest class in the event-delegation model? java.util.EventListener java.util.EventObject java.awt.AWTEvent java.awt.event.AWTEvent Ans : b. When two or more objects are added as listeners for the same event, which listener is first invoked to handle the event? The first object that was added as listener. The last object that was added as listener. There is no way to determine which listener will be invoked first. It is impossible to have more than one listener for a given event. Ans : c. Which of the following components generate action events? Buttons Labels Check boxes Windows Ans : a. Which of the following are true?
Freshersworld.com Resource Center

24

First Job. Dream Job. Freshersworld.com


A TextField object may generate an ActionEvent. A TextArea object may generate an ActionEvent. A Button object may generate an ActionEvent. A MenuItem object may generate an ActionEvent. Ans : a,c and d. Which of the following are true? The MouseListener interface defines methods for handling mouse clicks. The MouseMotionListener interface defines methods for handling mouse clicks. The MouseClickListener interface defines methods for handling mouse clicks. The ActionListener interface defines methods for handling the clicking of a button. Ans : a and d. Suppose that you want to have an object eh handle the TextEvent of a TextArea object t. How should you add eh as the event handler for t? t.addTextListener(eh); eh.addTextListener(t); addTextListener(eh.t); addTextListener(t,eh); Ans : a. What is the preferred way to handle an objects events in Java 2? Override the objects handleEvent( ) method. Add one or more event listeners to handle the events. Have the object override its processEvent( ) methods. Have the object override its dispatchEvent( ) methods. Ans : b. Which of the following are true? A component may handle its own events by adding itself as an event listener. A component may handle its own events by overriding its event-dispatching method. A component may not handle oits own events. A component may handle its own events only if it implements the handleEvent( ) method. Ans : a and b.

APPLETS What is an Applet? Should applets have constructors? Ans : Applet is a dynamic and interactive program that runs inside a Web page displayed by a Java capable browser. We dont have the concept of Constructors in Applets. How do we read number information from my applets parameters, given that Applets getParameter() method returns a string? Ans : Use the parseInt() method in the Integer Class, the Float(String) constructor in the
Freshersworld.com Resource Center

25

First Job. Dream Job. Freshersworld.com


Class Float, or the Double(String) constructor in the class Double. How can I arrange for different applets on a web page to communicate with each other? Ans : Name your applets inside the Applet tag and invoke AppletContexts getApplet() method in your applet code to obtain references to the other applets on the page. How do I select a URL from my Applet and send the browser to that page? Ans : Ask the applet for its applet context and invoke showDocument() on that context object. Eg. URL targetURL; String URLString AppletContext context = getAppletContext(); try{ targetUR L = new URL(URLString); } catch (Malformed URLException e){ // Code for recover from the exception } context. showDocument (targetURL); Can applets on different pages communicate with each other? Ans : No. Not Directly. The applets will exchange the information at one meeting place either on the local file system or at remote system. How do Applets differ from Applications? Ans : Appln: Stand Alone Applet: Needs no explicit installation on local m/c. Appln: Execution starts with main() method. Applet: Execution starts with init() method. Appln: May or may not be a GUI Applet: Must run within a GUI (Using AWT) How do I determine the width and height of my application? Ans : Use the getSize() method, which the Applet class inherits from the Component class in the Java.awt package. The getSize() method returns the size of the applet as a Dimension object, from which you extract separate width, height fields. Eg. Dimension dim = getSize (); int appletwidth = dim.width (); 8) What is AppletStub Interface? Ans : The applet stub interface provides the means by which an applet and the browser communicate. Your code will not typically implement this interface. It is essential to have both the .java file and the .html file of an applet in the same directory. True. False. Ans : b. The <PARAM> tag contains two attributes namely _________ and _______. Ans : Name , value. Passing values to parameters is done in the _________ file of an applet. Ans : .html. 12) What tags are mandatory when creating HTML to display an applet name, height, width code, name codebase, height, width d) code, height, width Ans : d. Applets getParameter( ) method can be used to get parameter values. True. False. Ans : a. What are the Applets Life Cycle methods? Explain them? Ans : init( ) method - Can be called when an applet is first loaded.
Freshersworld.com Resource Center

26

First Job. Dream Job. Freshersworld.com


start( ) method - Can be called each time an applet is started. paint( ) method - Can be called when the applet is minimized or refreshed. stop( ) method - Can be called when the browser moves off the applets page. destroy( ) method - Can be called when the browser is finished with the applet. What are the Applets information methods? Ans : getAppletInfo( ) method : Returns a string describing the applet, its author ,copy right information, etc. getParameterInfo( ) method : Returns an array of string describing the applets parameters. All Applets are subclasses of Applet. True. False. Ans : a. All Applets must import java.applet and java.awt. True. False. Ans : a. What are the steps involved in Applet development? Ans : a) Edit a Java source file, b) Compile your program and c) Execute the appletviewer, specifying the name of your applets source file. Applets are executed by the console based Java run-time interpreter. True. False. Ans : b. Which classes and interfaces does Applet class consist? Ans : Applet class consists of a single class, the Applet class and three interfaces: AppletContext, AppletStub and AudioClip. What is the sequence for calling the methods by AWT for applets? Ans : When an applet begins, the AWT calls the following methods, in this sequence. init( ) start( ) paint( ) When an applet is terminated, the following sequence of method cals takes place : stop( ) destroy( ) Which method is used to output a string to an applet? Ans : drawString ( ) method. Every color is created from an RGB value. True. False Ans : a.

AWT : WINDOWS, GRAPHICS AND FONTS How would you set the color of a graphics context called g to cyan? g.setColor(Color.cyan); g.setCurrentColor(cyan); g.setColor("Color.cyan"); g.setColor("cyan); g.setColor(new Color(cyan)); Ans : a. The code below draws a line. What color is the line? g.setColor(Color.red.green.yellow.red.cyan); g.drawLine(0, 0, 100,100); Red Green
Freshersworld.com Resource Center

27

First Job. Dream Job. Freshersworld.com


Yellow Cyan Black Ans : d. What does the following code draw? g.setColor(Color.black); g.drawLine(10, 10, 10, 50); g.setColor(Color.RED); g.drawRect(100, 100, 150, 150); A red vertical line that is 40 pixels long and a red square with sides of 150 pixels A black vertical line that is 40 pixels long and a red square with sides of 150 pixels A black vertical line that is 50 pixels long and a red square with sides of 150 pixels A red vertical line that is 50 pixels long and a red square with sides of 150 pixels A black vertical line that is 40 pixels long and a red square with sides of 100 pixel Ans : b. Which of the statements below are true? A polyline is always filled. b) A polyline can not be filled. c) A polygon is always filled. d) A polygon is always closed e) A polygon may be filled or not filled Ans : b, d and e. What code would you use to construct a 24-point bold serif font? new Font(Font.SERIF, 24,Font.BOLD); new Font("SERIF", 24, BOLD"); new Font("BOLD ", 24,Font.SERIF); new Font("SERIF", Font.BOLD,24); new Font(Font.SERIF, "BOLD", 24); Ans : d. What does the following paint( ) method draw? Public void paint(Graphics g) { g.drawString("question #6",10,0); } The string "question #6", with its top-left corner at 10,0 A little squiggle coming down from the top of the component, a little way in from the left edge Ans : b.

What does the following paint( ) method draw? Public void paint(Graphics g) { g.drawString("question #6",10,0); } A circle at (100, 100) with radius of 44 A circle at (100, 44) with radius of 100 A circle at (100, 44) with radius of 44 The code does not compile Ans : d. 8)What is relationship between the Canvas class and the Graphics class? Ans : A Canvas object provides access to a Graphics object via its paint( ) method. What are the Component subclasses that support painting. Ans : The Canvas, Frame, Panel and Applet classes support painting. What is the difference between the paint( ) and repaint( ) method? Ans : The paint( ) method supports painting via a Graphics object. The repaint( ) method is used to cause paint( ) to be invoked by the AWT painting method. What is the difference between the Font and FontMetrics classes? Ans : The FontMetrics class is used to define implementation-specific properties, such as ascent
Freshersworld.com Resource Center

28

First Job. Dream Job. Freshersworld.com


and descent, of a Font object. Which of the following are passed as an argument to the paint( ) method? A Canvas object A Graphics object An Image object A paint object Ans : b. Which of the following methods are invoked by the AWT to support paint and repaint operations? paint( ) repaint( ) draw( ) redraw( ) Ans : a. Which of the following classes have a paint( ) method? Canvas Image Frame Graphics Ans : a and c. Which of the following are methods of the Graphics class? drawRect( ) drawImage( ) drawPoint( ) drawString( ) Ans : a, b and d. Which Font attributes are available through the FontMetrics class? ascent leading case height Ans : a, b and d. Which of the following are true? The AWT automatically causes a window to be repainted when a portion of a window has been minimized and then maximized. The AWT automatically causes a window to be repainted when a portion of a window has been covered and then uncovered. The AWT automatically causes a window to be repainted when application data is changed. The AWT does not support repainting operations. Ans : a and b. Which method is used to size a graphics object to fit the current size of the window? Ans : getSize( ) method. What are the methods to be used to set foreground and background colors? Ans : setForeground( ) and setBackground( ) methods. 19) You have created a simple Frame and overridden the paint method as follows public void paint(Graphics g){ g.drawString("Dolly",50,10); } What will be the result when you attempt to compile and run the program? The string "Dolly" will be displayed at the centre of the frame b) An error at compilation complaining at the signature of the paint method c) The lower part of the word Dolly will be seen at the top of the form, with the top hidden. d) The string "Dolly" will be shown at the bottom of the form Ans : c. 20) Where g is a graphics instance what will the following code draw on the screen.
Freshersworld.com Resource Center

29

First Job. Dream Job. Freshersworld.com


g.fillArc(45,90,50,50,90,180); a) An arc bounded by a box of height 45, width 90 with a centre point of 50,50, starting at an angle of 90 degrees traversing through 180 degrees counter clockwise. b) An arc bounded by a box of height 50, width 50, with a centre point of 45,90 starting at an angle of 90 degrees traversing through 180 degrees clockwise. c) An arc bounded by a box of height 50, width 50, with a top left at coordinates of 45, 90, starting at 90 degrees and traversing through 180 degrees counter clockwise. d) An arc starting at 45 degrees, traversing through 90 degrees clockwise bounded by a box of height 50, width 50 with a centre point of 90, 180. Ans : c. 21) Given the following code import java.awt.*; public class SetF extends Frame{ public static void main(String argv[]){ SetF s = new SetF(); s.setSize(300,200); s.setVisible(true); } } How could you set the frame surface color to pink a)s.setBackground(Color.pink); b)s.setColor(PINK); c)s.Background(pink); d)s.color=Color.pink Ans : a.

AWT: CONTROLS, LAYOUT MANAGERS AND MENUS What is meant by Controls and what are different types of controls? Ans : Controls are componenets that allow a user to interact with your application. The AWT supports the following types of controls: Labels Push buttons Check boxes Choice lists Lists Scroll bars Text components These controls are subclasses of Component. You want to construct a text area that is 80 character-widths wide and 10 character-heights tall. What code do you use? new TextArea(80, 10) new TextArea(10, 80) Ans: b. A text field has a variable-width font. It is constructed by calling new TextField("iiiii"). What happens if you change the contents of the text field to "wwwww"? (Bear in mind that is one of the narrowest characters, and w is one of the widest.) The text field becomes wider. The text field becomes narrower. The text field stays the same width; to see the entire contents you will have to scroll by using the and keys. The text field stays the same width; to see the entire contents you will have to scroll by using the text fields horizontal scroll bar. Ans : c.
Freshersworld.com Resource Center

30

First Job. Dream Job. Freshersworld.com


The CheckboxGroup class is a subclass of the Component class. True False Ans : b. 5) What are the immediate super classes of the following classes? a) Container class b) MenuComponent class c) Dialog class d) Applet class e) Menu class Ans : a) Container - Component b) MenuComponent - Object c) Dialog - Window d) Applet - Panel e) Menu - MenuItem 6) What are the SubClass of Textcomponent Class? Ans : TextField and TextArea 7) Which method of the component class is used to set the position and the size of a component? Ans : setBounds() 8) Which TextComponent method is used to set a TextComponent to the read-only state? Ans : setEditable() 9) How can the Checkbox class be used to create a radio button? Ans : By associating Checkbox objects with a CheckboxGroup. 10) What Checkbox method allows you to tell if a Checkbox is checked? Ans : getState() 11) Which Component method is used to access a component's immediate Container? getVisible() getImmediate getParent() getContainer Ans : c. 12) What methods are used to get and set the text label displayed by a Button object? Ans : getLabel( ) and setLabel( ) 13) What is the difference between a Choice and a List? Ans : A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices. Only one item may be selected from a Choice. A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items. 14) Which Container method is used to cause a container to be laid out and redisplayed? Ans : validate( ) 15) What is the difference between a Scollbar and a Scrollpane? Ans : A Scrollbar is a Component, but not a Container. A Scrollpane is a Container and handles its own events and performs its own scrolling. 16) Which Component subclass is used for drawing and painting? Ans : Canvas. 17) Which of the following are direct or indirect subclasses of Component? Button Label CheckboxMenuItem Toolbar Frame Ans : a, b and e. 18) Which of the following are direct or indirect subclasses of Container? Frame TextArea
Freshersworld.com Resource Center

31

First Job. Dream Job. Freshersworld.com


MenuBar FileDialog Applet Ans : a,d and e. 19) Which method is used to set the text of a Label object? setText( ) setLabel( ) setTextLabel( ) setLabelText( ) Ans : a. 20) Which constructor creates a TextArea with 10 rows and 20 columns? new TextArea(10, 20) new TextArea(20, 10) new TextArea(new Rows(10), new columns(20)) new TextArea(200) Ans : a. (Usage is TextArea(rows, columns) 21) Which of the following creates a List with 5 visible items and multiple selection enabled? new List(5, true) new List(true, 5) new List(5, false) new List(false,5) Ans : a. [Usage is List(rows, multipleMode)] 22) Which are true about the Container class? The validate( ) method is used to cause a Container to be laid out and redisplayed. The add( ) method is used to add a Component to a Container. The getBorder( ) method returns information about a Containers insets. The getComponent( ) method is used to access a Component that is contained in a Container. Ans : a, b and d. 23) Suppose a Panel is added to a Frame and a Button is added to the Panel. If the Frames font is set to 12-point TimesRoman, the Panels font is set to 10-point TimesRoman, and the Buttons font is not set, what font will be used to dispaly the Buttons label? 12-point TimesRoman 11-point TimesRoman 10-point TimesRoman 9-point TimesRoman Ans : c. A Frames background color is set to Color.Yellow, and a Buttons background color is to Color.Blue. Suppose the Button is added to a Panel, which is added to the Frame. What background color will be used with the Panel? Colr.Yellow Color.Blue Color.Green Color.White Ans : a. 25) Which method will cause a Frame to be displayed? show( ) setVisible( ) display( ) displayFrame( ) Ans : a and b. 26) All the componenet classes and container classes are derived from _________ class. Ans : Object. 27) Which method of the container class can be used to add components to a Panel. Ans : add ( ) method.
Freshersworld.com Resource Center

32

First Job. Dream Job. Freshersworld.com


28) What are the subclasses of the Container class? Ans : The Container class has three major subclasses. They are : Window Panel ScrollPane 29) The Choice component allows multiple selection. True. False. Ans : b. 30) The List component does not generate any events. True. False. Ans : b. 31) Which components are used to get text input from the user. Ans : TextField and TextArea. 32) Which object is needed to group Checkboxes to make them exclusive? Ans : CheckboxGroup. 33) Which of the following components allow multiple selections? Non-exclusive Checkboxes. Radio buttons. Choice. List. Ans : a and d. 34) What are the types of Checkboxes and what is the difference between them? Ans : Java supports two types of Checkboxes. They are : Exclusive and Non-exclusive. In case of exclusive Checkboxes, only one among a group of items can be selected at a time. I f an item from the group is selected, the checkbox currently checked is deselected and the new selection is highlighted. The exclusive Checkboxes are also called as Radio buttons. The non-exclusive checkboxes are not grouped together and each one can be selected independent of the other. 35) What is a Layout Manager and what are the different Layout Managers available in java.awt and what is the default Layout manager for the panal and the panal subclasses? Ans: A layout Manager is an object that is used to organize components in a container. The different layouts available in java.awt are : FlowLayout, BorderLayout, CardLayout, GridLayout and GridBag Layout. The default Layout Manager of Panal and Panal sub classes is FlowLayout". 36) Can I exert control over the size and placement of components in my interface? Ans : Yes. myPanal.setLayout(null); myPanal.setbounds(20,20,200,200); 37) Can I add the same component to more than one container? Ans : No. Adding a component to a container automatically removes it from any previous parent(container). 38) How do I specify where a window is to be placed? Ans : Use setBounds, setSize, or setLocation methods to implement this. setBounds(int x, int y, int width, int height) setBounds(Rectangle r) setSize(int width, int height) setSize(Dimension d) setLocation(int x, int y) setLocation(Point p) 39) How can we create a borderless window? Ans : Create an instance of the Window class, give it a size, and show it on the screen. eg. Frame aFrame = ...... Window aWindow = new Window(aFrame);
Freshersworld.com Resource Center

33

First Job. Dream Job. Freshersworld.com


aWindow.setLayout(new FlowLayout()); aWindow.add(new Button("Press Me")); aWindow.getBounds(50,50,200,200); aWindow.show(); 40) Can I create a non-resizable windows? If so, how? Ans: Yes. By using setResizable() method in class Frame. 41) What is the default Layout Manager for the Window and Window subclasses (Frame,Dialog)? Ans : BorderLayout(). 42) How are the elements of different layouts organized? Ans : FlowLayout : The elements of a FlowLayout are organized in a top to bottom, left to right fashion. BorderLayout : The elements of a BorderLayout are organized at the borders (North, South, East and West) and the center of a container. CardLayout : The elements of a CardLayout are stacked, one on top of the other, like a deck of cards. GridLayout : The elements of a GridLayout are of equal size and are laid out using the square of a grid. GridBagLayout : The elements of a GridBagLayout are organized according to a grid.However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes. 43) Which containers use a BorderLayout as their default layout? Ans : The Window, Frame and Dialog classes use a BorderLayout as their default layout. 44) Which containers use a FlowLayout as their default layout? Ans : The Panel and the Applet classes use the FlowLayout as their default layout. 45) What is the preferred size of a component? Ans : The preferred size of a component size that will allow the component to display normally. 46) Which method is method to set the layout of a container? startLayout( ) initLayout( ) layoutContainer( ) setLayout( ) Ans : d. 47) Which method returns the preferred size of a component? getPreferredSize( ) getPreferred( ) getRequiredSize( ) getLayout( ) Ans : a.

48) Which layout should you use to organize the components of a container in a tabular form? CardLayout BorederLayout FlowLayout GridLayout Ans : d. An application has a frame that uses a Border layout manager. Why is it probably not a good idea to put a vertical scroll bar at North in the frame? The scroll bars height would be its preferred height, which is not likely to be enough. The scroll bars width would be the entire width of the frame, which would be much wider than necessary.
Freshersworld.com Resource Center

34

First Job. Dream Job. Freshersworld.com


Both a and b. Neither a nor b. There is no problem with the layout as described. Ans : c. What is the default layouts for a applet, a frame and a panel? Ans : For an applet and a panel, Flow layout is the default layout, whereas Border layout is default layout for a frame. If a frame uses a Grid layout manager and does not contain any panels, then all the components within the frame are the same width and height. True False. Ans : a. If a frame uses its default layout manager and does not contain any panels, then all the components within the frame are the same width and height. True False. Ans : b. With a Border layout manager, the component at Center gets all the space that is left over, after the components at North and South have been considered. True False Ans : b. An Applet has its Layout Manager set to the default of FlowLayout. What code would be the correct to change to another Layout Manager? setLayoutManager(new GridLayout()); setLayout(new GridLayout(2,2)); c) setGridLayout(2,2,)) d setBorderLayout(); Ans : b. 55) How do you indicate where a component will be positioned using Flowlayout? a) North, South,East,West b) Assign a row/column grid reference c) Pass a X/Y percentage parameter to the add method d) Do nothing, the FlowLayout will position the component Ans :d.

56) How do you change the current layout manager for a container? a) Use the setLayout method b) Once created you cannot change the current layout manager of a component c) Use the setLayoutManager method d) Use the updateLayout method Ans :a. 57)When using the GridBagLayout manager, each new component requires a new instance of the GridBagConstraints class. Is this statement true or false? a) true b) false Ans : b. 58) Which of the following statements are true? a)The default layout manager for an Applet is FlowLayout b) The default layout manager for an application is FlowLayout c) A layout manager must be assigned to an Applet before the setSize method is called d) The FlowLayout manager attempts to honor the preferred size of any components Ans : a and d. 59) Which method does display the messages whenever there is an item selection or deselection of the CheckboxMenuItem menu?
Freshersworld.com Resource Center

35

First Job. Dream Job. Freshersworld.com


Ans : itemStateChanged method. 60) Which is a dual state menu item? Ans : CheckboxMenuItem. 61) Which method can be used to enable/diable a checkbox menu item? Ans : setState(boolean). Which of the following may a menu contain? A separator A check box A menu A button A panel Ans : a and c. Which of the following may contain a menu bar? A panel A frame An applet A menu bar A menu Ans : b 64) What is the difference between a MenuItem and a CheckboxMenuItem? Ans : The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked. 65) Which of the following are true? A Dialog can have a MenuBar. MenuItem extends Menu. A MenuItem can be added to a Menu. A Menu can be added to a Menu. Ans : c and d.

Which colour is used to indicate instance methods in the standard "javadoc" format documentation: 1) blue 2) red 3) purple 4) orange Answer : 2 explain In JDK 1.1 the variabels, methods and constructors are colour coded to simplifytheir identification. endExplain What is the correct ordering for the import, class and package declarations when found in a single file? 1) package, import, class 2) class, import, package 3) import, package, class 4) package, class, import Answer : 1 explain This is my explanation for question 2 endExplain Which methods can be legally applied to a string object? (Multiple) 1) equals(String) 2) equals(Object) 3) trim() 4) round() 5) toString()
Freshersworld.com Resource Center

36

First Job. Dream Job. Freshersworld.com


Answer : 1,2,3,5 What is the parameter specification for the public static void main method? (multiple) 1) String args [] 2) String [] args 3) Strings args [] 4) String args Answer : 1,2 What does the zeroth element of the string array passed to the public static void main method contain? (multiple) 1) The name of the program 2) The number of arguments 3) The first argument if one is present Answer : 3 Which of the following are Java keywords? (multiple) 1) goto 2) malloc 3) extends 4) FALSE Answer : 3 What will be the result of compiling the following code: public class Test { public static void main (String args []) { int age; age = age + 1; System.out.println("The age is " + age); } } 1) Compiles and runs with no output 2) Compiles and runs printing out The age is 1 3) Compiles but generates a runtime error 4) Does not compile 5) Compiles but generates a compile time error Answer : 4 Which of these is the correct format to use to create the literal char value a? (multiple) 1) 'a' 2) "a" 3) new Character(a) 4) \000a Answer : 1 What is the legal range of a byte integral type? 1) 0 - 65, 535 2) (-128) - 127 3) (-32,768) - 32,767 4) (-256) - 255 Answer : 2 Which of the following is illegal: 1) int i = 32; 2) float f = 45.0; 3) double d = 45.0; Answer 2 What will be the result of compiling the following code: public class Test { static int age;
Freshersworld.com Resource Center

37

First Job. Dream Job. Freshersworld.com


public static void main (String args []) { age = age + 1; System.out.println("The age is " + age); } } 1) Compiles and runs with no output 2) Compiles and runs printing out The age is 1 3) Compiles but generates a runtime error 4) Does not compile 5) Compiles but generates a compile time error Answer : 2 Which of the following are correct? (multiple) 1) 128 >> 1 gives 64 2) 128 >>> 1 gives 64 3) 128 >> 1 gives -64 4) 128 >>> 1 gives -64 Answer : 1 Which of the following return true? (multiple) 1) "john" == new String("john") 2) "john".equals("john") 3) "john" = "john" 4) "john".equals(new Button("john")) Answer : 2 Which of the following do not lead to a runtime error? (multiple) 1) "john" + " was " + " here" 2) "john" + 3 3) 3 + 5 4) 5 + 5.5 answer 1,2,3,4 Which of the following are so called "short circuit" logical operators? (multiple) 1) & 2) || 3) && 4) | Answer : 2,3 Which of the following are acceptable? (multiple) 1) Object o = new Button("A"); 2) Boolean flag = true; 3) Panel p = new Frame(); 4) Frame f = new Panel(); 5) Panel p = new Applet(); Answer : 1,5 What is the result of compiling and running the following code: public class Test { static int total = 10; public static void main (String args []) { new Test(); } public Test () { System.out.println("In test"); System.out.println(this);
Freshersworld.com Resource Center

38

First Job. Dream Job. Freshersworld.com


int temp = this.total; if (temp > 5) { System.out.println(temp); } } } (multiple) 1) The class will not compile 2) The compiler reports and error at line 2 3) The compiler reports an error at line 9 4) The value 10 is one of the elements printed to the standard output 5) The class compiles but generates a runtime error Answer : 4 Which of the following is correct: 1) String temp [] = new String {"j" "a" "z"}; 2) String temp [] = { "j " " b" "c"}; 3) String temp = {"a", "b", "c"}; 4) String temp [] = {"a", "b", "c"}; Answer 4 What is the correct declaration of an abstract method that is intended to be public: 1) public abstract void add(); 2) public abstract void add() {} 3) public abstract add(); 4) public virtual add(); Answer : 1 Under what situations do you obtain a default constructor? 1) When you define any class 2) When the class has no other constructors 3) When you define at least one constructor Answer : 2 Which of the following can be used to define a constructor for this class, given the following code: public class Test { ... } 1) public void Test() {...} 2) public Test() {...} 3) public static Test() {...} 4) public static void Test() {...} Answer : 2 Which of the following are acceptable to the Java compiler: (multiple) 1) if (2 == 3) System.out.println("Hi"); 2) if (2 = 3) System.out.println("Hi"); 3) if (true) System.out.println("Hi"); 4) if (2 != 3) System.out.println("Hi"); 5) if (aString.equals("hello")) System.out.println("Hi"); Answer : 1,3,4,5 Assuming a method contains code which may raise an Exception (but not a RuntimeException), what is the correct way for a method to indicate that it expects the caller to handle that exception: 1) throw Exception 2) throws Exception 3) new Exception 4) Don't need to specify anything Answer : 2 What is the result of executing the following code, using the parameters 4 and 0: public void divide(int a, int b) {
Freshersworld.com Resource Center

39

First Job. Dream Job. Freshersworld.com


try { int c = a / b; } catch (Exception e) { System.out.print("Exception "); } finally { System.out.println("Finally"); } 1) Prints out: Exception Finally 2) Prints out: Finally 3) Prints out: Exception 4) No output Answer : 1 Which of the following is a legal return type of a method overloading the following method: public void add(int a) {...} 1) void 2) int 3) Can be anything Answer : 3 Which of the following statements is correct for a method which is overriding the following method: public void add(int a) {...} 1) the overriding method must return void 2) the overriding method must return int 3) the overriding method can return whatever it likes Answer : 1 Given the following classes defined in separate files, what will be the effect of compiling and running this class Test? class Vehicle { public void drive() { System.out.println("Vehicle: drive"); } } class Car extends Vehicle { public void drive() { System.out.println("Car: drive"); } } public class Test { public static void main (String args []) { Vehicle v; Car c; v = new Vehicle(); c = new Car(); v.drive(); c.drive(); v = c; v.drive(); } } 1) Generates a Compiler error on the statement v= c; 2) Generates runtime error on the statement v= c; 3) Prints out: Vehicle: drive Car: drive Car: drive 4) Prints out: Vehicle: drive
Freshersworld.com Resource Center

40

First Job. Dream Job. Freshersworld.com


Car: drive Vehicle: drive Answer : 3 Where in a constructor, can you place a call to a constructor defined in the super class? 1) Anywhere 2) The first statement in the constructor 3) The last statement in the constructor 4) You can't call super in a constructor Answer : 2 Which variables can an inner class access from the class which encapsulates it? (multiple) 1) All static variables 2) All final variables 3) All instance variables 4) Only final instance variables 5) Only final static variables Answer : 1,2,3 What class must an inner class extend: 1) The top level class 2) The Object class 3) Any class or interface 4) It must extend an interface Answer 3 In the following code, which is the earliest statement, where the object originally held in e, may be garbage collected: 1. public class Test { 2. public static void main (String args []) { 3. Employee e = new Employee("Bob", 48); 4. e.calculatePay(); 5. System.out.println(e.printDetails()); 6. e = null; 7. e = new Employee("Denise", 36); 8. e.calculatePay(); 9. System.out.println(e.printDetails()); 10. } 11. } 1) Line 10 2) Line 11 3) Line 7 4) Line 8 5) Never Answer : 3 What is the name of the interface that can be used to define a class that can execute within its own thread? 1) Runnable 2) Run 3) Threadable 4) Thread 5) Executable Answer : 1 What is the name of the method used to schedule a thread for execution? 1) init(); 2) start(); 3) run(); 4) resume(); 5) sleep();
Freshersworld.com Resource Center

41

First Job. Dream Job. Freshersworld.com


Answer : 2 Which methods may cause a thread to stop executing? (multiple) 1) sleep(); 2) stop(); 3) yield(); 4) wait(); 5) notify(); 6) notifyAll() 7) synchronized() Answer : 1,2,3,4 Which of the following would create a text field able to display 10 characters (assuming a fixed size font) displaying the initial string "hello": 1) new TextField("hello", 10); 2) new TextField("hello"); 3) new textField(10); 4) new TextField(); Answer : 1 Which of the following methods are defined on the Graphics class: (multiple) 1) drawLine(int, int, int, int) 2) drawImage(Image, int, int, ImageObserver) 3) drawString(String, int, int) 4) add(Component); 5) setVisible(boolean); 6) setLayout(Object); Answer : 1,2,3 Which of the following layout managers honours the preferred size of a component: (multiple) 1) CardLayout 2) FlowLayout 3) BorderLayout 4) GridLayout Answer : 2 Given the following code what is the effect of a being 5: public class Test { public void add(int a) { loop: for (int i = 1; i < 3; i++){ for (int j = 1; j < 3; j++) { if (a == 5) { break loop; } System.out.println(i * j); } } } } 1) Generate a runtime error 2) Throw an ArrayIndexOutOfBoundsException 3) Print the values: 1, 2, 2, 4 4) Produces no output Answer : 4 What is the effect of issuing a wait() method on an object 1) If a notify() method has already been sent to that object then it has no effect 2) The object issuing the call to wait() will halt until another object sends a notify() or notifyAll() method
Freshersworld.com Resource Center

42

First Job. Dream Job. Freshersworld.com


3) An exception will be raised 4) The object issuing the call to wait() will be automatically synchronized with any other objects using the receiving object. Answer : 2 The layout of a container can be altered using which of the following methods: (multiple) 1) setLayout(aLayoutManager); 2) addLayout(aLayoutManager); 3) layout(aLayoutManager); 4) setLayoutManager(aLayoutManager); Answer : 1 Using a FlowLayout manager, which is the correct way to add elements to a container: 1) add(component); 2) add("Center", component); 3) add(x, y, component); 4) set(component); Answer : 1 Given that a Button can generate an ActionEvent which listener would you expect to have to implement, in a class which would handle this event? 1) FocusListener 2) ComponentListener 3) WindowListener 4) ActionListener 5) ItemListener Answer : 4 Which of the following, are valid return types, for listener methods: 1) boolean 2) the type of event handled 3) void 4) Component Answer : 3 Assuming we have a class which implements the ActionListener interface, which method should be used to register this with a Button? 1) addListener(*); 2) addActionListener(*); 3) addButtonListener(*); 4) setListener(*); Answer : 2 In order to cause the paint(Graphics) method to execute, which of the following is the most appropriate method to call: 1) paint() 2) repaint() 3) paint(Graphics) 4) update(Graphics) 5) None - you should never cause paint(Graphics) to execute Answer : 2 Which of the following illustrates the correct way to pass a parameter into an applet: 1) <applet code=Test.class age=33 width=100 height=100> 2) <param name=age value=33> 3) <applet code=Test.class name=age value=33 width=100 height=100> 4) <applet Test 33> Answer : 2 Which of the following correctly illustrate how an InputStreamReader can be created: (multiple) 1) new InputStreamReader(new FileInputStream("data")); 2) new InputStreamReader(new FileReader("data"));
Freshersworld.com Resource Center

43

First Job. Dream Job. Freshersworld.com


3) new InputStreamReader(new BufferedReader("data")); 4) new InputStreamReader("data"); 5) new InputStreamReader(System.in); Answer : 1,5 What is the permanent effect on the file system of writing data to a new FileWriter("report"), given the file report already exists? 1) The data is appended to the file 2) The file is replaced with a new file 3) An exception is raised as the file already exists 4) The data is written to random locations within the file Answer : 2 What is the effect of adding the sixth element to a vector created in the following manner: new Vector(5, 10); 1) An IndexOutOfBounds exception is raised. 2) The vector grows in size to a capacity of 10 elements 3) The vector grows in size to a capacity of 15 elements 4) Nothing, the vector will have grown when the fifth element was added Answer : 3 What is the result of executing the following code when the value of x is 2: switch (x) { case 1: System.out.println(1); case 2: case 3: System.out.println(3); case 4: System.out.println(4); } 1) Nothing is printed out 2) The value 3 is printed out 3) The values 3 and 4 are printed out 4) The values 1, 3 and 4 are printed out Answer : 3 What is the result of compiling and running the Second class? Consider the following example: class First { public First (String s) { System.out.println(s); } } public class Second extends First { public static void main(String args []) { new Second(); } } 1) Nothing happens 2) A string is printed to the standard out 3) An instance of the class First is generated 4) An instance of the class Second is created 5) An exception is raised at runtime stating that there is no null parameter constructor in class First. 6) The class second will not compile as there is no null parameter constructor in the class First Answer : 6 What is the result of executing the following fragment of code: boolean flag = false; if (flag = true) { System.out.println("true");
Freshersworld.com Resource Center

44

First Job. Dream Job. Freshersworld.com


} else { System.out.println("false"); } 1) true is printed to standard out 2) false is printed to standard out 3) An exception is raised 4) Nothing happens Answer : 1 Consider the following classes. What is the result of compiling and running this class? public class Test { public static void test() { this.print(); } public static void print() { System.out.println("Test"); } public static void main(String args []) { test(); } } (multiple) 1) The string Test is printed to the standard out. 2) A runtime exception is raised stating that an object has not been created. 3) Nothing is printed to the standard output. 4) An exception is raised stating that the method test cannot be found. 5) An exception is raised stating that the variable this can only be used within an instance. 6) The class fails to compile stating that the variable this is undefined. Answer : 6 Examine the following class definition: public class Test { public static void test() { print(); } public static void print() { System.out.println("Test"); } public void print() { System.out.println("Another Test"); } } What is the result of compiling this class: 1) A successful compilation. 2) A warning stating that the class has no main method. 3) An error stating that there is a duplicated method. 4) An error stating that the method test() will call one or other of the print() methods. Answer : 3 What is the result of compiling and executing the following Java class: public class ThreadTest extends Thread { public void run() { System.out.println("In run"); suspend(); resume(); System.out.println("Leaving run"); } public static void main(String args []) { (new ThreadTest()).start();
Freshersworld.com Resource Center

45

First Job. Dream Job. Freshersworld.com


} } 1) Compilation will fail in the method main. 2) Compilation will fail in the method run. 3) A warning will be generated for method run. 4) The string "In run" will be printed to standard out. 5) Both strings will be printed to standard out. 6) Nothing will happen. Answer : 4 Given the following sequence of Java statements, Which of the following options are true: 1. StringBuffer sb = new StringBuffer("abc"); 2. String s = new String("abc"); 3. sb.append("def"); 4. s.append("def"); 5. sb.insert(1, "zzz"); 6. s.concat(sb); 7. s.trim(); (multiple) 1) The compiler would generate an error for line 1. 2) The compiler would generate an error for line 2. 3) The compiler would generate an error for line 3. 4) The compiler would generate an error for line 4. 5) The compiler would generate an error for line 5. 6) The compiler would generate an error for line 6. 7) The compiler would generate an error for line 7. Answer : 4,6 What is the result of executing the following Java class: import java.awt.*; public class FrameTest extends Frame { public FrameTest() { add (new Button("First")); add (new Button("Second")); add (new Button("Third")); pack(); setVisible(true); } public static void main(String args []) { new FrameTest(); } } 1) Nothing happens. 2) Three buttons are displayed across a window. 3) A runtime exception is generated (no layout manager specified). 4) Only the "first" button is displayed. 5) Only the "second" button is displayed. 6) Only the "third" button is displayed. Answer : 6 Consider the following tags and attributes of tags, which can be used with the <AAPLET> and </APPLET> tags? 1. CODEBASE 2. ALT 3. NAME 4. CLASS 5. JAVAC 6. HORIZONTALSPACE 7. VERTICALSPACE
Freshersworld.com Resource Center

46

First Job. Dream Job. Freshersworld.com


8. WIDTH 9. PARAM 10. JAR (multiple) 1) line 1, 2, 3 2) line 2, 5, 6, 7 3) line 3, 4, 5 4) line 8, 9, 10 5) line 8, 9 Answer : 1,5 Which of the following is a legal way to construct a RandomAccessFile: 1) RandomAccessFile("data", "r"); 2) RandomAccessFile("r", "data"); 3) RandomAccessFile("data", "read"); 4) RandomAccessFile("read", "data"); Answer : 1 Carefully examine the following code, When will the string "Hi there" be printed? public class StaticTest { static { System.out.println("Hi there"); } public void print() { System.out.println("Hello"); } public static void main(String args []) { StaticTest st1 = new StaticTest(); st1.print(); StaticTest st2 = new StaticTest(); st2.print(); } } 1) Never. 2) Each time a new instance is created. 3) Once when the class is first loaded into the Java virtual machine. 4) Only when the static method is called explicitly. Answer : 3 What is the result of the following program: public class Test { public static void main (String args []) { boolean a = false; if (a = true) System.out.println("Hello"); else System.out.println("Goodbye"); } } 1) Program produces no output but terminates correctly. 2) Program does not terminate. 3) Prints out "Hello" 4) Prints out "Goodbye" Answer : 3 Examine the following code, it includes an inner class, what is the result: public final class Test4 { class Inner { void test() { if (Test4.this.flag); {
Freshersworld.com Resource Center

47

First Job. Dream Job. Freshersworld.com


sample(); } } } private boolean flag = true; public void sample() { System.out.println("Sample"); } public Test4() { (new Inner()).test(); } public static void main(String args []) { new Test4(); } } 1) Prints out "Sample" 2) Program produces no output but terminates correctly. 3) Program does not terminate. 4) The program will not compile Answer : 1 Carefully examine the following class: public class Test5 { public static void main (String args []) { /* This is the start of a comment if (true) { Test5 = new test5(); System.out.println("Done the test"); } /* This is another comment */ System.out.println ("The end"); } } 1) Prints out "Done the test" and nothing else. 2) Program produces no output but terminates correctly. 3) Program does not terminate. 4) The program will not compile. 5) The program generates a runtime exception. 6) The program prints out "The end" and nothing else. 7) The program prints out "Done the test" and "The end" Answer : 6 What is the result of compiling and running the following applet: import java.applet.Applet; import java.awt.*; public class Sample extends Applet { private String text = "Hello World"; public void init() { add(new Label(text)); } public Sample (String string) { text = string; } } It is accessed form the following HTML page: <html> <title>Sample Applet</title> <body>
Freshersworld.com Resource Center

48

First Job. Dream Job. Freshersworld.com


<applet code="Sample.class" width=200 height=200></applet> </body> </html> 1) Prints "Hello World". 2) Generates a runtime error. 3) Does nothing. 4) Generates a compile time error. Answer : 2 What is the effect of compiling and (if possible) running this class: public class Calc { public static void main (String args []) { int total = 0; for (int i = 0, j = 10; total > 30; ++i, --j) { System.out.println(" i = " + i + " : j = " + j); total += (i + j); } System.out.println("Total " + total); } } 1) Produce a runtime error 2) Produce a compile time error 3) Print out "Total 0" 4) Generate the following as output: i = 0 : j = 10 i=1:j=9 i=2:j=8 Total 30 Answer : 3

Utility Package 1) What is the Vector class? ANSWER : The Vector class provides the capability to implement a growable array of objects. 2) What is the Set interface? ANSWER : The Set interface provides methods for accessing the elements of a finite mathematical set.Sets do not allow duplicate elements. 3) What is Dictionary class? ANSWER : The Dictionary class is the abstarct super class of Hashtable and Properties class.Dictionary provides the abstarct functions used to store and retrieve objects by key-value.This class allows any object to be used as a key or value. 4) What is the Hashtable class? ANSWER : The Hashtable class implements a hash table data structure. A hash table indexes and stores objects in a dictionary using hash codes as the objects' keys. Hash codes are integer values that identify objects. 5) What is the Properties class?
Freshersworld.com Resource Center

49

First Job. Dream Job. Freshersworld.com


Answer : The properties class is a subclass of Hashtable that can be read from or written to a stream.It also provides the capability to specify a set of default values to be used if a specified key is not found in the table. We have two methods load() and save(). 6) What changes are needed to make the following prg to compile? import java.util.*; class Ques{ public static void main (String args[]) { String s1 = "abc"; String s2 = "def"; Vector v = new Vector(); v.add(s1); v.add(s2); String s3 = v.elementAt(0) + v.elementAt(1); System.out.println(s3); } } ANSWER : Declare Ques as public B) Cast v.elementAt(0) to a String C) Cast v.elementAt(1) to an Object. D) Import java.lang ANSWER : B) Cast v.elementAt(0) to a String

8) What is the output of the prg. import java.util.*; class Ques{ public static void main (String args[]) { String s1 = "abc"; String s2 = "def"; Stack stack = new Stack(); stack.push(s1); stack.push(s2); try{ String s3 = (String) stack.pop() + (String) stack.pop() ; System.out.println(s3); }catch (EmptyStackException ex){} } } ANSWER : abcdef B) defabc C) abcabc D) defdef ANSWER : B) defabc 9) Which of the following may have duplicate elements? ANSWER : Collection B) List C) Map D) Set ANSWER : A and B Neither a Map nor a Set may have duplicate elements. 10) Can null value be added to a List? ANSWER : Yes.A Null value may be added to any List. 11) What is the output of the following prg. import java.util.*; class Ques{ public static void main (String args[]) { HashSet set = new HashSet(); String s1 = "abc"; String s2 = "def"; String s3 = ""; set.add(s1); set.add(s2);
Freshersworld.com Resource Center

50

First Job. Dream Job. Freshersworld.com


set.add(s1); set.add(s2); Iterator i = set.iterator(); while(i.hasNext()) { s3 += (String) i.next(); } System.out.println(s3); } } A) abcdefabcdef B) defabcdefabc C) fedcbafedcba D) defabc ANSWER : D) defabc. Sets may not have duplicate elements. 12) Which of the following java.util classes support internationalization? A) Locale B) ResourceBundle C) Country D) Language ANSWER : A and B . Country and Language are not java.util classes. 13) What is the ResourceBundle? The ResourceBundle class also supports internationalization. ResourceBundle subclasses are used to store locale-specific resources that can be loaded by a program to tailor the program's appearence to the paticular locale in which it is being run. Resource Bundles provide the capability to isolate a program's locale-specific resources in a standard and modular manner. 14) How are Observer Interface and Observable class, in java.util package, used? ANSWER : Objects that subclass the Observable class maintain a list of Observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects. 15) Which java.util classes and interfaces support event handling? ANSWER : The EventObject class and the EventListener interface support event processing. 16) Does java provide standard iterator functions for inspecting a collection of objects? ANSWER : The Enumeration interface in the java.util package provides a framework for stepping once through a collection of objects. We have two methods in that interface. public interface Enumeration { boolean hasMoreElements(); Object nextElement(); } 17) The Math.random method is too limited for my needs- How can I generate random numbers more flexibly? ANSWER : The random method in Math class provide quick, convienient access to random numbers, but more power and flexibility use the Random class in the java.util package. double doubleval = Math.random(); The Random class provide methods returning float, int, double, and long values. nextFloat() // type float; 0.0 <= value < 1.0 nextDouble() // type double; 0.0 <= value < 1.0 nextInt() // type int; Integer.MIN_VALUE <= value <= Integer.MAX_VALUE nextLong() // type long; Long.MIN_VALUE <= value <= Long.MAX_VALUE nextGaussian() // type double; has Gaussian("normal") distribution with mean 0.0 and standard deviation 1.0) Eg. Random r = new Random(); float floatval = r.nextFloat();

18) How can we get all public methods of an object dynamically? ANSWER : By using getMethods(). It return an array of method objects corresponding to the public methods of this class. getFields() returns an array of Filed objects corresponding to the public Fields(variables) of this class.
Freshersworld.com Resource Center

51

First Job. Dream Job. Freshersworld.com


getConstructors() returns an array of constructor objects corresponding to the public constructors of this class.

JDBC 1) What are the steps involved in establishing a connection? ANSWER : This involves two steps: (1) loading the driver and (2) making the connection. 2) How can you load the drivers? ANSWER : Loading the driver or drivers you want to use is very simple and involves just one line of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the following code will load it: Eg. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Your driver documentation will give you the class name to use. For instance, if the class name is jdbc.DriverXYZ , you would load the driver with the following line of code: Eg. Class.forName("jdbc.DriverXYZ"); 3) What Class.forName will do while loading drivers? ANSWER : It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS. 4) How can you make the connection? ANSWER : In establishing a connection is to have the appropriate driver connect to the DBMS. The following line of code illustrates the general idea: Eg. String url = "jdbc:odbc:Fred"; Connection con = DriverManager.getConnection(url, "Fernanda", "J8"); 5) How can you create JDBC statements? ANSWER : A Statement object is what sends your SQL statement to the DBMS. You simply create a Statement object and then execute it, supplying the appropriate execute method with the SQL statement you want to send. For a SELECT statement, the method to use is executeQuery. For statements that create or modify tables, the method to use is executeUpdate. Eg. It takes an instance of an active connection to create a Statement object. In the following example, we use our Connection object con to create the Statement object stmt : Statement stmt = con.createStatement(); 6) How can you retrieve data from the ResultSet? ANSWER : Step 1. JDBC returns results in a ResultSet object, so we need to declare an instance of the class ResultSet to hold our results. The following code demonstrates declaring the ResultSet object rs. Eg. ResultSet rs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES"); Step2. String s = rs.getString("COF_NAME"); The method getString is invoked on the ResultSet object rs , so getString will retrieve (get) the value stored in the column COF_NAME in the current row of rs 7) What are the different types of Statements? ANSWER : 1.Statement (use createStatement method) 2. Prepared Statement (Use prepareStatement method) and 3. Callable Statement (Use prepareCall) 8) How can you use PreparedStatement? ANSWER : This special type of statement is derived from the more general class, Statement.If you want to execute a Statement object many times, it will normally reduce execution time to use a PreparedStatement object instead. The advantage to this is that in most cases, this SQL statement will be sent to the DBMS right away, where it will be compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement 's SQL statement without having to compile it first.
Freshersworld.com Resource Center

52

First Job. Dream Job. Freshersworld.com


Eg. PreparedStatement updateSales = con.prepareStatement("UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?"); 9) What setAutoCommit does? ANSWER : When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and will be automatically committed right after it is executed. The way to allow two or more statements to be grouped into a transaction is to disable auto-commit mode Eg. con.setAutoCommit(false); Once auto-commit mode is disabled, no SQL statements will be committed until you call the method commit explicitly. Eg. con.setAutoCommit(false); PreparedStatement updateSales = con.prepareStatement( "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?"); updateSales.setInt(1, 50); updateSales.setString(2, "Colombian"); updateSales.executeUpdate(); PreparedStatement updateTotal = con.prepareStatement("UPDATE COFFEES SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?"); updateTotal.setInt(1, 50); updateTotal.setString(2, "Colombian"); updateTotal.executeUpdate(); con.commit(); con.setAutoCommit(true); 10) How to call a Strored Procedure from JDBC? ANSWER : The first step is to create a CallableStatement object. As with Statement an and PreparedStatement objects, this is done with an open Connection object. A CallableStatement object contains a call to a stored procedure; Eg. CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}"); ResultSet rs = cs.executeQuery(); 11) How to Retrieve Warnings? ANSWER : SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object Eg. SQLWarning warning = stmt.getWarnings(); if (warning != null) { System.out.println("\n---Warning---\n"); while (warning != null) { System.out.println("Message: " + warning.getMessage()); System.out.println("SQLState: " + warning.getSQLState()); System.out.print("Vendor error code: "); System.out.println(warning.getErrorCode()); System.out.println(""); warning = warning.getNextWarning(); } } 12) How can you Move the Cursor in Scrollable Result Sets ?

Freshersworld.com Resource Center

53

First Job. Dream Job. Freshersworld.com


ANSWER : One of the new features in the JDBC 2.0 API is the ability to move a result set's cursor backward as well as forward. There are also methods that let you move the cursor to a particular row and check the position of the cursor. Eg. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet srs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES"); The first argument is one of three constants added to the ResultSet API to indicate the type of a ResultSet object: TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE . The second argument is one of two ResultSet constants for specifying whether a result set is read-only or updatable: CONCUR_READ_ONLY and CONCUR_UPDATABLE . The point to remember here is that if you specify a type, you must also specify whether it is read-only or updatable. Also, you must specify the type first, and because both parameters are of type int , the compiler will not complain if you switch the order. Specifying the constant TYPE_FORWARD_ONLY creates a nonscrollable result set, that is, one in which the cursor moves only forward. If you do not specify any constants for the type and updatability of a ResultSet object, you will automatically get one that is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY 13) Whats the difference between TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE? ANSWER : You will get a scrollable ResultSet object if you specify one of these ResultSet constants.The difference between the two has to do with whether a result set reflects changes that are made to it while it is open and whether certain methods can be called to detect these changes. Generally speaking, a result set that is TYPE_SCROLL_INSENSITIVE does not reflect changes made while it is still open and one that is TYPE_SCROLL_SENSITIVE does. All three types of result sets will make changes visible if they are closed and then reopened Eg. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet srs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES"); srs.afterLast(); while (srs.previous()) { String name = srs.getString("COF_NAME"); float price = srs.getFloat("PRICE"); System.out.println(name + " " + price); } 14) How to Make Updates to Updatable Result Sets? ANSWER : Another new feature in the JDBC 2.0 API is the ability to update rows in a result set using methods in the Java programming language rather than having to send an SQL command. But before you can take advantage of this capability, you need to create a ResultSet object that is updatable. In order to do this, you supply the ResultSet constant CONCUR_UPDATABLE to the createStatement method. Eg. Connection con = DriverManager.getConnection("jdbc:mySubprotocol:mySubName"); Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet uprs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES"); Networking Concepts 1) The API doesn't list any constructors for InetAddress- How do I create an InetAddress instance? ANSWER : In case of InetAddress the three methods getLocalHost, getByName, getByAllName can be used to create instances. E.g. InetAddress add1;
Freshersworld.com Resource Center

54

First Job. Dream Job. Freshersworld.com


InetAddress add2; try{ add1 = InetAddress.getByName("java.sun.com"); add2 = InetAddress.getByName("199.22.22.22"); }catch(UnknownHostException e){} 2) Is it possible to get the Local host IP? ANSWER : Yes. Use InetAddress's getLocalHost method. 3) What's the Factory Method? ANSWER : Factory methods are merely a convention whereby static methods in a class return an instance of that class. The InetAddress class has no visible constructors. To create an InetAddress object, you have to use one of the available factory methods. In InetAddress the three methods getLocalHost, getByName, getByAllName can be used to create instances of InetAddress. 4) Whats the difference between TCP and UDP? ANSWER : These two protocols differ in the way they carry out the action of communicating. A TCP protocol establishes a two way connection between a pair of computers, while the UDP protocol is a one-way message sender. The common analogy is that TCP is like making a phone call and carrying on a two-way communication, while UDP is like mailing a letter. 5) What is the Proxy Server? ANSWER : A proxy server speaks the client side of a protocol to another server. This is often required when clients have certain restrictions on which servers they can connect to. And when several users are hitting a popular web site, a proxy server can get the contents of the web server's popular pages once, saving expensive internetwork transfers while providing faster access to those pages to the clients. Also, we can get multiple connections for a single server. 6) What are the seven layers of OSI model? ANSWER : Application, Presentation, Session, Transport, Network, DataLink, Physical Layer. What Transport Layer does? ANSWER : It ensures that the mail gets to its destination. If a packet fails to get its destination, it handles the process of notifying the sender and requesting that another packet be sent. 8) What is DHCP? ANSWER : Dynamic Host Configuration Protocol, a piece of the TCP/IP protocol suite that handles the automatic assignment of IP addresses to clients. 9) What is SMTP? ANSWER : Simple Mail Transmission Protocol, the TCP/IP Standard for Internet mails. SMTP exchanges mail between servers; contrast this with POP, which transmits mail between a server and a client. 10) In OSI N/w architecture, the dialogue control and token management are responsibilities of... Answer : Network b) Session c) Application d) DataLink ANSWER : b) Session Layer. 11) In OSI N/W Architecture, the routing is performed by ______ Answer : Network b) Session c) Application d) DataLink ANSWER : Answer : Network Layer. Networking What is the difference between URL instance and URLConnection instance? ANSWER : A URL instance represents the location of a resource, and a URLConnection instance represents a link for accessing or communicating with the resource at the location. 2) How do I make a connection to URL? ANSWER : You obtain a URL instance and then invoke openConnection on it. URLConnection is an abstract class, which means you can't directly create instances of it using a constructor. We have to invoke openConnection method on a URL instance, to get the right kind of connection for your URL. Eg. URL url; URLConnection connection; try{ url = new URL("..."); conection = url.openConnection(); }catch (MalFormedURLException e) { }
Freshersworld.com Resource Center

55

First Job. Dream Job. Freshersworld.com

3) What Is a Socket? A socket is one end-point of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent.Socket classes are used to represent the connection between a client program and a server program. The java.net package provides two classes--Socket and ServerSocket--which implement the client side of the connection and the server side of the connection, respectively. What information is needed to create a TCP Socket? ANSWER : The Local Systems IP Address and Port Number. And the Remote System's IPAddress and Port Number. 5) What are the two important TCP Socket classes? ANSWER : Socket and ServerSocket. ServerSocket is used for normal two-way socket communication. Socket class allows us to read and write through the sockets. getInputStream() and getOutputStream() are the two methods available in Socket class. When MalformedURLException and UnknownHostException throws? ANSWER : When the specified URL is not connected then the URL throw MalformedURLException and If InetAddress methods getByName and getLocalHost are unabletoresolve the host name they throwan UnknownHostException. Servlets 1) What is the servlet? ANSWER : Servlets are modules that extend request/response-oriented servers, such as Java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company's order database. Servlets are to servers what applets are to browsers. Unlike applets, however, servlets have no graphical user interface. 2) Whats the advantages using servlets than using CGI? ANSWER : Servlets provide a way to generate dynamic documents that is both easier to write and faster to run. Servlets also address the problem of doing server-side programming with platformspecific APIs: they are developed with the Java Servlet API, a standard Java extension. 3) What are the uses of Servlets? ANSWER : A servlet can handle multiple requests concurrently, and can synchronize requests. This allows servlets to support systems such as on-line conferencing. Servlets can forward requests to other servers and servlets.Thus servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task type or organizational boundaries. 4) Which pakage provides interfaces and classes for writing servlets? ANSWER : javax 5) Whats the Servlet Interfcae? ANSWER : The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or, more commonly, by extending a class that implements it such as HttpServlet. Servlets-->Generic Servlet-->HttpServlet-->MyServlet. The Servlet interface declares, but does not implement, methods that manage the servlet and its communications with clients. Servlet writers provide some or all of these methods when developing a servlet. 6) When a servlet accepts a call from a client, it receives two objects- What are they? ANSWER : ServeltRequest: Which encapsulates the communication from the client to the server. ServletResponse: Whcih encapsulates the communication from the servlet back to the client. ServletRequest and ServletResponse are interfaces defined by the javax.servlet package. 7) What information that the ServletRequest interface allows the servlet access to? ANSWER : Information such as the names of the parameters passed in by the client, the protocol (scheme) being used by the client, and the names of the remote host that made the request and the server that received it.

Freshersworld.com Resource Center

56

First Job. Dream Job. Freshersworld.com


The input stream, ServletInputStream.Servlets use the input stream to get data from clients that use application protocols such as the HTTP POST and PUT methods. 8) What information that the ServletResponse interface gives the servlet methods for replying to the client? ANSWER : It Allows the servlet to set the content length and MIME type of the reply. Provides an output stream, ServletOutputStream and a Writer through which the servlet can send the reply data. 9) What is the servlet Lifecycle? ANSWER : Each servlet has the same life cycle: A server loads and initializes the servlet (init()) The servlet handles zero or more client requests (service()) The server removes the servlet (destroy()) (some servers do this step only when they shut down) 10) How HTTP Servlet handles client requests? ANSWER : An HTTP Servlet handles client requests through its service method. The service method supports standard HTTP client requests by dispatching each request to a method designed to handle that request. 1

Encapsulation : Encapsulation is the mechanism that binds together code and the data it manipulates and keeps both safe from outside interference and misuse. Inheritance: Inheritance is the process by which one object acquires the properties of another object. Polymorphism: Polymorphism is a feature that allows one interface to be used for a general class of actions. The specific action is determined by the exact nature of actions. Code Blocks: Two or more statements which is allowed to be grouped into blocks of code is otherwise called as Code Blocks.This is done by enclosing the statements between opening and closing curly braces. Floating-point numbers: Floating-point numbers which is also known as real numbers, are used when evaluating expressions that require fractional precision. Unicode: Unicode defines a fully international character set that can represent all of the characters found in all human languages. It is a unification of dozens of character sets, such as Latin, Greek, Arabic and many more. Booleans: Java has a simple type called boolean, for logical values. It can have only on of two possible values, true or false. Casting: A cast is simply an explicit type conversion. To create a conversion between two incompatible types, you must use a cast. Arrays: An array is a group of like-typed variables that are referred to by a common name. Arrays offer a convenient means of grouping related information. Arrays of any type can be created and may have one or more dimension. Relational Operators: The relational operators determine the relationship that one operand has to the other. They determine the equality and ordering. 11.Short-Circuit Logical Operators: The secondary versions of the Boolean AND and OR operators are known as shortcircuit logical operators. It is represented by || and &&.. 12. Switch: The switch statement is Javas multiway branch statement. It provides an easy way to dispatch execution to different parts of your code based on the value of an
Freshersworld.com Resource Center

57

First Job. Dream Job. Freshersworld.com


experession. 13. Jump Statements: Jump statements are the statements which transfer control to another part of your program. Java Supports three jump statements: break, continue, and return. 14. Instance Variables: The data, or variable, defined within a class are called instance variable.

Freshersworld.com Resource Center

58

First Job. Dream Job. Freshersworld.com

RDBMS Concepts
1. What is database? A database is a logically coherent collection of data with some inherent meaning, representing some aspect of real world and which is designed, built and populated with data for a specific purpose.

2. What is DBMS? It is a collection of programs that enables user to create and maintain a database. In other words it is general-purpose software that provides the users with the processes of defining, constructing and manipulating the database for various applications. 3. What is a Database system? The database and DBMS software together is called as Database system. 4. 5. Advantages of DBMS? Redundancy is controlled. Unauthorised access is restricted. Providing multiple user interfaces. Enforcing integrity constraints. Providing backup and recovery. Disadvantage in File Processing System? Data redundancy & inconsistency. Difficult in accessing data. Data isolation. Data integrity. Concurrent access is not possible. Security Problems.

6. Describe the three levels of data abstraction? The are three levels of abstraction: Physical level: The lowest level of abstraction describes how data are stored. Logical level: The next higher level of abstraction, describes what data are stored in database and what relationship among those data. View level: The highest level of abstraction describes only part of entire database. 7. Define the "integrity rules" There are two Integrity rules. Entity Integrity: States that Primary key cannot have NULL value Referential Integrity: States that Foreign Key can be either a NULL value or should be Primary Key value of other relation.
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com

8. What is extension and intension? Extension It is the number of tuples present in a table at any instance. This is time dependent. Intension It is a constant value that gives the name, structure of table and the constraints laid on it. 9. What is System R? What are its two major subsystems? System R was designed and developed over a period of 1974-79 at IBM San Jose Research Center. It is a prototype and its purpose was to demonstrate that it is possible to build a Relational System that can be used in a real life environment to solve real life problems, with performance at least comparable to that of existing system. Its two subsystems are Research Storage System Relational Data System. 10. How is the data structure of System R different from the relational structure? Unlike Relational systems in System R Domains are not supported Enforcement of candidate key uniqueness is optional Enforcement of entity integrity is optional Referential integrity is not enforced 11. What is Data Independence? Data independence means that the application is independent of the storage structure and access strategy of data. In other words, The ability to modify the schema definition in one level should not affect the schema definition in the next higher level. Two types of Data Independence: Physical Data Independence: Modification in physical level should not affect the logical level. Logical Data Independence: Modification in logical level should affect the view level. NOTE: Logical Data Independence is more difficult to achieve 12. What is a view? How it is related to data independence? A view may be thought of as a virtual table, that is, a table that does not really exist in its own right but is instead derived from one or more underlying base table. In other words, there is no stored file that direct represents the view instead a definition of view is stored in data dictionary. Growth and restructuring of base tables is not reflected in views. Thus the view can insulate users from the effects of restructuring and growth in the database. Hence accounts for logical data independence.
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com

13. What is Data Model? A collection of conceptual tools for describing data, data relationships data semantics and constraints. 14. What is E-R model? This data model is based on real world that consists of basic objects called entities and of relationship among these objects. Entities are described in a database by a set of attributes. 15. What is Object Oriented model? This model is based on collection of objects. An object contains values stored in instance variables with in the object. An object also contains bodies of code that operate on the object. These bodies of code are called methods. Objects that contain same types of values and the same methods are grouped together into classes. 16. What is an Entity? It is a 'thing' in the real world with an independent existence. 17. What is an Entity type? It is a collection (set) of entities that have same attributes. 18. What is an Entity set? It is a collection of all entities of particular entity type in the database. 19. What is an Extension of entity type? The collections of entities of a particular entity type are grouped together into an entity set. 20. What is Weak Entity set? An entity set may not have sufficient attributes to form a primary key, and its primary key compromises of its partial key and primary key of its parent entity, then it is said to be Weak Entity set. 21. What is an attribute? It is a particular property, which describes the entity. 22. What is a Relation Schema and a Relation? A relation Schema denoted by R(A1, A2, , An) is made up of the relation name R and the list of attributes Ai that it contains. A relation is defined as a set of tuples. Let r be the relation which contains set tuples (t1, t2, t3, ..., tn). Each tuple is an ordered list of n-values t=(v1,v2, ..., vn). 23. What is degree of a Relation? It is the number of attribute of its relation schema.

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com 24. What is Relationship? It is an association among two or more entities. 25. What is Relationship set? The collection (or set) of similar relationships. 26. What is Relationship type? Relationship type defines a set of associations or a relationship set among a given set of entity types. 27. What is degree of Relationship type? It is the number of entity type participating. 25. What is DDL (Data Definition Language)? A data base schema is specifies by a set of definitions expressed by a special language called DDL. 26. What is VDL (View Definition Language)? It specifies user views and their mappings to the conceptual schema. 27. What is SDL (Storage Definition Language)? This language is to specify the internal schema. This language may specify the mapping between two schemas. 28. What is Data Storage - Definition Language? The storage structures and access methods used by database system are specified by a set of definition in a special type of DDL called data storage-definition language. 29. What is DML (Data Manipulation Language)? This language that enable user to access or manipulate data as organised by appropriate data model. Procedural DML or Low level: DML requires a user to specify what data are needed and how to get those data. Non-Procedural DML or High level: DML requires a user to specify what data are needed without specifying how to get those data. 31. What is DML Compiler? It translates DML statements in a query language into low-level instruction that the query evaluation engine can understand. 32. What is Query evaluation engine? It executes low-level instruction generated by compiler. 33. What is DDL Interpreter? It interprets DDL statements and record them in tables containing metadata.
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com

34. What is Record-at-a-time? The Low level or Procedural DML can specify and retrieve each record from a set of records. This retrieve of a record is said to be Record-at-a-time. 35. What is Set-at-a-time or Set-oriented? The High level or Non-procedural DML can specify and retrieve many records in a single DML statement. This retrieve of a record is said to be Set-at-a-time or Set-oriented. 36. What is Relational Algebra? It is procedural query language. It consists of a set of operations that take one or two relations as input and produce a new relation. 37. What is Relational Calculus? It is an applied predicate calculus specifically tailored for relational databases proposed by E.F. Codd. E.g. of languages based on it are DSL ALPHA, QUEL. 38. How does Tuple-oriented relational calculus differ from domain-oriented relational calculus The tuple-oriented calculus uses a tuple variables i.e., variable whose only permitted values are tuples of that relation. E.g. QUEL The domain-oriented calculus has domain variables i.e., variables that range over the underlying domains instead of over relation. E.g. ILL, DEDUCE. 39. What is normalization? It is a process of analysing the given relation schemas based on their Functional Dependencies (FDs) and primary key to achieve the properties Minimizing redundancy Minimizing insertion, deletion and update anomalies. 40. What is Functional Dependency? A Functional dependency is denoted by X Y between two sets of attributes X and Y that are subsets of R specifies a constraint on the possible tuple that can form a relation state r of R. The constraint is for any two tuples t1 and t2 in r if t1[X] = t2[X] then they have t1[Y] = t2[Y]. This means the value of X component of a tuple uniquely determines the value of component Y. 41. When is a functional dependency F said to be minimal? Every dependency in F has a single attribute for its right hand side. We cannot replace any dependency X A in F with a dependency Y A where Y is a proper subset of X and still have a set of dependency that is equivalent to F. We cannot remove any dependency from F and still have set of dependency that is equivalent to F. 42. What is Multivalued dependency?
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com Multivalued dependency denoted by X Y specified on relation schema R, where X and Y are both subsets of R, specifies the following constraint on any relation r of R: if two tuples t1 and t2 exist in r such that t1[X] = t2[X] then t3 and t4 should also exist in r with the following properties t3[x] = t4[X] = t1[X] = t2[X] t3[Y] = t1[Y] and t4[Y] = t2[Y] t3[Z] = t2[Z] and t4[Z] = t1[Z] where [Z = (R-(X U Y)) ] 43. What is Lossless join property? It guarantees that the spurious tuple generation does not occur with respect to relation schemas after decomposition. 44. What is 1 NF (Normal Form)? The domain of attribute must include only atomic (simple, indivisible) values. 45. What is Fully Functional dependency? It is based on concept of full functional dependency. A functional dependency X Y is full functional dependency if removal of any attribute A from X means that the dependency does not hold any more. 46. What is 2NF? A relation schema R is in 2NF if it is in 1NF and every non-prime attribute A in R is fully functionally dependent on primary key. 47. What is 3NF? A relation schema R is in 3NF if it is in 2NF and for every FD X A either of the following is true X is a Super-key of R. A is a prime attribute of R. In other words, if every non prime attribute is non-transitively dependent on primary key. 48. What is BCNF (Boyce-Codd Normal Form)? A relation schema R is in BCNF if it is in 3NF and satisfies an additional constraint that for every FD X A, X must be a candidate key. 49. What is 4NF? A relation schema R is said to be in 4NF if for every Multivalued dependency X Y that holds over R, one of following is true X is subset or equal to (or) XY = R. X is a super key. 50. What is 5NF? A Relation schema R is said to be 5NF if for every join dependency {R1, R2, ..., Rn} that holds R, one the following is true
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com Ri = R for some i. The join dependency is implied by the set of FD, over R in which the left side is key of R. 51. What is Domain-Key Normal Form? A relation is said to be in DKNF if all constraints and dependencies that should hold on the the constraint can be enforced by simply enforcing the domain constraint and key constraint on the relation. 52. What are partial, alternate,, artificial, compound and natural key? Partial Key: It is a set of attributes that can uniquely identify weak entities and that are related to same owner entity. It is sometime called as Discriminator. Alternate Key: All Candidate Keys excluding the Primary Key are known as Alternate Keys. Artificial Key: If no obvious key, either stand alone or compound is available, then the last resort is to simply create a key, by assigning a unique number to each record or occurrence. Then this is known as developing an artificial key. Compound Key: If no single data element uniquely identifies occurrences within a construct, then combining multiple elements to create a unique identifier for the construct is known as creating a compound key. Natural Key: When one of the data elements stored within a construct is utilized as the primary key, then it is called the natural key. 53. What is indexing and what are the different kinds of indexing? Indexing is a technique for determining how quickly specific data can be found. Types: Binary search style indexing B-Tree indexing Inverted list indexing Memory resident table Table indexing 54. What is system catalog or catalog relation? How is better known as? A RDBMS maintains a description of all the data that it contains, information about every relation and index that it contains. This information is stored in a collection of relations maintained by the system called metadata. It is also called data dictionary. 55. What is meant by query optimization? The phase that identifies an efficient execution plan for evaluating a query that has the least estimated cost is referred to as query optimization.
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com

56. What is join dependency and inclusion dependency? Join Dependency: A Join dependency is generalization of Multivalued dependency.A JD {R1, R2, ..., Rn} is said to hold over a relation R if R1, R2, R3, ..., Rn is a lossless-join decomposition of R . There is no set of sound and complete inference rules for JD. Inclusion Dependency: An Inclusion Dependency is a statement of the form that some columns of a relation are contained in other columns. A foreign key constraint is an example of inclusion dependency. 57. What is durability in DBMS? Once the DBMS informs the user that a transaction has successfully completed, its effects should persist even if the system crashes before all its changes are reflected on disk. This property is called durability. 58. What do you mean by atomicity and aggregation? Atomicity: Either all actions are carried out or none are. Users should not have to worry about the effect of incomplete transactions. DBMS ensures this by undoing the actions of incomplete transactions. Aggregation: A concept which is used to model a relationship between a collection of entities and relationships. It is used when we need to express a relationship among relationships. 59. What is a Phantom Deadlock? In distributed deadlock detection, the delay in propagating local information might cause the deadlock detection algorithms to identify deadlocks that do not really exist. Such situations are called phantom deadlocks and they lead to unnecessary aborts. 60. What is a checkpoint and When does it occur? A Checkpoint is like a snapshot of the DBMS state. By taking checkpoints, the DBMS can reduce the amount of work to be done during restart in the event of subsequent crashes. 61. What are the different phases of transaction? Different phases are Analysis phase Redo Phase Undo phase 62. What do you mean by flat file database?

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com It is a database in which there are no programs or user access languages. It has no cross-file capabilities but is user-friendly and provides user-interface management. 63. What is "transparent DBMS"? It is one, which keeps its Physical Structure hidden from user. 64. Brief theory of Network, Hierarchical schemas and their properties Network schema uses a graph data structure to organize records example for such a database management system is CTCG while a hierarchical schema uses a tree data structure example for such a system is IMS. 65. What is a query? A query with respect to DBMS relates to user commands that are used to interact with a data base. The query language can be classified into data definition language and data manipulation language. 66. What do you mean by Correlated subquery? Subqueries, or nested queries, are used to bring back a set of rows to be used by the parent query. Depending on how the subquery is written, it can be executed once for the parent query or it can be executed once for each row returned by the parent query. If the subquery is executed for each row of the parent, this is called a correlated subquery. A correlated subquery can be easily identified if it contains any references to the parent subquery columns in its WHERE clause. Columns from the subquery cannot be referenced anywhere else in the parent query. The following example demonstrates a non-correlated subquery. E.g. Select * From CUST Where '10/03/1990' IN (Select ODATE From ORDER Where CUST.CNUM = ORDER.CNUM) 67. What are the primitive operations common to all record management systems? Addition, deletion and modification. 68. Name the buffer in which all the commands that are typed in are stored Edit Buffer 69. What are the unary operations in Relational Algebra? PROJECTION and SELECTION. 70. Are the resulting relations of PRODUCT and JOIN operation the same? No. PRODUCT: Concatenation of every row in one relation with every row in another. JOIN: Concatenation of rows from one relation and related rows from another. 71. What is RDBMS KERNEL?

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com Two important pieces of RDBMS architecture are the kernel, which is the software, and the data dictionary, which consists of the system-level data structures used by the kernel to manage the database You might think of an RDBMS as an operating system (or set of subsystems), designed specifically for controlling data access; its primary functions are storing, retrieving, and securing data. An RDBMS maintains its own list of authorized users and their associated privileges; manages memory caches and paging; controls locking for concurrent resource usage; dispatches and schedules user requests; and manages space usage within its table-space structures . 72. Name the sub-systems of a RDBMS I/O, Security, Language Processing, Process Control, Storage Management, Logging and Recovery, Distribution Control, Transaction Control, Memory Management, Lock Management 73. Which part of the RDBMS takes care of the data dictionary? How Data dictionary is a set of tables and database objects that is stored in a special area of the database and maintained exclusively by the kernel. 74. What is the job of the information stored in data-dictionary? The information in the data dictionary validates the existence of the objects, provides access to them, and maps the actual physical storage location. 75. Not only RDBMS takes care of locating data it also determines an optimal access path to store or retrieve the data 76. How do you communicate with an RDBMS? You communicate with an RDBMS using Structured Query Language (SQL) 77. Define SQL and state the differences between SQL and other conventional programming Languages SQL is a nonprocedural language that is designed specifically for data access operations on normalized relational database structures. The primary difference between SQL and other conventional programming languages is that SQL statements specify what data operations should be performed rather than how to perform them. 78. Name the three major set of files on disk that compose a database in Oracle
There are three major sets of files on disk that compose a database. All the files are binary. These are

Database files Control files Redo logs The most important of these are the database files where the actual data resides. The control files and the redo logs support the functioning of the architecture itself.
All three sets of files must be present, open, and available to Oracle for any data on the database to be useable. Without these files, you cannot access the database, and the database administrator might have to recover some or all of the database using a backup, if there is one.

Freshersworld.com Resource Center

10

First Job. Dream Job. Freshersworld.com

79. What is an Oracle Instance? The Oracle system processes, also known as Oracle background processes, provide functions for the user processesfunctions that would otherwise be done by the user processes themselves Oracle database-wide system memory is known as the SGA, the system global area or shared global area. The data and control structures in the SGA are shareable, and all the Oracle background processes and user processes can use them. The combination of the SGA and the Oracle background processes is known as an Oracle instance 80. What are the four Oracle system processes that must always be up and running for the database to be useable The four Oracle system processes that must always be up and running for the database to be useable include DBWR (Database Writer), LGWR (Log Writer), SMON (System Monitor), and PMON (Process Monitor). 81. What are database files, control files and log files. How many of these files should a database have at least? Why? Database Files The database files hold the actual data and are typically the largest in size. Depending on their sizes, the tables (and other objects) for all the user accounts can go in one database filebut that's not an ideal situation because it does not make the database structure very flexible for controlling access to storage for different users, putting the database on different disk drives, or backing up and restoring just part of the database. You must have at least one database file but usually, more than one files are used. In terms of accessing and using the data in the tables and other objects, the number (or location) of the files is immaterial. The database files are fixed in size and never grow bigger than the size at which they were created Control Files The control files and redo logs support the rest of the architecture. Any database must have at least one control file, although you typically have more than one to guard against loss. The control file records the name of the database, the date and time it was created, the location of the database and redo logs, and the synchronization information to ensure that all three sets of files are always in step. Every time you add a new database or redo log file to the database, the information is recorded in the control files.

Freshersworld.com Resource Center

11

First Job. Dream Job. Freshersworld.com Redo Logs Any database must have at least two redo logs. These are the journals for the database; the redo logs record all changes to the user objects or system objects. If any type of failure occurs, the changes recorded in the redo logs can be used to bring the database to a consistent state without losing any committed transactions. In the case of non-data loss failure, Oracle can apply the information in the redo logs automatically without intervention from the DBA. The redo log files are fixed in size and never grow dynamically from the size at which they were created. 82. What is ROWID? The ROWID is a unique database-wide physical address for every row on every table. Once assigned (when the row is first inserted into the database), it never changes until the row is deleted or the table is dropped. The ROWID consists of the following three components, the combination of which uniquely identifies the physical storage location of the row. Oracle database file number, which contains the block with the rows Oracle block address, which contains the row The row within the block (because each block can hold many rows) The ROWID is used internally in indexes as a quick means of retrieving rows with a particular key value. Application developers also use it in SQL statements as a quick way to access a row once they know the ROWID 83. What is Oracle Block? Can two Oracle Blocks have the same address? Oracle "formats" the database files into a number of Oracle blocks when they are first createdmaking it easier for the RDBMS software to manage the files and easier to read data into the memory areas. The block size should be a multiple of the operating system block size. Regardless of the block size, the entire block is not available for holding data; Oracle takes up some space to manage the contents of the block. This block header has a minimum size, but it can grow. These Oracle blocks are the smallest unit of storage. Increasing the Oracle block size can improve performance, but it should be done only when the database is first created. Each Oracle block is numbered sequentially for each database file starting at 1. Two blocks can have the same block address if they are in different database files. 84. What is database Trigger? A database trigger is a PL/SQL block that can defined to automatically execute for insert, update, and delete statements against a table. The trigger can e defined to execute once for the entire statement or once for every row that is inserted, updated, or deleted. For any one table, there are twelve events for which you can define database triggers. A database trigger can call database procedures that are also written in PL/SQL. 85. Name two utilities that Oracle provides, which are use for backup and recovery.
Freshersworld.com Resource Center

12

First Job. Dream Job. Freshersworld.com Along with the RDBMS software, Oracle provides two utilities that you can use to back up and restore the database. These utilities are Export and Import. The Export utility dumps the definitions and data for the specified part of the database to an operating system binary file. The Import utility reads the file produced by an export, recreates the definitions of objects, and inserts the data If Export and Import are used as a means of backing up and recovering the database, all the changes made to the database cannot be recovered since the export was performed. The best you can do is recover the database to the time when the export was last performed. 86. What are stored-procedures? And what are the advantages of using them. Stored procedures are database objects that perform a user defined operation. A stored procedure can have a set of compound SQL statements. A stored procedure executes the SQL commands and returns the result to the client. Stored procedures are used to reduce network traffic. 87. How are exceptions handled in PL/SQL? Give some of the internal exceptions' name PL/SQL exception handling is a mechanism for dealing with run-time errors encountered during procedure execution. Use of this mechanism enables execution to continue if the error is not severe enough to cause procedure termination. The exception handler must be defined within a subprogram specification. Errors cause the program to raise an exception with a transfer of control to the exception-handler block. After the exception handler executes, control returns to the block in which the handler was defined. If there are no more executable statements in the block, control returns to the caller. User-Defined Exceptions PL/SQL enables the user to define exception handlers in the declarations area of subprogram specifications. User accomplishes this by naming an exception as in the following example: ot_failure EXCEPTION; In this case, the exception name is ot_failure. Code associated with this handler is written in the EXCEPTION specification area as follows: EXCEPTION when OT_FAILURE then out_status_code := g_out_status_code; out_msg := g_out_msg;
The following is an example of a subprogram exception:

EXCEPTION when NO_DATA_FOUND then g_out_status_code := 'FAIL'; RAISE ot_failure; Within this exception is the RAISE statement that transfers control back to the ot_failure exception handler. This technique of raising the exception is used to invoke all user-defined exceptions. System-Defined Exceptions
Freshersworld.com Resource Center

13

First Job. Dream Job. Freshersworld.com Exceptions internal to PL/SQL are raised automatically upon error. NO_DATA_FOUND is a system-defined exception. Table below gives a complete list of internal exceptions. PL/SQL internal exceptions. Exception Name CURSOR_ALREADY_OPEN DUP_VAL_ON_INDEX INVALID_CURSOR INVALID_NUMBER LOGIN_DENIED NO_DATA_FOUND NOT_LOGGED_ON PROGRAM_ERROR STORAGE_ERROR TIMEOUT_ON_RESOURCE TOO_MANY_ROWS TRANSACTION_BACKED_OUT VALUE_ERROR ZERO_DIVIDE Oracle Error ORA-06511 ORA-00001 ORA-01001 ORA-01722 ORA-01017 ORA-01403 ORA-01012 ORA-06501 ORA-06500 ORA-00051 ORA-01422 ORA-00061 ORA-06502 ORA-01476

In addition to this list of exceptions, there is a catch-all exception named OTHERS that traps all errors for which specific error handling has not been established. 88. Does PL/SQL support "overloading"? Explain The concept of overloading in PL/SQL relates to the idea that you can define procedures and functions with the same name. PL/SQL does not look only at the referenced name, however, to resolve a procedure or function call. The count and data types of formal parameters are also considered.
PL/SQL also attempts to resolve any procedure or function calls in locally defined packages before looking at globally defined packages or internal functions. To further ensure calling the proper procedure, you can use the dot notation. Prefacing a procedure or function name with the package name fully qualifies any procedure or function reference.

89. Tables derived from the ERD a) Are totally unnormalised b) Are always in 1NF c) Can be further denormalised d) May have multi-valued attributes (b) Are always in 1NF 90. Spurious tuples may occur due to i. Bad normalization ii. Theta joins iii. Updating tables from join
Freshersworld.com Resource Center

14

First Job. Dream Job. Freshersworld.com a) i & ii c) i & iii b) ii & iii d) ii & iii

(a) i & iii because theta joins are joins made on keys that are not primary keys. 91. A B C is a set of attributes. The functional dependency is as follows AB -> B AC -> C C -> B a) is in 1NF b) is in 2NF c) is in 3NF d) is in BCNF (a) is in 1NF since (AC)+ = { A, B, C} hence AC is the primary key. Since C B is a FD given, where neither C is a Key nor B is a prime attribute, this it is not in 3NF. Further B is not functionally dependent on key AC thus it is not in 2NF. Thus the given FDs is in 1NF. 92. In mapping of ERD to DFD a) entities in ERD should correspond to an existing entity/store in DFD b) entity in DFD is converted to attributes of an entity in ERD c) relations in ERD has 1 to 1 correspondence to processes in DFD d) relationships in ERD has 1 to 1 correspondence to flows in DFD (a) entities in ERD should correspond to an existing entity/store in DFD 93. A dominant entity is the entity a) on the N side in a 1 : N relationship b) on the 1 side in a 1 : N relationship c) on either side in a 1 : 1 relationship d) nothing to do with 1 : 1 or 1 : N relationship (b) on the 1 side in a 1 : N relationship 94. Select 'NORTH', CUSTOMER From CUST_DTLS Where REGION = 'N' Order By CUSTOMER Union Select 'EAST', CUSTOMER From CUST_DTLS Where REGION = 'E' Order By CUSTOMER The above is a) Not an error b) Error - the string in single quotes 'NORTH' and 'SOUTH' c) Error - the string should be in double quotes d) Error - ORDER BY clause

Freshersworld.com Resource Center

15

First Job. Dream Job. Freshersworld.com (d) Error - the ORDER BY clause. Since ORDER BY clause cannot be used in UNIONS 95. What is Storage Manager? It is a program module that provides the interface between the low-level data stored in database, application programs and queries submitted to the system. 96. What is Buffer Manager? It is a program module, which is responsible for fetching data from disk storage into main memory and deciding what data to be cache in memory. 97. What is Transaction Manager? It is a program module, which ensures that database, remains in a consistent state despite system failures and concurrent transaction execution proceeds without conflicting. 98. What is File Manager? It is a program module, which manages the allocation of space on disk storage and data structure used to represent information stored on a disk. 99. What is Authorization and Integrity manager? It is the program module, which tests for the satisfaction of integrity constraint and checks the authority of user to access data. 100. What are stand-alone procedures? Procedures that are not part of a package are known as stand-alone because they independently defined. A good example of a stand-alone procedure is one written in a SQL*Forms application. These types of procedures are not available for reference from other Oracle tools. Another limitation of stand-alone procedures is that they are compiled at run time, which slows execution. 101. What are cursors give different types of cursors. PL/SQL uses cursors for all database information accesses statements. The language supports the use two types of cursors Implicit Explicit 102. What is cold backup and hot backup (in case of Oracle)? Cold Backup: It is copying the three sets of files (database files, redo logs, and control file) when the instance is shut down. This is a straight file copy, usually from the disk directly to tape. You must shut down the instance to guarantee a consistent copy. If a cold backup is performed, the only option available in the event of data file loss is restoring all the files from the latest backup. All work performed on the database since the last backup is lost.
Freshersworld.com Resource Center

16

First Job. Dream Job. Freshersworld.com Hot Backup: Some sites (such as worldwide airline reservations systems) cannot shut down the database while making a backup copy of the files. The cold backup is not an available option. So different means of backing up database must be used the hot backup. Issue a SQL command to indicate to Oracle, on a tablespace-by-tablespace basis, that the files of the tablespace are to backed up. The users can continue to make full use of the files, including making changes to the data. Once the user has indicated that he/she wants to back up the tablespace files, he/she can use the operating system to copy those files to the desired backup destination. The database must be running in ARCHIVELOG mode for the hot backup option. If a data loss failure does occur, the lost database files can be restored using the hot backup and the online and offline redo logs created since the backup was done. The database is restored to the most consistent state without any loss of committed transactions. 103. What are Armstrong rules? How do we say that they are complete and/or sound The well-known inference rules for FDs Reflexive rule : If Y is subset or equal to X then X Y. Augmentation rule: If X Y then XZ YZ. Transitive rule: If {X Y, Y Z} then X Z. Decomposition rule : If X YZ then X Y. Union or Additive rule: If {X Y, X Z} then X YZ. Pseudo Transitive rule : If {X Y, WY Z} then WX Z. Of these the first three are known as Amstrong Rules. They are sound because it is enough if a set of FDs satisfy these three. They are called complete because using these three rules we can generate the rest all inference rules. 104. How can you find the minimal key of relational schema? Minimal key is one which can identify each tuple of the given relation schema uniquely. For finding the minimal key it is required to find the closure that is the set of all attributes that are dependent on any given set of attributes under the given set of functional dependency. Algo. I Determining X+, closure for X, given set of FDs F 1. Set X+ = X 2. Set Old X+ = X+ 3. For each FD Y Z in F and if Y belongs to X+ then add + Z to X
Freshersworld.com Resource Center

17

First Job. Dream Job. Freshersworld.com 4. Repeat steps 2 and 3 until Old X+ = X+ Algo.II Determining minimal K for relation schema R, given set of FDs F 1. Set K to R that is make K a set of all attributes in R 2. For each attribute A in K a. Compute (K A)+ with respect to F b. If (K A)+ = R then set K = (K A)+

105.

What do you understand by dependency preservation? Given a relation R and a set of FDs F, dependency preservation states that the closure of the union of the projection of F on each decomposed relation Ri is equal to the closure of F. i.e., ((R1(F)) U U (Rn(F)))+ = F+ if decomposition is not dependency preserving, then some dependency is lost in the decomposition. 106. What is meant by Proactive, Retroactive and Simultaneous Update. Proactive Update: The updates that are applied to database before it becomes effective in real world . Retroactive Update: The updates that are applied to database after it becomes effective in real world . Simulatneous Update: The updates that are applied to database at the same time when it becomes effective in real world . 107. What are the different types of JOIN operations? Equi Join: This is the most common type of join which involves only equality comparisions. The disadvantage in this type of join is that there

Freshersworld.com Resource Center

18

First Job. Dream Job. Freshersworld.com

Freshersworld.com Resource Center

19

Q. What is database? A. A database is a logically coherent collection of data with some inherent meaning, representing some aspect of real world and which is designed, built and populated with data for a specific purpose. Q. What is DBMS? A. It is a collection of programs that enables user to create and maintain a database. In other words it is general-purpose software that provides the users with the processes of defining, constructing and manipulating the database for various applications Q. Advantages of DBMS??Redundancy is controlled. A. Unauthorised access is restricted. Providing multiple user interfaces. Enforcing integrity constraints. Providing backup and recovery Q. What is Object Oriented model? A. This model is based on collection of objects. An object contains values stored in instance variables with in the object. An object also contains bodies of code that operate on the object. These bodies of code are called methods. Objects that contain same types of values and the same methods are grouped together into classes Q. What are partial, alternate,, artificial, compound and natural key? A. Partial Key: It is a set of attributes that can uniquely identify weak entities and that are related to same owner entity. It is sometime called as Discriminator. Alternate Key: All Candidate Keys excluding the Primary Key are known as Alternate Keys.

Artificial Key: If no obvious key, either stand alone or compound is available, then the last resort is to simply create a key, by assigning a unique number to each record or occurrence. Then this is known as developing an artificial key. Compound Key: If no single data element uniquely identifies occurrences within a construct, then combining multiple elements to create a unique identifier for the construct is known as creating a compound key. Natural Key: When one of the data elements stored within a construct is utilized as the primary key, then it is called the natural key Q. What is Data Model? A. A collection of conceptual tools for describing data, data relationships data semantics and constraints Q. Whats the difference between a primary key and a unique key? A. Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesnt allow NULLs, but unique key allows one NULL only. Q. What is E-R model? A. This data model is based on real world that consists of basic objects called entities and of relationship among these objects. Entities are described in a database by a set of attributes Q. What is an Entity? A. It is a thing in the real world with an independent existence Q. What is an Entity type? A. It is a collection (set) of entities that have same attributes.

Q.What is Weak Entity set? An entity set may not have sufficient attributes to form a primary key, and its primary key compromises of its partial key and primary key of its parent entity, then it is said to be Weak Entity set. Q.What is an attribute? It is a particular property, which describes the entity Q. What is degree of a Relation? A. It is the number of attribute of its relation schema. Q. What is Relationship set? A. The collection (or set) of similar relationships Q. What is Relationship type? A. Relationship type defines a set of associations or a relationship set among a given set of entity types. Q. What is degree of Relationship type? A. It is the number of entity type participating Q. What is DDL (Data Definition Language)? A. A data base schema is specifies by a set of definitions expressed by a special language called DDL. Q. What is VDL (View Definition Language)? A. It specifies user views and their mappings to the conceptual schema. Q. What is SDL (Storage Definition Language)? A. This language is to specify the internal schema. This language may specify the mapping between two schemas. Q. What is Data Storage - Definition Language?

A. The storage structures and access methods used by database system are specified by a set of definition in a special type of DDL called data storagedefinition language Q. What is DML (Data Manipulation Language)? This language that enable user to access or manipulate data as organised by appropriate data model. Procedural DML or Low level: DML requires a user to specify what data are needed and how to get those data. Non-Procedural DML or High level: DML requires a user to specify what data are needed without specifying how to get those data. Q. What is DML Compiler? A. It translates DML statements in a query language into low-level instruction that the query evaluation engine can understand Q. What is Query evaluation engine? A. It executes low-level instruction generated by compiler. Q. What is DDL Interpreter? A. It interprets DDL statements and record them in tables containing metadata Q. What is Record-at-a-time? A. The Low level or Procedural DML can specify and retrieve each record from a set of records. This retrieve of a record is said to be Record-at-a-time. Q. What is Relational Calculus? A. It is an applied predicate calculus specifically tailored for relational databases proposed by E.F. Codd. E.g. of languages based on it are DSL ALPHA, QUEL. Q. What is Relational Algebra? A. It is procedural query language. It consists of a set of operations that take one or two relations as input and produce a new relation.

Q. What is 1 NF (Normal Form)? A. The domain of attribute must include only atomic (simple, indivisible) values Q. What is 2NF? A. A relation schema R is in 2NF if it is in 1NF and every non-prime attribute A in R is fully functionally dependent on primary key. Q. What is 3NF? A. A relation schema R is in 3NF if it is in 2NF and for every FD X A either of the following is true X is a Super-key of R. A is a prime attribute of R. In other words, if every non prime attribute is non-transitively dependent on primary key. Q. What is 4NF? A. A relation schema R is said to be in 4NF if for every Multivalued dependency X Y that holds over R, one of following is trueX is subset or equal to (or) XY = R.X is a super key.

Q. What is 5NF? A. A Relation schema R is said to be 5NF if for every join dependency {R1, R2, , Rn} that holds R, one the following is true Ri = R for some i.The join dependency is implied by the set of FD, over R in which the left side is key of R. Q. What is BCNF (Boyce-Codd Normal Form)? A. A relation schema R is in BCNF if it is in 3NF and satisfies an additional constraint that for every FD X A, X must be a candidate key.

Q. What is Fully Functional dependency?

A. It is based on concept of full functional dependency. A functional dependency X Y is full functional dependency if removal of any attribute A from X means that the dependency does not hold any more. Q. What is Lossless join property? A. It guarantees that the spurious tuple generation does not occur with respect to relation schemas after decomposition Q. What is durability in DBMS? A. Once the DBMS informs the user that a transaction has successfully completed, its effects should persist even if the system crashes before all its changes are reflected on disk. This property is called durability. Q. What is Boyce Codd Normal form? A. A relation schema R is in BCNF with respect to a set F of functional dependencies if for all functional dependencies in F+ of the form a->b, where a and b is a subset of R, at least one of the following holds: a->b is a trivial functional dependency (b is a subset of a) a is a superkey for schema R Q. What is indexing and what are the different kinds of indexing? Indexing is a technique for determining how quickly specific data can be found. Types: Binary search style indexing B-Tree indexing Inverted list indexing Memory resident table Table indexing Q. Give the two types of tables involved in producing a star schema and the type of data they hold. A. Fact tables and dimension tables. A fact table contains measurements while dimension tables will contain data that will help describe the fact tables.

Q. What is the difference among dropping a table, truncating a table and deleting all records from a table. A. Drop Table - will remove the existence of the table from the database along with its data and structure and all the constraints. The table will be no longer available. Truncate Table - will remove all the rows (only the rows) from a table. it will not delete the table. Its a DDL statement that means the deleted rows cannot be reverted back by ROLLBACK statement; Delete Table - is a DML statement which will delete rows from a table according to the matching criteria mentions in the where clause. And these rows can be reverted back by ROLLBACK statement if COMMIT is not fired. Q. What is SQL*Loader? A. Oracle database. One can load data into an Oracle database by using the sqlldr (sqlload on some platforms) utility. Q. How to create a database link? A. A database link is an object in the local database that allows you to access objects on a remote database or to mount a secondary database in read-only mode. CREATE [PUBLIC] DATABASE LINK dblink [CONNECT TO user IDENTIFIED BY password] [USING connect_string] Q. What are the Large object types suported by Oracle? A. These are the large object type supported bye oracle CLOB and LONG for large fixed-width character data NCLOB for large fixed-width national character set data BLOB and LONG RAW for storing unstructured data BFILE for storing unstructured data in operating system files Q. What are the different types of joins?

A. Different Types of JoinsInner Join Outer Join - Right Outer Join & Left Outer Join Cross Join Q. What is snapshot log? A. It is a table that maintains a record of modifications to the master table in a snapshot. It is stored in the same database as master table and is only available for simple snapshots. It should be created before creating snapshots. Q. Explain the difference between MyISAM Static and MyISAM Dynamic. A. In MyISAM static all the fields have fixed width. The Dynamic MyISAM table would include fields such as TEXT, BLOB, etc. to accommodate the data types with various lengths. MyISAM Static would be easier to restore in case of corruption, since even though you might lose some data, you know exactly where to look for the beginning of the next record. Q. What is a SQL * NET? A. SQL *NET is ORACLEs mechanism for interfacing with the communication protocols used by the networks that facilitate distributed processing and distributed databases. It is used in Clint-Server and ServerServer communications Q. How can you Enforce Referential Integrity in snapshots? A. Time the references to occur when master tables are not in use. Peform the reference the manually immdiately locking the master tables. We can join tables in snopshots by creating a complex snapshots that will based on the master tables. Q. What is Two-Phase Commit? A. Two-phase commit is mechanism that guarantees a distributed transaction either commits on all involved nodes or rolls back on all involved nodes to maintain data consistency across the global distributed database. It has two phase, a Prepare Phase and a Commit Phase. Q. What is a cluster Key?

A. The related columns of the tables are called the cluster key. The cluster key is indexed using a cluster index and its value is stored only once for multiple tables in the cluster Q. What is a deadlock? A. Two processes waiting to update the rows of a table which are locked by the other process then deadlock arises. In a database environment this will often happen because of not issuing proper row lock commands. Poor design of front-end application may cause this situation and the performance of server will reduce drastically. These locks will be released automatically when a commit/rollback operation performed or any one of this processes being killed externally. Q. What is Read-Only Transaction? A. A Read-Only transaction ensures that the results of each query executed in the transaction are consistent with respect to the same point in time. Q. Define Transaction? A. A Transaction is a logical unit of work that comprises one or more SQL statements executed by a single user Q. What is Rule-based approach to optimization? A. Choosing an executing plan based on the access paths available and the ranks of these access paths. Q. What is Cost-based approach to optimization? A. Considering available access paths and determining the most efficient execution plan based on statistics in the data dictionary for the tables accessed by the statement and their associated clusters and indexes Q. What does Commit do? A. Commit makes permanent the changes resulting from all SQL statements in the transaction. The changes made by the SQL statements of a transaction become visible to other user sessions transactions that start only after transaction is committed.

Q. What is meant by Proactive, Retroactive and Simultaneous Update. A. Proactive Update: The updates that are applied to database before it becomes effective in real world . Retroactive Update: The updates that are applied to database after it becomes effective in real world . Simulatneous Update: The updates that are applied to database at the same time when it becomes effective in real world Q. What is cold backup and hot backup (in case of Oracle)? A. Cold Backup: It is copying the three sets of files (database files, redo logs, and control file) when the instance is shut down. This is a straight file copy, usually from the disk directly to tape. You must shut down the instance to guarantee a consistent copy. Hot Backup: Some sites (such as worldwide airline reservations systems) cannot shut down the database while making a backup copy of the files. The cold backup is not an available option Q. What is Authorization and Integrity manager? A. It is the program module, which tests for the satisfaction of integrity constraint and checks the authority of user to access data. Q. What is an Oracle Instance? A. The combination of the SGA and the Oracle background processes is known as an Oracle instance Q. What is Domain-Key Normal Form? A. A relation is said to be in DKNF if all constraints and dependencies that should hold on the the constraint can be

enforced by simply enforcing the domain constraint and key constraint on the relation. <!--[if !supportLineBreakNewLine]--> <!--[endif]--> Q. What is Fully Functional dependency? A. It is based on concept of full functional dependency. A functional dependency X Y is full functional dependency if removal of any attribute A from X means that the dependency does not hold any more. Q. How does Tuple-oriented relational calculus differ from domain-oriented relational calculus? A. The tuple-oriented calculus uses a tuple variables i.e., variable whose only permitted values are tuples of that relation. E.g. QUEL The domain-oriented calculus has domain variables i.e., variables that range over the underlying domains instead of over relation. E.g. ILL, DEDUCE Q. What is System R? A. System R was designed and developed over a period of 1974-79 at IBM San Jose Research Center. It is a prototype and its purpose was to demonstrate that it is possible to build a Relational System that can be used in a real life environment to solve real life problems, with performance at least comparable to that of existing system. Its two subsystems are >Research Storage >System Relational Data System. Q. Define the integrity rules . A. There are two Integrity rules. Entity Integrity: States that Primary key cannot have NULL value

Referential Integrity: States that Foreign Key can be either a NULL value or should be Primary Key value of other relation. Q. What are levels of Abstraction? A. The are three levels of abstraction: Physical level: The lowest level of abstraction describes how data are stored. Logical level: The next higher level of abstraction, describes what data are stored in database and what relationship among those data. View level: The highest level of abstraction describes only part of entire database. Q. DBMS V/s File Processing System A. DBMS Redundancy is controlled. Unauthorised access is restricted. Providing multiple user interfaces. Enforcing integrity constraints. Providing backup and recovery. File Processing System Data redundancy & inconsistency. Difficult in accessing data. Data isolation. Data integrity. Concurrent access is not possible. Security Problems. Q. What is LookUp table ? A. When a foreign key exists in a table, the foreign keys table is sometimes referred to as a lookup table. The DEPARTMENT table in our example is a lookup table for the EMPLOYEE table. The value of an employees department can be looked up in the DEPARTMENT table

Q. What is the Purpose of ERASE command ? A. ERASE removes an indicated Global variable & releases the memory associated with it Q. How do you evaluate performance ? A. Using SQL TRACE. It is an utility that can monitor and report on database performance when one or more queries are run against the database. It is used to gather statistics when running the query (i.e) reports on CPU time spent on the query, the total no. of rows processed and statistics related to parsing and cache performance. Q. What is the DIFFERENCE between PRE-QUERY and POST-QUERY ? A. PRE-QUERY fires ONLY ONCE during EXECUTE-QUERY or COUNT-QUERY processing, just before Oracle Forms constructs and issues the SELECT statement to identify rows that match the query criteria. POST-QUERY fires each time for records placed on the blocks list of records. Q. What is APPLICATION PARTITIONING ? A. PL/SQL is the language used for both client-side Oracle forms applications and server-side database triggers and stored procedures and there is a PL/SQl engine in both Oracle forms Runform and the Oracle7 Server. This means that you can take advantage of application patitioning to execute application code on either the client or the server. Application partitioning allows you to optimize performance and resource usage by storing and executing procedures either locally or at the server, which makes the most sense for your particular application and configuration Q. Can we define our OWN EXCEPTION ? How to raise it ? A. In the DECLARATION part define a variable of type exception. In the excecution part call the exception using RAISE exception_name. In the exception part handle the exception using WHEN exception_name. Q. What is ROWID ? What are its components ?

A. ROWID is the logical address of a row, and it is unique within the database.The ROWID is broken into three sections: left,middle,, and right (corresponding to 00001F20,000C, AND 0001, just shown). The numbering is in hexadecimal notation. Q. What is a DATABASE trigger ? What is a DATABASE Procedure ? A. A DATABASE TRIGGER is a stored procedure associated with a table that ORACLE7 automatically executes on one or more specified events (BEFORE or AFTER an INSERT,UPDATE or DELETE) affecting the table. Triggers can execute for the table as a whole or for each affected row in the table. A PACKAGED PROCEDURE is a built-in PL/SQL procedure that is available in all forms. Each packaged procedure executes a SQL*FORMS function, such as moving to a field or executing a query. Q. What is SNAPSHOT ? What is a SNAPSHOT LOG ? A. A SNAPSHOT is a means of creating a local copy of remote data. A snapshot can be used to replicate all or part of a single table, or to replicate the result of a query against multiple tables. The refreshes of the replicated data can be done automatically by the database ( at time intervals you specify ) or manually.Snapshot Log is the table associated with the Master Table of the Snap shot. Q. What is a package ? A. A PACKAGE is a PL/SQL object that groups PL/SQL types, variables, SQL cursors, exceptions,procedures, and functions.Each package has a specification and a body. The specification shows the object you can access when you use the package. The body fully defines all the objects and can contain additional objects used only for the internal workings Q. What is Data Dictionary ? A. The DATA DICTIONARY is a comprehensive set of tables and views owned by the DBA users SYS and SYSTEM, which activates when ORACLE is initially installed, and is a cental source of information for the ORACLE RDBMS itself and for all users of ORACLE Q. What is index ?

A. INDEX is a general term for an ORACLE / SQL feature used primarily to speed execution an impose UNIQUENESS upon certain data. INDEX provides a faster access method to one tables data than doing a full table scan. There are several types of Indexes : UNIQUE INDEX, COMPRESSED INDEX, CONCATENATED INDEX. Q. What is an UTL_FILE.What are different procedures and functions associated with it ? A. UTL_FILE is a package that adds the ability to read and write to operating system files Procedures associated with it are FCLOSE, FCLOSE_ALL and 5 procedures to output data to a file PUT, PUT_LINE, NEW_LINE, PUTF, FFLUSH.PUT, FFLUSH.PUT_LINE,FFLUSH.NEW_LINE. Functions associated with it are FOPEN, ISOPEN. Q. What is difference between a formal and an actual parameter ? A. The variables declared in the procedure and which are passed, as arguments are called actual, the parameters in the procedure declaration. Actual parameters contain the values that are passed to a procedure and receive results. Formal parameters are the placeholders for the values of actual parameters. Q. Difference between procedure and function ? A. Functions are named PL/SQL blocks that return a value and can be called with arguments procedure a named block that can be called with parameter. A procedure all is a PL/SQL statement by itself, while a Function call is called as part of an expression. Q. How you were passing cursor variables in PL/SQL 2.2 ? A. In PL/SQL 2.2 cursor variables cannot be declared in a package.This is because the storage for a cursor variable has to be allocated using Pro*C or OCI with version 2.2,the only means of passing a cursor variable to a PL/SQL block is via bind variable or a procedure parameter. Q. What is the purpose of a cluster ?

A. Oracle does not allow a user to specifically locate tables, since that is a part of the function of the RDBMS. However, for the purpose of increasing performance, oracle allows a developer to create a CLUSTER. A CLUSTER provides a means for storing data from different tables together for faster retrieval than if the table placement were left to the RDBMS Q. What is a OUTER JOIN ? A. Outer JoinIts a join condition used where you can query all the rows of one of the tables in the join condition even though they dont satisfy the join condition Q. When you use WHERE clause and when you use HAVING clause ? A. HAVING clause is used when you want to specify a condition for a group function and it is written after GROUP BY clause The WHERE clause is used when you want to specify a condition for columns, single row functions except group functions and it is written before GROUP BY clause if it is used Q. What is difference between SQL and SQL*PLUS ? A. SQL*PLUS is a command line tool where as SQL and PL/SQL language interface and reporting tool. Its a command line tool that allows user to type SQL commands to be executed directly against an Oracle database. SQL is a language used to query the relational database(DML,DCL,DDL). SQL*PLUS commands are used to format query result, Set options, Edit SQL commands and PL/SQL. Q. What is a Temporary Segment ? A. Temporary segments are created by ORACLE when a SQL statement needs a temporary work area to complete execution. When the statement finishes execution, the temporary segment extents are released to the system for future use. Q. What is Rollback Segment ? A. A Database contains one or more Rollback Segments to temporarily store undo information

Q. What is an Index Segment ? A. Each Index has an Index segment that stores all of its data Q. What is a Data Segment ? A. Each Non-clustered table has a data segment. All of the tables data is stored in the extents of its data segment. Each Eluster has a data segment. The data of every table in the cluster is stored in the clusters data segment Q. What are the different type of Segments ? A. Q. What is a Segment ? A. A segment is a set of extents allocated for a certain logical structure. Q. What is an Extent ? A. An Extent is a specific number of contiguous data blocks, obtained in a single allocation, used to store a specific type of information. Q. What are the two parts of a procedure ? A. Procedure Specification and Procedure Body. The Same procedure name is repeated with parameters of different datatypes and parameters in different positions, varying number of parameters is called overloading of procedures.e.g. DBMS_OUTPUT put_line Q. What is a stored procedure ? A. A stored procedure is a sequence of statements that perform specific function Q. What is a Navigable item? A. A navigable item is one that operators can navigate to with the keyboard during default navigation, or that Oracle forms can navigate to by executing a navigational built-in procedure.

Q. Explain types of Block in forms4.0? A. Base table Blocks,Control Blocks.A base table block is one that is associated with a specific database table or view.A control block is a block that is not associated with a database table. Q. What is an Alert ? A. An alert is window that appears in the middle of the screen overlaying a portion of the current display Q. What do you mean by a pop-up window ? A. Pop-up windows are screen areas that overlay all or a portion of the display screen when a form is running Q. How does the command POST differs from COMMIT ? A. Post writes data in the form to the database but does not perform database commit Commit permenently writes data in the form to the database. Q. What is the difference between NAME_IN and COPY ? A. Copy is package procedure and writes values into a field. Name in is a package function and returns the contents of the variable to which you apply. Q. What SYNCHRONIZE procedure does ? A. It synchoronizes the terminal screen with the internal state of the form. Q. What is the difference between a POST-FIELD trigger and a POSTCHANGE trigger ? A. Post-field trigger fires whenever the control leaving from the filed. Post-change trigger fires at the time of execute-query procedure invoked or filed validation status changed. Q. What is the difference between an ON-VALIDATE-FIELD trigger and a trigger ?

A. On-validate-field trigger fires, when the field Validation status New or changed. Post-field-trigger whenever the control leaving form the field, it will fire. Q. How many LONG columns are allowed in a table ? Is it possible to use LONG columns in WHERE clause or ORDER BY ? A. Only one LONG columns is allowed. It is not possible to use LONG column in WHERE or ORDER BY clause Q. What is difference between CHAR and VARCHAR2? What is the maximum SIZE allowed for each type ? A. CHAR pads blank spaces to the maximum length. VARCHAR2 does not pad blank spaces. For CHAR it is 255 and 2000 for VARCHAR2. Q. What is ON DELETE CASCADE ? A. When ON DELETE CASCADE is specified ORACLE maintains referential integrity by automatically removing dependent foreign key values if a referenced primary or unique key value is removed. Q. What are the usage of SAVEPOINTS ? A. SAVEPOINTS are used to subdivide a transaction into smaller parts. It enables rolling back part of a transaction. Maximum of five save points are allowed. Q. What is an Integrity Constraint ? A. Integrity constraint is a rule that restricts values to a column in a table. Q. What is the use of IGNORE option in IMP command ? A. A flag to indicate whether the import should ignore errors encounter when issuing CREATE commands Q. What is the use of SHOW option in IMP command ? A. A flag to indicate whether file content should be displayed or not. Q. What is the use of FILE option in IMP command ?

A. The name of the file from which import should be performed Q. What is use of LOG (Ver 7) option in EXP command ? A. The name of the file which log of the export will be written. Q. What is the use of CONSISTENT (Ver 7) option in EXP command ? A. A flag to indicate whether a read consistent version of all the exported objects should be maintained. Q. What is the use of ANALYSE ( Ver 7) option in EXP command ? A. A flag to indicate whether statistical information about the exported objects should be written to export dump file Q. What is the use of PARFILE option in EXP command ? A. Name of the parameter file to be passed for export. Q. What is the use of RECORD option in EXP command ? A. For Incremental exports, the flag indirects whether a record will be stores data dictionary tables recording the export. Q. What is the use of INCTYPE option in EXP command ? A. Type export should be performed COMPLETE,CUMULATIVE,INCREMENTAL Q. What is the use of FULL option in EXP command ? A. A flag to indicate whether full databse export should be performed. Q. What is the use of CONSTRAINTS option in EXP command ? A. A flag to indicate whether constraints on table need to be exported. Q. What is the use of ROWS option in EXP command ? A. Flag to indicate whether table rows should be exported. If N only DDL statements for the databse objects will be created

Q. What is the use of INDEXES option in EXP command ? A. A flag to indicate whether indexes on tables will be exported. Q. What is the use of GRANT option in EXP command ? A. A flag to indicate whether grants on databse objects will be exported or not. Value is Y or N Q. What is the use of COMPRESS option in EXP command ? A. Flag to indicate whether export should compress fragmented segments into single extents. Q. What is the use of FILE option in EXP command ? A. To give the export file name. Q. What changes would you make if you came on board? A. You, of course, will want to take a good hard look at everything the company is doing before making any recommendations Q. What is a Phantom Deadlock? A. In distributed deadlock detection, the delay in propagating local information might cause the deadlock detection algorithms to identify deadlocks that do not really exist. Such situations are called phantom deadlocks and they lead to unnecessary aborts. Q. What is transparent DBMS? A. It is one, which keeps its Physical Structure hidden from user Q. What do you mean by flat file database? A. It is a database in which there are no programs or user access languages. It has no cross-file capabilities but is user-friendly and provides userinterface management. Q. What are the unary operations in Relational Algebra?

A. PROJECTION and SELECTION. Q. Are the resulting relations of PRODUCT and JOIN operation the same? A. PRODUCT: Concatenation of every row in one relation with every row in another. JOIN: Concatenation of rows from one relation and related rows from another. Q. What is the job of the information stored in data-dictionary? A. The information in the data dictionary validates the existence of the objects, provides access to them, and maps the actual physical storage location. Q. Which part of the RDBMS takes care of the data dictionary? How A. Data dictionary is a set of tables and database objects that is stored in a special area of the database and maintained exclusively by the kernel Q. Name the sub-systName the sub-systems of a RDBMS A. I/O, Security, Language Processing, Process Control, Storage Management, Logging and Recovery, Distribution Control, Transaction Control, Memory Management, Lock Management Q. Not only RDBMS takes care of locating data it also A. determines an optimal access path to store or retrieve the data Q. How do you communicate with an RDBMS? A. You communicate with an RDBMS using Structured Query Language (SQL) Q. Name the three major set of files on disk that compose a database in Oracle A. There are three major sets of files on disk that compose a database. All the files are binary. these are:Database files Control files

Redo logs The most important of these are the database files where the actual data resides. The control files and the redo logs support the functioning of the architecture itself. All three sets of files must be present, open, and available to Oracle for any data on the database to be useable. Without these files, you cannot access the database, and the database administrator might have to recover some or all of the database using a backup, if there is one. Q. What are the four Oracle system processes that must always be up and running for the database to be useable A. The four Oracle system processes that must always be up and running for the database to be useable include DBWR (Database Writer), LGWR (Log Writer), SMON (System Monitor), and PMON (Process Monitor). Q. What is Authorization and Integrity manager? A. It is the program module, which tests for the satisfaction of integrity constraint and checks the authority of user to access data. Q. What is File Manager? A. It is a program module, which manages the allocation of space on disk storage and data structure used to represent information stored on a disk. Q. What is Transaction Manager? A. It is a program module, which ensures that database, remains in a consistent state despite system failures and concurrent transaction execution proceeds without conflicting. Q. What is Buffer Manager? A. It is a program module, which is responsible for fetching data from disk storage into main memory and deciding what data to be cache in memory. Q. What is Storage Manager?

A. It is a program module that provides the interface between the low-level data stored in database, application programs and queries submitted to the system Q. How can you find the minimal key of relational schema? A. Minimal key is one which can identify each tuple of the given relation schema uniquely. For finding the minimal key it is required to find the closure that is the set of all attributes that are dependent on any given set of attributes under the given set of functional dependency. Q. What are stand-alone procedures? A. Procedures that are not part of a package are known as stand-alone because they independently defined. A good example of a stand-alone procedure is one written in a SQL*Forms application. These types of procedures are not available for reference from other Oracle tools. Another limitation of stand-alone procedures is that they are compiled at run time, which slows execution. Q. What are stored-procedures? And what are the advantages of using them. A. Stored procedures are database objects that perform a user defined operation. A stored procedure can have a set of compound SQL statements. A stored procedure executes the SQL commands and returns the result to the client. Stored procedures are used to reduce network traffic. Q. Name two utilities that Oracle provides, which are use for backup and recovery. A. Along with the RDBMS software, Oracle provides two utilities that you can use to back up and restore the database. Theseutilities are Export and Import. The Export utility dumps the definitions and data for the specified part of the database to an operating system binary file. The Import utility reads the file produced by an export, recreates thedefinitions of objects, and inserts the dataIf Export and Import are used as a means of backing up and recovering the database Q. What are database files, control files and log files. How many of these files should a database have at least? Why?

A. You must have at least one database file but usually, more than one files are used. The database files are fixed in size and never grow bigger than the size at which they were created Control Files The control files and redo logs support the rest of the architecture. Any database must have at least one control file, although you typically have more than one to guard against loss. The control file records the name of the database, the date and time it was created, the location of the database and redo logs, Redo Logs Any database must have at least two redo logs. These are the journals for the database; the redo logs record all changes to the user objects or system objects Q. Define SQL and state the differences between SQL and other conventional programming Languages A. SQL is a nonprocedural language that is designed specifically for data access operations on normalized relational database structures. The primary difference between SQL and other conventional programming languages is that SQL statements specify what data operations should be performed rather than how to perform them. Q. What is RDBMS KERNEL? A. Two important pieces of RDBMS architecture are the kernel, which is the software, and the data dictionary, which consists of the system-level data structures used by the kernel to manage the database Q. What do you mean by Correlated subquery? A. Subqueries, or nested queries, are used to bring back a set of rows to be used by the parent query A correlated subquery can be easily identified if it contains any references to the parent subquery columns in its WHERE clause. Q. What is a query?

A. A query with respect to DBMS relates to user commands that are used to interact with a data base. The query language can be classified into data definition language and data manipulation language. Q. Brief theory of Network, Hierarchical schemas and their properties A. Network schema uses a graph data structure to organize records example for such a database management system is CTCG while a hierarchical schema uses a tree data structure example for such a system is IMS. Q. What is a checkpoint and When does it occur? A. A Checkpoint is like a snapshot of the DBMS state. By taking checkpoints, the DBMS can reduce the amount of work to be done during restart in the event of subsequent crashes Q. What do you mean by atomicity and aggregation? A. Atomicity:Either all actions are carried out or none are. Users should not have to worry about the effect of incomplete transactions. DBMS ensures this by undoing the actions of incomplete transactions. Aggregation:A concept which is used to model a relationship between a collection of entities and relationships. It is used when we need to express a relationship among relationships Q. What is durability in DBMS? A. Once the DBMS informs the user that a transaction has successfully completed, its effects should persist even if the system crashes before all its changes are reflected on disk. This property is called durability Q. What is join dependency and inclusion dependency? A. Join Dependency:A Join dependency is generalization of Multivalued dependency.A JD {R1, R2, , Rn} is said to hold over a relation R if R1, R2, R3, , Rn is a lossless-join decomposition of R . There is no set of sound and complete inference rules for JD.

Inclusion Dependency:An Inclusion Dependency is a statement of the form that some columns of a relation are contained in other columns. A foreign key constraint is an example of inclusion dependency. Q. What is system catalog or catalog relation? How is better known as? A. A RDBMS maintains a description of all the data that it contains, information about every relation and index that it contains. This information is stored in a collection of relations maintained by the system called metadata. It is also called data dictionary Q. What is indexing and what are the different kinds of indexing? A. Indexing is a technique for determining how quickly specific data can be found. Types: Binary search style indexingB-Tree indexingInverted list indexingMemory resident tableTable indexing Q. When is a functional dependency F said to be minimal? A. Every dependency in F has a single attribute for its right hand side. We cannot replace any dependency X A in F with a dependency Y A where Y is a proper subset of X and still have a set of dependency that is equivalent to F.We cannot remove any dependency from F and still have set of dependency that is equivalent to F. Q. What is Functional Dependency? A. A Functional dependency is denoted by X Y between two sets of attributes X and Y that are subsets of R specifies a constraint on the possible tuple that can form a relation state r of R. The constraint is for any two tuples t1 and t2 in r if t1[X] = t2[X] then they have t1[Y] = t2[Y]. This means the value of X component of a tuple uniquely determines the value of component Y. Q. What is normalization? A. It is a process of analysing the given relation schemas based on their Functional Dependencies (FDs) and primary key to achieve the properties

Minimizing redundancy Minimizing insertion, deletion and update anomalies. Q. What is Set-at-a-time or Set-oriented? A. The High level or Non-procedural DML can specify and retrieve many records in a single DML statement. This retrieve of a record is said to be Set-at-a-time or Set-oriented. Q. What is a Relation Schema and a Relation? A. A relation Schema denoted by R(A1, A2, , An) is made up of the relation name R and the list of attributes Ai that it contains. A relation is defined as a set of tuples. Let r be the relation which contains set tuples (t1, t2, t3, , tn). Each tuple is an ordered list of n-values t=(v1,v2, , vn). Q. What is a view? How it is related to data independence? A. A view may be thought of as a virtual table, that is, a table that does not really exist in its own right but is instead derived from one or more underlying base table. In other words, there is no stored file that direct represents the view instead a definition of view is stored in data dictionary. Q. How is the data structure of System R different from the relational structure? A. Unlike Relational systems in System R Domains are not supported Enforcement of candidate key uniqueness is optional Enforcement of entity integrity is optional Referential integrity is not enforced Q. Describe the three levels of data abstraction? A. The are three levels of abstraction: Physical level: The lowest level of abstraction describes how data are stored. Logical level: The next higher level of abstraction, describes what data are stored in database and what relationship among those data. View level: The highest level of abstraction describes only part of entire database.

Q. Disadvantage in File Processing System? A. Data redundancy & inconsistency. Difficult in accessing data. Data isolation. Data integrity. Concurrent access is not possible Q. How to Run a Query on a Remote SQL Server? A. You can use the OPENROWSET( ) function to run a query on a remote SQL server by using the following syntax: SELECT * FROM OPENROWSET(SQLOLEDB, remote_server_name; sa; password,'SQL statement) Q. How do I list the available tables in a database Im querying? A. You can get a list of tables in a database by calling the INFORMATION_SCHEMA.Tables view like this: SELECT * FROM information_schema.tables Q. What are the different types of SQL commands ? A. DDL ( Data definition language ) DML ( Data manipulation language ) TCL ( Transact control language) Session Control Statements. ( ALTER SESSION, ROLE ) System Control Statements. ( ALTER SYSTEM ) Q. What are the benefits of SQL ? A. 1. It is flexible, Powerful and easy to learn. 2. It is a non-procedural language. It a] Processes set of records rather than just one at a time

and b] Provides automatic navigation to the data. 3. It provides commands for a variety of tasks including : a] Querying data b] Creating,Updating and Replacing objects and Inserting, Updating and Deleting rows. 4. All RDBMS supports SQL Thus one can transfer the skills gained with SQL from one RDBMS to another. 5. Programs written in SQL are portable, they can often be moved from one database to another with little modification.

. .

First Job. Dream Job. Freshersworld.com

Networking concepts
1. What are the two types of transmission technology available? (i) Broadcast and (ii) point-to-point 2. What is subnet? A generic term for section of a large networks usually separated by a bridge or router. 3. Difference between the communication and transmission. Transmission is a physical movement of information and concern issues like bit polarity, synchronisation, clock etc. Communication means the meaning full exchange of information between two communication media. 4. What are the possible ways of data exchange? (i) Simplex (ii) Half-duplex (iii) Full-duplex. 5. What is SAP? Series of interface points that allow other computers to communicate with the other layers of network protocol stack. 6. What do you meant by "triple X" in Networks? The function of PAD (Packet Assembler Disassembler) is described in a document known as X.3. The standard protocol has been defined between the terminal and the PAD, called X.28; another standard protocol exists between hte PAD and the network, called X.29. Together, these three recommendations are often called "triple X" 7. What is frame relay, in which layer it comes? Frame relay is a packet switching technology. It will operate in the data link layer. 8. What is terminal emulation, in which layer it comes? Telnet is also called as terminal emulation. It belongs to application layer. 9. What is Beaconing? The process that allows a network to self-repair networks problems. The stations on the network notify the other stations on the ring when they are not receiving the transmissions. Beaconing is used in Token ring and FDDI networks. 10. What is redirector? Redirector is software that intercepts file or prints I/O requests and translates them into network requests. This comes under presentation layer.

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com 11. What is NETBIOS and NETBEUI? NETBIOS is a programming interface that allows I/O requests to be sent to and received from a remote computer and it hides the networking hardware from applications. NETBEUI is NetBIOS extended user interface. A transport protocol designed by microsoft and IBM for the use on small subnets. 12. What is RAID? A method for providing fault tolerance by using multiple hard disk drives. 13. What is passive topology? When the computers on the network simply listen and receive the signal, they are referred to as passive because they dont amplify the signal in any way. Example for passive topology - linear bus. 14. What is Brouter? Hybrid devices that combine the features of both bridges and routers. 15. What is cladding? A layer of a glass surrounding the center fiber of glass inside a fiber-optic cable. 16. What is point-to-point protocol A communications protocol used to connect computers to remote networking services including Internet service providers. 17. How Gateway is different from Routers? A gateway operates at the upper levels of the OSI model and translates information between two completely different network architectures or data formats 18. What is attenuation? The degeneration of a signal over distance on a network cable is called attenuation. 19. What is MAC address? The address for a device as it is identified at the Media Access Control (MAC) layer in the network architecture. MAC address is usually stored in ROM on the network adapter card and is unique. 20. Difference between bit rate and baud rate. Bit rate is the number of bits transmitted during one second whereas baud rate refers to the number of signal units per second that are required to represent those bits. baud rate = bit rate / N where N is no-of-bits represented by each signal shift.

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com 21. What is Bandwidth? Every line has an upper limit and a lower limit on the frequency of signals it can carry. This limited range is called the bandwidth. 22. What are the types of Transmission media? Signals are usually transmitted over some transmission media that are broadly classified in to two categories. a) Guided Media: These are those that provide a conduit from one device to another that include twisted-pair, coaxial cable and fiber-optic cable. A signal traveling along any of these media is directed and is contained by the physical limits of the medium. Twisted-pair and coaxial cable use metallic that accept and transport signals in the form of electrical current. Optical fiber is a glass or plastic cable that accepts and transports signals in the form of light. b) Unguided Media: This is the wireless media that transport electromagnetic waves without using a physical conductor. Signals are broadcast either through air. This is done through radio communication, satellite communication and cellular telephony. 23. What is Project 802? It is a project started by IEEE to set standards to enable intercommunication between equipment from a variety of manufacturers. It is a way for specifying functions of the physical layer, the data link layer and to some extent the network layer to allow for interconnectivity of major LAN protocols. It consists of the following: 802.1 is an internetworking standard for compatibility of different LANs and MANs across protocols. 802.2 Logical link control (LLC) is the upper sublayer of the data link layer which is non-architecture-specific, that is remains the same for all IEEE-defined LANs. Media access control (MAC) is the lower sublayer of the data link layer that contains some distinct modules each carrying proprietary information specific to the LAN product being used. The modules are Ethernet LAN (802.3), Token ring LAN (802.4), Token bus LAN (802.5). 802.6 is distributed queue dual bus (DQDB) designed to be used in MANs. 24. What is Protocol Data Unit? The data unit in the LLC level is called the protocol data unit (PDU). The PDU contains of four fields a destination service access point (DSAP), a source service access point (SSAP), a control field and an information field. DSAP, SSAP are addresses used by the LLC to identify the protocol stacks on the receiving and sending machines that are generating and using the data. The control field specifies whether the PDU frame is a information frame (I - frame) or a supervisory frame (S frame) or a unnumbered frame (U - frame). 25. What are the different type of networking / internetworking devices?
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com Repeater: Also called a regenerator, it is an electronic device that operates only at physical layer. It receives the signal in the network before it becomes weak, regenerates the original bit pattern and puts the refreshed copy back in to the link. Bridges: These operate both in the physical and data link layers of LANs of same type. They divide a larger network in to smaller segments. They contain logic that allow them to keep the traffic for each segment separate and thus are repeaters that relay a frame only the side of the segment containing the intended recipent and control congestion. Routers: They relay packets among multiple interconnected networks (i.e. LANs of different type). They operate in the physical, data link and network layers. They contain software that enable them to determine which of the several possible paths is the best for a particular transmission. Gateways: They relay packets among networks that have different protocols (e.g. between a LAN and a WAN). They accept a packet formatted for one protocol and convert it to a packet formatted for another protocol before forwarding it. They operate in all seven layers of the OSI model. 26. What is ICMP? ICMP is Internet Control Message Protocol, a network layer protocol of the TCP/IP suite used by hosts and gateways to send notification of datagram problems back to the sender. It uses the echo test / reply to test whether a destination is reachable and responding. It also handles both control and error messages. 27. What are the data units at different layers of the TCP / IP protocol suite? The data unit created at the application layer is called a message, at the transport layer the data unit created is called either a segment or an user datagram, at the network layer the data unit created is called the datagram, at the data link layer the datagram is encapsulated in to a frame and finally transmitted as signals along the transmission media. 28. What is difference between ARP and RARP? The address resolution protocol (ARP) is used to associate the 32 bit IP address with the 48 bit physical address, used by a host or a router to find the physical address of another host on its network by sending a ARP query packet that includes the IP address of the receiver. The reverse address resolution protocol (RARP) allows a host to discover its Internet address when it knows only its physical address. 29. What is the minimum and maximum length of the header in the TCP segment and IP datagram? The header should have a minimum length of 20 bytes and can have a maximum length of 60 bytes.
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com

30. What is the range of addresses in the classes of internet addresses? Class A 0.0.0.0 127.255.255.255 Class B 128.0.0.0 191.255.255.255 Class C 192.0.0.0 223.255.255.255 Class D 224.0.0.0 239.255.255.255 Class E 240.0.0.0 247.255.255.255 31. What is the difference between TFTP and FTP application layer protocols? The Trivial File Transfer Protocol (TFTP) allows a local host to obtain files from a remote host but does not provide reliability or security. It uses the fundamental packet delivery services offered by UDP. The File Transfer Protocol (FTP) is the standard mechanism provided by TCP / IP for copying a file from one host to another. It uses the services offer by TCP and so is reliable and secure. It establishes two connections (virtual circuits) between the hosts, one for data transfer and another for control information. 32. What are major types of networks and explain? Server-based network Peer-to-peer network Peer-to-peer network, computers can act as both servers sharing resources and as clients using the resources. Server-based networks provide centralized control of network resources and rely on server computers to provide security and network administration 33. What are the important topologies for networks? BUS topology: In this each computer is directly connected to primary network cable in a single line. Advantages: Inexpensive, easy to install, simple to understand, easy to extend. STAR topology: In this all computers are connected using a central hub. Advantages: Can be inexpensive, easy to install and reconfigure and easy to trouble shoot physical problems. RING topology: In this all computers are connected in loop. Advantages: All computers have equal access to network media, installation can be simple, and signal does not degrade as much as in other topologies because each computer regenerates it. 34. What is mesh network?
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com A network in which there are multiple network links between computers to provide multiple paths for data to travel. 35. What is difference between baseband and broadband transmission? In a baseband transmission, the entire bandwidth of the cable is consumed by a single signal. In broadband transmission, signals are sent on multiple frequencies, allowing multiple signals to be sent simultaneously. 36. Explain 5-4-3 rule? In a Ethernet network, between any two points on the network ,there can be no more than five network segments or four repeaters, and of those five segments only three of segments can be populated. 37. What MAU? In token Ring , hub is called Multistation Access Unit(MAU). 38. What is the difference between routable and non- routable protocols? Routable protocols can work with a router and can be used to build large networks. Non-Routable protocols are designed to work on small, local networks and cannot be used with a router 39. Why should you care about the OSI Reference Model? It provides a framework for discussing network operations and design. 40. What is logical link control? One of two sublayers of the data link layer of OSI reference model, as defined by the IEEE 802 standard. This sublayer is responsible for maintaining the link between computers when they are sending data across the physical network connection. 41. What is virtual channel? Virtual channel is normally a connection from one source to one destination, although multicast connections are also permitted. The other name for virtual channel is virtual circuit. 42. What is virtual path? Along any transmission path from a given source to a given destination, a group of virtual circuits can be grouped together into what is called path. 43. What is packet filter? Packet filter is a standard router equipped with some extra functionality. The extra functionality allows every incoming or outgoing packet to be inspected. Packets meeting some criterion are forwarded normally. Those that fail the test are dropped.

Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com 44. What is traffic shaping? One of the main causes of congestion is that traffic is often busy. If hosts could be made to transmit at a uniform rate, congestion would be less common. Another open loop method to help manage congestion is forcing the packet to be transmitted at a more predictable rate. This is called traffic shaping. 45. What is multicast routing? Sending a message to a group is called multicasting, and its routing algorithm is called multicast routing. 46. What is region? When hierarchical routing is used, the routers are divided into what we will call regions, with each router knowing all the details about how to route packets to destinations within its own region, but knowing nothing about the internal structure of other regions. 47. What is silly window syndrome? It is a problem that can ruin TCP performance. This problem occurs when data are passed to the sending TCP entity in large blocks, but an interactive application on the receiving side reads 1 byte at a time. 48. What are Digrams and Trigrams? The most common two letter combinations are called as digrams. e.g. th, in, er, re and an. The most common three letter combinations are called as trigrams. e.g. the, ing, and, and ion. 49. Expand IDEA. IDEA stands for International Data Encryption Algorithm. 50. What is wide-mouth frog? Wide-mouth frog is the simplest known key distribution center (KDC) authentication protocol. 51. What is Mail Gateway? It is a system that performs a protocol translation between different electronic mail delivery protocols. 52. What is IGP (Interior Gateway Protocol)? It is any routing protocol used within an autonomous system. 53. What is EGP (Exterior Gateway Protocol)? It is the protocol the routers in neighboring autonomous systems use to identify the set of networks that can be reached within or via each autonomous system. 54. What is autonomous system?
Freshersworld.com Resource Center

First Job. Dream Job. Freshersworld.com It is a collection of routers under the control of a single administrative authority and that uses a common Interior Gateway Protocol. 55. What is BGP (Border Gateway Protocol)? It is a protocol used to advertise the set of networks that can be reached with in an autonomous system. BGP enables this information to be shared with the autonomous system. This is newer than EGP (Exterior Gateway Protocol). 56. What is Gateway-to-Gateway protocol? It is a protocol formerly used to exchange routing information between Internet core routers. 57. What is NVT (Network Virtual Terminal)? It is a set of rules defining a very simple virtual terminal interaction. The NVT is used in the start of a Telnet session. 58. What is a Multi-homed Host? It is a host that has a multiple network interfaces and that requires multiple IP addresses is called as a Multi-homed Host. 59. What is Kerberos? It is an authentication service developed at the Massachusetts Institute of Technology. Kerberos uses encryption to prevent intruders from discovering passwords and gaining unauthorized access to files. 60. What is OSPF? It is an Internet routing protocol that scales well, can route traffic along multiple paths, and uses knowledge of an Internet's topology to make accurate routing decisions. 61. What is Proxy ARP? It is using a router to answer ARP requests. This will be done when the originating host believes that a destination is local, when in fact is lies beyond router.

62. What is SLIP (Serial Line Interface Protocol)? It is a very simple protocol used for transmission of IP datagrams across a serial line. 63. What is RIP (Routing Information Protocol)? It is a simple protocol used to exchange information between the routers. 64. What is source route? It is a sequence of IP addresses identifying the route a datagram must follow. A source route may optionally be included in an IP datagram header.

Freshersworld.com Resource Center

Computer-Networks Question and Answer

Q. Explain difference between baseband and broadband transmission. A. In a baseband transmission, the entire bandwidth of the cable is consumed by a single signal. In broadband transmission, signals are sent on multiple frequencies, allowing multiple signals to be sent simultaneously Q. Explain redirector. A. Redirector is software that intercepts file or prints I/O requests and translates them into network requests. This comes under presentation layer Q. Explain the HELLO protocol used for. A. The HELLO protocol uses time instead of distance to determine optimal routing. It is an alternative to the Routing Information Protocol Q. Explain a DNS resource record. A. A resource record is an entry in a name servers database. There are several types of resource records used, including name-to-address resolution information. Resource records are maintained as ASCII files Q. Explain External Data Representation. A. External Data Representation is a method of encoding data within an RPC message, used to ensure that the data is not system-dependent Q. Explain anonymous FTP and why would you use it ? A. Anonymous FTP enables users to connect to a host without using a valid login and password. Usually, anonymous FTP uses a login called anonymous or guest, with the password usually requesting the users ID for tracking purposes only. Anonymous FTP is used to enable a large number of users to access files on the host without having to go to the trouble of setting up logins for them all. Anonymous FTP systems usually have strict controls over the areas an anonymous user can access.

Q. Explain a Management Information Base (MIB). A. A Management Information Base is part of every SNMP-managed device. Each SNMP agent has the MIB database that contains information about the devices status, its performance, connections, and configuration. The MIB is queried by SNMP Q. Explain the difference between an unspecified passive open and a fully specified passive open.

A. An unspecified passive open has the server waiting for a connection request from a client. A fully specified passive open has the server waiting for a connection from a specific client. Q. What is the difference between POP3 and IMAP Mail Server?

A. The using of IMAP to access your mailbox has advantages over POP3 and the difference of their working mechanism. Mechanism of POP3 Since email needs to be downloaded into desktop PC before being displayed, you may have the following problems for POP3 access: You need to download all email again when using another desktop PC to check your email. May get confused if you need to check email both in the office and at home. The downloaded email may be deleted from the server depending on the setting of your email client. All messages as well as their attachments will be downloaded into desktop PC during the check new email process. Mailboxes can only be created on desktop PC. There is only one mailbox (INBOX) exists on the server. Filters can transfer incoming/outgoing messages only to local mailboxes. Outgoing email is stored only locally on the desktop PC. Messages are deleted on the desktop PC. Comparatively, it is inconvenient to clean up your mailbox on the server.

Messages may be reloaded onto desktop PC several times due to the corruption of system files. Mechanism of IMAP Since email is kept on server, it would gain the following benefits for IMAP access: No need to download all email when using other desktop PC to check your email. Easier to identify the unread email. A whole message will be downloaded only when it is opened for display from its content. Multiple mailboxes can be created on the desktop PC as well as on the server. Filters can transfer incoming/outgoing messages to other mailboxes no matter where the mailboxes locate (on the server or the PC). Outgoing email can be filtered to a mailbox on server for accessibility from other machine. Messages can be deleted directly on the server to make it more convenient to clean up your mailbox on the server. The occurrence of reloading messages from the server to PC is much less when compared to POP3. Q. What is ERD(Emergency Repair Disk)? A. you must have a ERD diskette containing a valid Setup.log file for that computer before repairs are possible. When you attempt to repair Windows 2000, it asks if you have an ERD diskette, if you do not have the diskett, press L and the computer attempts to locate your Windows 2000 installation to perform repairs. This process looks for the Boot.ini file on your computer partition and reads the ARC paths to your operating system(s). The computer then attempts to load the following hive for each ARC path Q. What are the Advantages and Disadvantages of DHCP? A. DHCP (Dynamic Host Configuration Protocol) allows your computer to automatically obtain a fully functional IP address from the central RPI DHCP server. Every time you boot up your computer, your operating system retrieves a new IP address.

Q. What is Recovery Console?


A. The Recovery Console is a feature of the Windows 2000 and Windows XP operating systems. It provides the means for administrators to perform a limited range of tasks using a textual user interface. As its name suggests, its primary function is to enable administrators to recover from situations where Windows does not boot as far as presenting its graphical user interface. Q. What is a different between switch and Hub? A. Q. Explain traffic shaping. A. One of the main causes of congestion is that traffic is often busy. If hosts could be made to transmit at a uniform rate, congestion would be less common. Another open loop method to help manage congestion is forcing the packet to be transmitted at a more predictable rate. This is called traffic shaping. Q. Explain Project 802. A. It is a project started by IEEE to set standards that enable intercommunication between equipment from a variety of manufacturers. It is a way for specifying functions of the physical layer, the data link layer and to some extent the network layer to allow for interconnectivity of major LAN protocols Q. What do you meant by triple X in Networks? A. The function of PAD (Packet Assembler Disassembler) is described in a document known as X.3. The standard protocol has been defined between the terminal and the PAD, called X.28; another standard protocol exists between hte PAD and the network, called X.29. Together, these three recommendations are often called triple X Q. Explain the minimum and maximum length of the header in the TCP segment and IP datagram A. The header should have a minimum length of 20 bytes and can have a maximum length of 60 bytes.

Q. What is frame relay, in which layer it comes? A. Frame relay is a packet switching technology. It will operate in the data link layer. Q. What is RAID? A. RAID (Redundant Array of Independent Disks) is a set of technology standards for teaming disk drives to improve fault tolerance and performance RAID 0 Optimized for Performance RAID 1 Optimized for Redundancy RAID 5 A Good Compromise RAID 0+1 Optimize for Performance and Redundancy RAID 0+1 combines the performance of RAID 0 with the redundancy of RAID 1 Q. What is attenuation? A. Attenuation is a general term that refers to any reduction in the strength of a signal. Attenuation occurs with any type of signal, whether digital or analog. Sometimes called loss, attenuation is a natural consequence of signal transmission over long distances. The extent of attenuation is usually expressed in units called decibels (dBs). Q. Difference between bit rate and baud rate? A. Bitrate (sometimes written bit rate, data rate or as a variable Rbit) is the number of bits that are conveyed or processed per unit of time. Bit rate is often used as synonym to the terms connection speed, transfer rate, channel capacity, maximum throughput and digital bandwidth capacity of a communication system Baud (pronounced /b??d/, unit symbol Bd), is a measure of the symbol rate, that is, the number of distinct symbol changes (signalling events) made to the transmission medium per second in a digitally modulated signal. The term baud rate is also commonly used to refer to the symbol rate Q. What is the minimum and maximum length of the header in the TCP segment and IP datagram? A. The default IP Maximum Datagram Size is 576. The default TCP Maximum Segment Size is 536.

Q. What is Gateway-to-Gateway protocol? A. GGP is a min-hop algorithm, i.e., its length measure is simply the number of network hops between gateway pairs. It implements a distributed shortest-path algorithm, which requires global convergence of the routing tables after a change in topology or connectivity. Each gateway sends a GGP routing update only to its neighbors, but each update includes an entry for every known network, where each entry contains the hop count from the gateway sending the update Q. What is a Multi-homed Host? A. A computer that is connected to more than one physical data link, these data links may or may not be attached to the same network. The host may send and receive data over any of the links but will not route traffic for other nodes Q. What is SLIP (Serial Line Internet Protocol)? A. The Serial Line Internet Protocol (SLIP) is a mostly obsolete encapsulation of the Internet Protocol designed to work over serial ports and modem connections Q. What is RIP (Routing Information Protocol)? A. The Routing Information Protocol, or RIP, as it is more commonly called, is one of the most enduring of all routing protocols. RIP sends routingupdate messages at regular intervals and when the network topology changes Q. What is Interior Gateway Protocol ? A. IGRP is a distance vector Interior Gateway Protocol (IGP). Distance vector routing protocols mathematically compare routes using some measurement of distance Q. Why EIGRP is more efficient in operation than IGRP ? A. Unlike most other distance vector routing protocols, EIGRP does not mandate a periodic update of routing tables between neighboring routers. Instead, it employs a neighbor discovery/recovery mechanism to ensure that neighbors remain aware of each others accessibility

Q. Name the four key technologies that are used by EIGRP ? A. EIGRP employs four key technologies 1. including neighbor discover/recovery, 2. Reliable Transport Protocol (RTP), 3. Diffusing Update ALgorithm (DUAL) finite-state machine, 4. and a modular architecture that enables support for new protocols to be easily added to an existing network. Q. What is Enhanced Interior Gateway Routing Protocol ? A. The Enhanced Interior Gateway Routing Protocol (EIGRP) represents an evolution from its predecessor IGRP. This evolution resulted from changes in networking and the demands of diverse, large-scale internetworks Q. What is Banyan VINES ? A. Banyan Virtual Integrated Network Service (VINES) implements a distributed network operating system based on a proprietary protocol family derived from the Xerox Corporations Xerox Network Systems (XNS) protocols. VINES uses a client/server architecture in which clients request certain services, such as file and printer access, from servers Q. What is Data-Link Switching ? A. Data-link switching (DLSw) provides a means of transporting IBM Systems Network Architecture (SNA) and network basic input/output system (NetBIOS) traffic over an IP network Q. Where is SMDS Interface Protocol used ? A. The SMDS Interface Protocol (SIP) is used for communications between CPE (Customer premises equipment) and SMDS (Switched Multimegabit Data Service) carrier equipment Q. What is Switched Multimegabit Data Service ?

A. Switched Multimegabit Data Service (SMDS) is a high-speed, packetswitched, datagram-based WAN networking technology used for communication over public data networks (PDNs). Q. What is the basic difference between transparent bridges and source-route bridges relative to the forwarding processes ? A. In a transparent bridged environment, bridges determine whether a frame needs to be forwarded, and through what path based upon local bridge tables. In an SRB network, the source device prescribes the route to the destination and indicates the desired path in the RIF. Q. What is Transparent Bridge ? A. Transparent bridges were first developed at Digital Equipment Corporation (Digital) in the early 1980s. Transparent bridges are so named because their presence and operation are transparent to network hosts. When transparent bridges are powered on, they learn the workstation locations by analyzing the source address of incoming frames from all attached networks Q. What is source-route bridging algorithm ? A. The source-route bridging (SRB) algorithm was developed by IBM and was proposed to the IEEE 802.5 committee as the means to bridge between all LANs it does make several suggestions, including the following: First frame received Response with the minimum number of hops Response with the largest allowed frame size Various combinations of the preceding criteria Q. Which are the three types of routing tables ? Ans. The three types of routing tables are fixed, dynamic, and fixed central. A fixed table must be manually modified every time there is a change.

A dynamic table changes its information based on network traffic, reducing the amount of manual maintenance. A fixed central table lets a manager modify only one table, which is then read by other devices Q. What protocol is used by DNS name servers ? A. DNS uses UDP for communication between servers. It is a better choice than TCP because of the improved speed a connectionless protocol offers. Of course, transmission reliability suffers with UDP. Q. What are 10Base2, 10Base5 and 10BaseT Ethernet LANs ?

A. 10Base2An Ethernet term meaning a maximum transfer rate of 10 Megabits per second that uses baseband signaling, with a contiguous cable segment length of 100 meters and a maximum of 2 segments. 10Base5An Ethernet term meaning a maximum transfer rate of 10 Megabits per second that uses baseband signaling, with 5 continuous segments not exceeding 100 meters per segment. 10BaseTAn Ethernet term meaning a maximum transfer rate of 10 Megabits per second that uses baseband signaling and twisted pair cabling.

Q. What is the difference between interior and exterior neighbor


gateways? A. Interior gateways connect LANs of one organization, whereas exterior gateways connect the organization to the outside world

Q. What is External Data Representation?


A. eXternal Data Representation (XDR) is an IETF standard from 1995 of the presentation layer in the OSI model. XDR allows data to be wrapped in an architecture independent manner so data can be transferred between heterogeneous computer systems. Q. What is the Network Time Protocol?

A. The Network Time Protocol is a protocol for synchronizing the clocks of computer systems over packet-switched, variable-latency data networks. NTP uses UDP port 123 as its transport layer. Q. What is anonymous FTP and why would you use it? A. Anonymous FTP enables users to connect to a host without using a valid login and password. Usually, anonymous FTP uses a login called anonymous or guest, with the password usually requesting the users ID for tracking purposes only Q. What does the Mount protocol do ? A. The Mount protocol returns a file handle and the name of the file system in which a requested file resides. The message is sent to the client from the server after reception of a clients request. Q. What is Domain Naming Service(DNS)? A. It is very difficult to remember a set of numbers(IP address) to connect to the Internet. The Domain Naming Service(DNS) is used to overcome this problem. It maps one particular IP address to a string of characters.

Q. What is URL?
A. URL stands for Uniform Resource Locator and it points to resource files on the Internet. URL has four components: http://www. address. com:80/index.html, where http - protocol name, address - IP address or host name, 80 - port number and index.html - file path. Q. What is Inet address? A. Every computer connected to a network has an IP address. An IP address is a number that uniquely identifies each computer on the Net. An IP address is a 32-bit number. Q. What is the difference between TCP/IP and UDP? A. TCP/IP is a two-way communication between the client and the server and it is a reliable and there is a confirmation regarding reaching the message to the destination. It is like a phone call. UDP is a one-way

communication only between the client and the server and it is not a reliable and there is no confirmation regarding reaching the message to the destination. It is like a postal mail. Q. what is the significance of the IP address 255.255.255.255? A. The limited broadcast address is utilized when an IP node must perform a one-to-everyone delivery on the local network but the network ID is unknown. Q. What tool have you used to create and analyze packet captures? A. Network Monitor in Win2K / Win2K3, Ethereal in Linux, OptiView Series II (by Fluke Networks). Q. What is LDAP used for? A. LDAP is a set of protocol used for providing access to information directories Q. What is the difference between a domain local group and a global group? A. Domain local groups grant permissions to objects within the domain in which the reside. Global groups contain grant permissions tree or forest wide for any objects within the Active Directory Q. How do you set a default route on an IOS Cisco router? A . ip route 0.0.0.0 0.0.0.0 x.x.x.x [where x.x.x.x represents the destination address] Q. What is a default gateway? A. The exit-point from one network and entry-way into another network, often the router of the network Q. What is Kerberos? A. It is an authentication service developed at the Massachusetts Institute of Technology. Kerberos uses encryption to prevent intruders from discovering passwords and gaining unauthorized access to files.

Q. What is NVT (Network Virtual Terminal)? A. It is a set of rules defining a very simple virtual terminal interaction. The NVT is used in the start of a Telnet session Q. What is silly window syndrome? A. It is a problem that can ruin TCP performance. This problem occurs when data are passed to the sending TCP entity in large blocks, but an interactive application on the receiving side reads 1 byte at a time. Q. What is region? A. When hierarchical routing is used, the routers are divided into what we will call regions, with each router knowing all the details about how to route packets to destinations within its own region, but knowing nothing about the internal structure of other regions. Q. What is traffic shaping? A. One of the main causes of congestion is that traffic is often busy. If hosts could be made to transmit at a uniform rate, congestion would be less common. Another open loop method to help manage congestion is forcing the packet to be transmitted at a more predictable rate. This is called traffic shaping. Q. What is packet filter? A. Packet filter is a standard router equipped with some extra functionality. The extra functionality allows every incoming or outgoing packet to be inspected. Packets meeting some criterion are forwarded normally. Those that fail the test are dropped. Q. What is virtual path? A. Along any transmission path from a given source to a given destination, a group of virtual circuits can be grouped together into what is called path. Q. What is virtual channel?

A. Virtual channel is normally a connection from one source to one destination, although multicast connections are also permitted. The other name for virtual channel is virtual circuit. Q. What is LLC? A. LLC is Logical Link Control, one of two sublayers of the data link layer of OSI reference model, as defined by the IEEE 802 standard. This sublayer is responsible for maintaining the link between computers when they are sending data across the physical network connection. Q. What is the difference between routable and non- routable protocols? A. Routable protocols can work with a router and can be used to build large networks. Non-Routable protocols are designed to work on small, local networks and cannot be used with a router Q. What is MAU? A. In token Ring , hub is called Multistation Access Unit(MAU). Q. Explain 5-4-3 rule? A. In a Ethernet network, between any two points on the network ,there can be no more than five network segments or four repeaters, and of those five segments only three of segments can be populated. Q. What is the difference between TFTP and FTP application layer protocols? A. The Trivial File Transfer Protocol (TFTP) allows a local host to obtain files from a remote host but does not provide reliability or security. It uses the fundamental packet delivery services offered by UDP. The File Transfer Protocol (FTP) is the standard mechanism provided by TCP / IP for copying a file from one host to another. It uses the services offer by TCP and so is reliable and secure. Q. What is the range of addresses in the classes of internet addresses? A.

Class A 0.0.0.0 - 127.255.255.255 Class B 128.0.0.0 - 191.255.255.255 Class C 192.0.0.0 - 223.255.255.255 Class D 224.0.0.0 - 239.255.255.255 Class E 240.0.0.0 - 247.255.255.255 Q. What is difference between ARP and RARP? A. The address resolution protocol (ARP) is used to associate the 32 bit IP address with the 48 bit physical address, used by a host or a router to find the physical address of another host on its network by sending a ARP query packet that includes the IP address of the receiver. The reverse address resolution protocol (RARP) allows a host to discover its Internet address when it knows only its physical address. Q. What are the data units at different layers of the TCP / IP protocol suite? A. The data unit created at the application layer is called a message, at the transport layer the data unit created is called either a segment or an user datagram, at the network layer the data unit created is called the datagram, at the data link layer the datagram is encapsulated in to a frame and finally transmitted as signals along the transmission media. Q. What is ICMP? A. ICMP is Internet Control Message Protocol, a network layer protocol of the TCP/IP suite used by hosts and gateways to send notification of datagram problems back to the sender Q. What is Protocol Data Unit? A. The data unit in the LLC level is called the protocol data unit (PDU). The PDU contains of four fields a destination service access point (DSAP), a source service access point (SSAP). Q. How Gateway is different from Routers? A. A gateway operates at the upper levels of the OSI model and translates information between two completely different network architectures or data formats.

Q. What is passive topology? A. When the computers on the network simply listen and receive the signal, they are referred to as passive because they dont amplify the signal in any way. Example for passive topology - linear bus. Q. What is NETBIOS and NETBEUI? A. NETBIOS is a programming interface that allows I/O requests to be sent to and received from a remote computer and it hides the networking hardware from applications. NETBEUI is NetBIOS extended user interface. A transport protocol designed by microsoft and IBM for the use on small subnets. Q. What is redirector? A. Redirector is software that intercepts file or prints I/O requests and translates them into network requests. This comes under presentation layer. Q. What is Beaconing? A. The process that allows a network to self-repair networks problems Q. What is terminal emulation, in which layer it comes? A. Telnet is also called as terminal emulation. It belongs to application layer Q. What do you meant by triple X in Networks? A. The function of PAD (Packet Assembler Disassembler) is described in a document known as X.3. The standard protocol has been defined between the terminal and the PAD, called X.28; another standard protocol exists between hte PAD and the network, called X.29. Together, these three recommendations are often called triple X Q. What is SAP? A. SAP: Service Access Point , Series of interface points that allow other computers to communicate with the other layers of network protocol stack. Q. How does the browser know to go to a certain IP address when you enter a domain like kyapoocha.com? A. It searches through local DNS cache, if nothing is there, it queries the ISPs DNS server

Q. What is Load balancing? A. If the number of incoming clients requests exceeds the number of processes in a server class, the TP Monitor may dynamically start new ones and this is called Load balancing Q. What is OLTP? A. In the transaction server, the client component usually includes GUI and the server components usually consists of SQL transactions against a database. These applications are called OLTP (Online Transaction Processing) OLTP Applications typically, Q. What is Message Oriented Middleware (MOM)? A. MOM allows general purpose messages to be exchanged in a Client/Server system using message queues. Applications communicate over networks by simply putting messages in the queues and getting messages from queues. It typically provides a very simple high level APIs to its services. Q. What is meant by Asymmetrical protocols? A. There is a many-to-one relationship between clients and server. Clients always initiate the dialog by requesting a service. Servers are passively awaiting for requests from clients Q. What is Groupware server? A. Groupware addresses the management of semi-structured information such as text, image, mail, bulletin boards and the flow of work. These Client/Server systems have people in direct contact with other people. Q. What is Client/Server? A. Clients and Servers are separate logical entities that work together over a network to accomplish a task. Many systems with very different architectures that are connected together are also called Client/Server Q. What is a File server? A. File servers are useful for sharing files across a network. With a file server, the client passes requests for file records over nerwork to file server.

Q. What are called Fat clients and Fat servers? A. If the bulk of the application runs on the Client side, then it is Fat clients. It is used for decision support and personal software. If the bulk of the application runs on the Server side, then it is Fat servers. It tries to minimize network interchanges by creating more abstract levels of services Q. What is Remote Procedure Call (RPC)? A. RPC hides the intricacies of the network by using the ordinary procedure call mechanism familiar to every programmer. A client process calls a function on a remote server and suspends itself until it gets back the results. Parameters are passed like in any ordinary procedure. The RPC, like an ordinary procedure, is synchoronous. The process that issues the call waits until it gets the results. Under the covers, the RPC run-time software collects values for the parameters, forms a message, and sends it to the remote server. The server receives the request, unpack the parameters, calls the procedures, and sends the reply back to the client. It is a telephone-like metaphor. Q. What are the building blocks of Client/Server? A. The client ,The server and Middleware Q. What is a TP Monitor? A. There is no commonly accepted definition for a TP monitor. According to Jeri Edwards a TP Monitor is an OS for transaction processing Q. What are Super servers? A. These are fully-loaded machines which includes multiprocessors, highspeed disk arrays for intervive I/O and fault tolerant features. Q. What is a Web server? A. This new model of Client/Server consists of thin, protable, universal clients that talk to superfat servers. In the simplet form, a web server returns documents when clients ask for them by name. The clients and server communicate using an RPC-like protocol called HTTP.

Q. What is a Database Server? A. With a database server, the client passes SQL requests as messages to the database server. The results of each SQL command are returned over the network. The server uses its own processing power to find the request data instead of passing all the records back to the client and then getting it find its own data. The result is a much more efficient use of distributed processing power. It is also known as SQL engine. Q. What is anonymous FTP and why would you use it? A. Anonymous FTP enables users to connect to a host without using a valid login and password. Usually, anonymous FTP uses a login called anonymous or guest, with the password usually requesting the users ID for tracking purposes only. Anonymous FTP is used to enable a large number of users to access files on the host without having to go to the trouble of setting up logins for them all. Q. What is a DNS resource record? A. A resource record is an entry in a name servers database. There are several types of resource records used, including name-to-address resolution information. Resource records are maintained as ASCII files. Q. Explain the function of Transmission Control Block? A. A TCB is a complex data structure that contains a considerable amount of information about each connection. Q. What is virtual path? A. Along any transmission path from a given source to a given destination, a group of virtual circuits can be grouped together into what is called path. Q. What protocol is used by DNS name servers? A. DNS uses UDP for communication between servers. It is a better choice than TCP because of the improved speed a connectionless protocol offers. Of course, transmission reliability suffers with UDP. Q. What is External Data Representation?

A. External Data Representation is a method of encoding data within an RPC message, used to ensure that the data is not system-dependent. Q. What is Brouter? A. Hybrid devices that combine the features of both bridges and routers Q. What is REX? A. Request to Exit (REX) - A signal that informs the controller that someone has requested to exit from a secure area Q. What are major types of networks and explain? A. Server-based network. Peer-to-peer network. Peer-to-peer network, computers can act as both servers sharing resources and as clients using the resources. Server-based networks provide centralized control of network resources and rely on server computers to provide security and network administration. Q. Explain the importance and use of each, Version, Culture and PublicKeyToken for an assembly. A. PublicKeyToken: Each assembly can have a public key embedded in its manifest that identifies the developer. This ensures that once the assembly ships, no one can modify the code or other resources contained in the assembly. Culture: Specifies which culture the assembly supports Version: The version number of the assembly.It is of the following form major.minor.build.revision Q. How you will set the datarelation between two columns? A. ADO.NET provides DataRelation object to set relation between two columns.It helps to enforce the following constraints,a unique constraint, which guarantees that a column in the table contains no duplicates and a foreign-key constraint,which can be used to maintain referential integrity.A unique constraint is implemented either by simply setting the Unique property of a data column to true, or by adding an instance of the UniqueConstraint class to the DataRelation objects ParentKeyConstraint.

As part of the foreign-key constraint, you can specify referential integrity rules that are applied at three points,when a parent record is updated,when a parent record is deleted and when a change is accepted or rejected. Q. What is source route? A. It is a sequence of IP addresses identifying the route a datagram must follow. A source route may optionally be included in an IP datagram header. Q. What is Proxy ARP? A. It is using a router to answer ARP requests. This will be done when the originating host believes that a destination is local, when in fact is lies beyond router. Q. What is OSPF? A. It is an Internet routing protocol that scales well, can route traffic along multiple paths, and uses knowledge of an Internets topology to make accurate routing decisions. Q. What is BGP (Border Gateway Protocol)? A. It is a protocol used to advertise the set of networks that can be reached with in an autonomous system. BGP enables this information to be shared with the autonomous system. This is newer than EGP (Exterior Gateway Protocol). Q. What is autonomous system? A. It is a collection of routers under the control of a single administrative authority and that uses a common Interior Gateway Protocol. Q. What is EGP (Exterior Gateway Protocol)? A. It is the protocol the routers in neighboring autonomous systems use to identify the set of networks that can be reached within or via each autonomous system. Q. What is IGP (Interior Gateway Protocol)? A. It is any routing protocol used within an autonomous system Q. What is Mail Gateway?

A. It is a system that performs a protocol translation between different electronic mail delivery protocols Q. What is wide-mouth frog? A. Wide-mouth frog is the simplest known key distribution center (KDC) authentication protocol. Q. What are Digrams and Trigrams? A. The most common two letter combinations are called as digrams. e.g. th, in, er, re and an. The most common three letter combinations are called as trigrams. e.g. the, ing, and, and ion. Q. What is multicast routing? A. Sending a message to a group is called multicasting, and its routing algorithm is called multicast routing. Q. What is logical link control? A. One of two sublayers of the data link layer of OSI reference model, as defined by the IEEE 802 standard. This sublayer is responsible for maintaining the link between computers when they are sending data across the physical network connection Q. What are the important topologies for networks? A. BUS topology:In this each computer is directly connected to primary network cable in a single line. Advantages:Inexpensive, easy to install, simple to understand, easy to extend. STAR topology:In this all computers are connected using a central hub. Advantages:Can be inexpensive, easy to install and reconfigure and easy to trouble shoot physical problems. RING topology:In this all computers are connected in loop. Advantages:All computers have equal access to network media, installation can be simple, and signal does not degrade as much as in other topologies because each computer regenerates it Q. What are the data units at different layers of the TCP / IP protocol suite?

A. The data unit created at the application layer is called a message, at the transport layer the data unit created is called either a segment or an user datagram, at the network layer the data unit created is called the datagram, at the data link layer the datagram is encapsulated in to a frame and finally transmitted as signals along the transmission media. Q. What is ICMP? A. ICMP is Internet Control Message Protocol, a network layer protocol of the TCP/IP suite used by hosts and gateways to send notification of datagram problems back to the sender Q. What are the different type of networking / internetworking devices? A. Repeater:Also called a regenerator, it is an electronic device that operates only at physical layer. It receives the signal in the network before it becomes weak, regenerates the original bit pattern and puts the refreshed copy back in to the link. Bridges: These operate both in the physical and data link layers of LANs of same type. They divide a larger network in to smaller segments. They contain logic that allow them to keep the traffic for each segment separate and thus are repeaters that relay a frame only the side of the segment containing the intended recipent and control congestion. Routers:They relay packets among multiple interconnected networks (i.e. LANs of different type). They operate in the physical, data link and network layers. They contain software that enable them to determine which of the several possible paths is the best for a particular transmission. Gateways:They relay packets among networks that have different protocols (e.g. between a LAN and a WAN). They accept a packet formatted for one protocol and convert it to a packet formatted for another protocol before forwarding it. They operate in all seven layers of the OSI model. Q. What is Protocol Data Unit?

A. The data unit in the LLC level is called the protocol data unit (PDU). The PDU contains of four fields a destination service access point (DSAP), a source service access point (SSAP), a control field and an information field. DSAP, SSAP are addresses used by the LLC to identify the protocol stacks on the receiving and sending machines that are generating and using the data. The control field specifies whether the PDU frame is a information frame (I - frame) or a supervisory frame (S - frame) or a unnumbered frame (U frame). Q. What are the types of Transmission media? A. Signals are usually transmitted over some transmission media that are broadly classified in to two categories. a)Guided Media:These are those that provide a conduit from one device to another that include twisted-pair, coaxial cable and fiber-optic cable. A signal traveling along any of these media is directed and is contained by the physical limits of the medium. Twisted-pair and coaxial cable use metallic that accept and transport signals in the form of electrical current. Optical fiber is a glass or plastic cable that accepts and transports signals in the form of light. b) Unguided Media: This is the wireless media that transport electromagnetic waves without using a physical conductor. Signals are broadcast either through air. This is done through radio communication, satellite communication and cellular telephony. Q. What is Bandwidth? A. Every line has an upper limit and a lower limit on the frequency of signals it can carry. This limited range is called the bandwidth Q. What is MAC address? A. The address for a device as it is identified at the Media Access Control (MAC) layer in the network architecture. MAC address is usually stored in ROM on the network adapter card and is unique. Q. What is cladding? A. A layer of a glass surrounding the center fiber of glass inside a fiber-optic cable

Q. What is subnet? A. A generic term for section of a large networks usually separated by a bridge or router. Q. What is IP? A. IP is Internet Protocol. It is the network protocol which is used to send information from one computer to another over the network over the internet in the form of packets

You might also like