Material from Interview Mantra. Mantra . Subscribe to free updates via email.
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
Favourite 50 – C Interview Question Bank for freshers and experienced IT programmers
Written by Madhulika Reddy and Dhoka Ratan. Edited and Published by ridhar !ammalamadaka
Get the latest updates and news on topics Career and Education from Interview Mantra – Subscribe to Interview Mantra for free .
ABOUT THIS BOOK This book comprises of Inter"ie# $uestions and %ns#ers collected from the famous career ad"ice blog & ###.Inter"ie#Mantra.net The aim of this book is to h elp freshers and experienced programmers to 'uickly brush up the basic concepts of ( language. This book can be used as a 'uick study guide before attending a )ob inter"ie# #hich re'uires kno#ledge of ( programming language. The 'uestions that appear in this book are fe# of the most fre'uently asked 'uestions in IT !ob inter"ie#s in top M*( companies. %ll %ll the 'uestions ha"e been neatly ans#ered and ha"e been supported #ith example code #here"er applicable. % lot lot of effort has been put into this this book to make the ans#ers ans#ers as accurate as possible+ possible+ but no #arranty or fitness is implied. The authors and the publisher shall ha"e neither liability nor responsibility to any person or entity #ith respect to any loss or damages arising from the information contained in this book or from the use of the programs accompanying it. Please send your feedback to us "ia email to sridhar,inter"ie#mantra.net sridhar,inter"ie#mantra.net
COPYRIHT I!FO ( language - Inter"ie# $uestion ank by ridhar !ammalamadaka is !ammalamadaka is licensed under a (reati"e (ommons %ttribution&hare %ttribution& hare %like %like /.0 India 1icense 1icense.. ased on a #ork at ###.inter"ie#mantra.net . In simple #ords+ you may use this #ork for commercial purposes+ remix the #ork+ reproduce it by any means+ pro"ided you keep a link to http233###.inter"ie#mantra.net and attribute the the #ork to the o#ner o#ner & ridhar !ammalamadaka.
CO!T"!TS CO!T"!T S AT AT A #A!C" # A!C" 1. 2. 3. 4. .
C$a%ter !a&e %'(no 4ariables 5 (ontrol 6lo# 6l o# . . . . . . . . . . . . . . . . . . . . 7 8perators+ 8perator s+ (onstants (onstan ts 5 tructures tructure s . . . . . . . . . . . .99 .99 6unctions 6unctio ns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9: Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ./; ./ ; Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ./<
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
TAB#" OF CO!T"!TS CHAPT"R )* +aria,-es . Contro- F-ow 9. What is the the differenc difference e bet#een bet#een declaring declaring a "ariable "ariable and and defining defining a "ariabl "ariable= e= /. What What is a stat static ic "ar "aria iabl ble= e= ;. What What is a reg regis iste terr "ari "ariab able le= = >. Where Where is an auto auto "ariab "ariable le stor stored= ed= 0. What is is scope 5 storage storage allocati allocation on of extern extern and global global "ariables= "ariables= 7. What is scope scope 5 storage storage alloca allocation tion of regist register er++ static static and local local "ariables= "ariables= :. What are storage storage memory memory+ default "alue+ "alue+ scope and life life of %utomatic %utomatic and Register Register storage storage class= class= ?. What are storage storage memory memory++ default default "alue+ scope scope and life life of tatic and and External External storage storage class= class= <. What is is the differ difference ence bet#ee bet#een n @break@ @break@ and @contin @continue@ ue@ stateme statements= nts= 9A. What is the difference bet#een bet#een @for@ and @#hile@ @#hile@ loops= CHAPT"R /* O%erators Constants . Stru1tures 9. Which bit#is bit#ise e operator operator is suitable suitable for checking checking #hether #hether a particul particular ar bit is 8* or 866= 866= /. Which bit#is bit#ise e operator operator is suitable suitable for for turning turning 866 a partic particular ular bit bit in a number= number= ;. What is e'ui"ale e'ui"alent nt of multiplyi multiplying ng an unsigned unsigned int by /2 left shift shift of number number by 9 or right shift shift of number number by 9= >. What What is is an Enumer Enumerati ation on (ons (onstan tant= t= 0. What What is a stru struct ctur ure= e= 7. What are are the the differen differences ces bet#ee bet#een n a structur structure e and a union= union= :. What What are are the the ad"an ad"antag tages es of of unio unions= ns= ?. Bo# can can typed typedef ef be to defin define e a type of struc structur ture= e= <. Write Write a program program that returns returns ; numbers numbers from from a function function using using a structure structure.. 9A. In code code snippet snippet belo# belo#22 struct Date C int yr int day int month date9+date/ date9.yr F /AA> date9.day F > date9.month F 9/ Write a function that assigns "alues to date/. %rguments to the function must be pointers to the structure+ Date and integer "ariables date+ month+ yea r.
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
CHAPT"R 2* Fun1tions 9. What is is the purpose purpose of mainGH mainGH function= function= /. Explain Explain command command line line arguments arguments of main functi function= on= ;. What are header files= %re functions functions declared or defined in header header files = >. What are the the differences bet#een formal formal arguments and actual arguments arguments of a function= function= 0. What is pass pass by "alue "alue in in functions functions= = 7. What is is pass by reference reference in functi functions= ons= :. What are the the differences bet#een getcharGH and scanfGH functions functions for reading reading strings= ?. 8ut of the the functions fgetsGH fgetsGH and getsGH+ getsGH+ #hich one is safer to use and #hy=
!. What is the difference bet#een the functions strdupGH and strcpyGH= CHAPT"R 3* Pointers 9. What What is is a poin pointer ter in (= (= /. What are are the ad"antage ad"antages s of using using pointers pointers= = ;. What are the differen differences ces bet#een bet#een mallocGH mallocGH and callocGH= callocGH= >. Bo# to use use reallocGH to to dynamically increase sie of an already allocated array= array= 0. What is the e'ui"alent e'ui"alent pointer expression for for referring an element element aJiKJ)KJkKJlK+ aJiKJ)KJkKJlK+ in a four dimensional array= 7. Declare an array of three function pointers pointers #here each function function recei"es t#o integers integers and returns float. :. Explain Explain the "ariabl "ariable e assignment assignment in the declarat declaration ion int LGLpJ9AKHGchar L+ char LH ?. What What is is the the "alue "alue of sieofGaH 3sieofGchar LH in a code snippet2 char LaJ>KFCsridhar+ragha"a+ LaJ>KFCsridhar+ragha"a+shashi+srikanth shashi+srikanth <. GiH What are are the differences differences bet#een bet#een the ( statements statements belo#2 belo#2 char Lstr F Bello char arrJK F Bello GiiH Whether follo#ing statements get complied or not= Explain each statement. arrNN LGarr N 9H F @s@ printfGOs+arrH CHAPT"R 5* Pro'ra&s 9. Write Write a program program to find factorial factorial of the the gi"en number number.. /. Write Write a program program to check #hether #hether the gi"en gi"en number number is e"en or odd. ;. Write a program to s#ap t#o numbers numbers using a temporary "ariable. "ariable. >. Write a program to s#ap s#ap t#o numbers #ithout using a temporary "ariable.
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
0. Write Write a program to s#ap t#o t#o numbers using using bit#ise bit#ise operators. operators. 7. Write Write a program program to find the greates greatestt of three numbers. numbers. :. Write Write a program program to find the greates greatestt among ten numbers. numbers. ?. Write Write a program program to check #hether #hether the gi"en gi"en number number is a prime. <. Write a program to check check #hether the the gi"en number is a palindromic palindromic number. number. 9A.Write a program to check #hether the gi"en string is a palindrome. 99.Write a program to generate the 6ibonacci series. 9/.Write a program to print Bello World #ithout using semicolon any#here in the code. 9;.Write a program to print a semicolon #ithout using a semicolon any#here in the code. 9>.Write a program to compare t#o strings #ithout using strcmpGH function. 90.Write a program to concatenate t#o strings #ithout using strcatGH function. 97.Write a program to delete a specified line from a text file. 9:.Write a program to replace a specified line in a text f ile. 9?.Write a program to find the number of lines in a text file. 9<.Write a ( program #hich asks the user for a number bet#een 9 to < and sho#s the number. If the user inputs a number out of the specified range+ the program should sho# an error and prompt the user for a "alid input. /A.Write a program to display the multiplication table of a gi"en number.
Testi&onia-s Anushka M says Thank you soooo much for all these 'uestions+ along #ith the solutions. ItQs a great compilation. Thanks a lot guys. 2H
Anonymous says %#esome. Thanks a ton for uploading this pdf+ your concept #as crystal clear. *o# I am "ery confident about myself. *o# I@m ready to face the inter"ie# challenge. Thanks once a gain.
Urmi says Thank Sou..It@s Sou..It@s *ice..It sa"ed my "aluable Time.. Thanks a lot
Rajakumari says Thank you so ... much Mr. ridhar. ridhar. *o #ords to say + lot of thanksUU 4ery useful to freshers 5 experienced.
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
CHAPT"R )* +aria,-es . Contro- F-ow )4 $at is t$e t$e 6i77eren1 6i77eren1e e ,etween ,etween 6e1-arin 6e1-arin' ' a varia,-e varia,-e an6 6e7inin 6e7inin' ' a varia,-e8 varia,-e8 Declaration of a "ariable in ( hints the compiler about the type and sie of the "ariable in compile time. imilarly+ imilarly+ declaration of a function hints about type and sie of function parameters. *o space is reser"ed in memory for any "ariable in case of declaration. "9a&%-e* int "9a&%-e* int a Bere "ariable @a@ is declared of data type @int@ Defining a "ariable means declaring it and also allocating space to hold it. We can say Definition F Declaration N pace reser"ation. "9a&%-e* int "9a&%-e* int a F 9A Bere "ariable a is described as an int to the compiler and memory is allocated to hold "alue 9A. /4 $at $at is is a stat stati1 i1 var varia ia,,-e8 e8 % static static "ariable is a special "ariable that that is stored in the the data segment unlike the the default automatic "ariable that is stored in stack. % static "ariable can be initialied by using key#ord static before "ariable name. "9a&%-e* static int a F 0 % static static "ariable beha"es in in a different manner depending upon #hether #hether it is a global "ariable or a local "ariable. % static static global "ariable "ariable is same as an ordinary ordinary global "ariable except except that it cannot be accessed by other files files in the same program 3 pro)ect e"en #ith the use of key#ord extern. % static static local "ariable is different from local "ariable. It is initialied only once no matter ho# many times that function in #hich it resides is called. It may be used as a count "ariable. "9a&%-e* Vinclude stdio.hX 33program in file f9.c "oid countG"oidH C static int count9 F A int count/ F A count9NN count/NN printfGYn4alue printfGYn4alue of count9 is Od+ 4alue 4alue of count/ is Od+ count9+ count/H 3LMain functionL3 int mainGHC countGH countGH countGH return A Out%ut* 4alue of count9 is 9+ 4alue 4alue of count/ is 9 4alue of count9 is /+ 4alue 4alue of count/ is 9
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
4alue of count9 is ;+ 4alue 4alue of count/ is 9
24 $at $at is is a re'ist re'ister er varia, varia,-e8 -e8 Register "ariables are stored in the (PZ registers. Its default "alue is a garbage "alue. cope of a register "ariable is local to the block in #hich it is defined. 1ifetime is till control remains #ithin the block in #hich the register "ariable is defined. 4ariable stored in a (PZ register can al#ays be accessed faster than the one that is stored in memory. memory. Therefore+ if a "ariable is used at many places in a program+ it is better to declare its storage class as register "9a&%-e* register int xF0 4ariables for loop counters can be declared as register. *ote that register key#ord may be ignored by some compilers.
34 $ere $ere is is an auto auto vari varia,a,-es es store store68 68 Main memory and (PZ registers are the t#o memory locations #here auto "ariables are stored. %uto "ariables are defined under automatic storage class. They are stored in main memory. memory. Memory is allocated to an automatic "ariable #hen the block #hich contains it is called and it is de&allocated at the completion of its block execution. Auto varia,-es* Stora'e * main memory. :e7a :e7auu-tt vava-ue ue * garbage "alue. S1o%e * local to the block in #hich the "ariable is defined. till the control remains #ithin the block in #hich the "ariable is defined. #i7eti&e *
54 $at is is s1o%e s1o%e . stora'e stora'e a--o1at a--o1ation ion o7 e9tern e9tern an6 '-o,a '-o,a-- varia,-es varia,-es8 8 "9tern varia,-es* belong to the External storage class and are stored in the main memory. extern is used #hen #e ha"e to refer a function or "ariable that is implemented in other file in the same pro)ect. The scope of the extern "ariables is [lobal. "9a&%-e* 3LLLLLLLLLLLLLLL Index2 f9.c LLLLLLLLLLLLLLLL3 Vinclude stdio.hX extern int x int mainGH C printfG"alue of x Od+ xH return A Index2 f/.c LLLLLLLLLLLLLLLL3 int x F ; Bere+ the program #ritten in file f9.c has the main function and reference to "ariable x. The file f/.c has the declaration of "ariable x. The compiler should kno# the datatype of x and this is done by extern definition. extern definition.
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
-o,a- varia,-es* are varia,-es* are "ariables #hich are declared abo"e the mainG H function. These "ariables are accessible throughout the program. They can be accessed by all the functions in the program. Their default "alue is ero.
"9a&%-e* Vinclude stdio.hX int x F A 3L 4ariable x is a global "ariable. It can be accessed throughout the program L3 "oid incrementG"oidH C x F x N 9 printfGYn "alue of x2 Od+ xH int mainGHC printfGYn "alue of x2 Od+ xH incrementGH return A ;4 $at is s1o%e s1o%e . stora'e stora'e a--o1at a--o1ation ion o7 re'ister re'ister stati1 an6 an6 -o1a- varia, varia,-es8 -es8 Re'ister varia,-es* belong varia,-es* belong to the register storage class and are stored in the (PZ registers. The scope of the register "ariables is local to the block in #hich the "ariables are defined. The "ariables #hich are used for more number of times in a program are declared as register "ariables for faster access. Example2 loop counter "ariables. register int yF7 Stati1 varia,-es* Memory varia,-es* Memory is allocated at the beginning of the program execution and it is reallocated only after the program terminates. The scope of the static "ariables is local to the block in #hich the "ariables are defined. "9a&%-e* Vinclude stdio.hX "oid decrementGHC static int aF0 a&& printfG4alue printfG4alue of a2OdYn+ a2OdYn+ aH int mainGHC decrementGH return A Bere @a@ is initialied only once. E"ery time this function is called+ @a@ does not get initialied. so output #ould be > ; / etc.+ #o1a- varia,-es* are varia,-es* are "ariables #hich are declared #ithin any function or a block. They can be accessed only by function or block in #hich they are declared. Their default "alue is a garbage "alue. <4 $at are stora'e stora'e &e&or= &e&or= 6e7au-t va-ue s1o%e s1o%e an6 -i7e -i7e o7 Auto&ati1 an6 Re'ister Re'ister stora'e 1-ass8 )4 Auto&ati1 stora'e 1-ass* Stora'e * :e7a :e7auu-tt vava-ue ue *
main memory. garbage "alue.
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
S1o%e #i7eti&e
* *
local to the block in #hich the "ariable is defined. till control remains #ithin the block.
/4 Re'ister stora'e 1-ass* Stora'e :e7a :e7auu-tt vava-ue ue S1o%e #i7eti&e
* * * *
(PZ registers. garbage "alue. local to the block in #hich the "ariable is defined. till control remains #ithin the block.
>4 $at are stora'e stora'e &e&or= &e&or= 6e7au-t va-ue s1o%e s1o%e an6 -i7e -i7e o7 Stati1 Stati1 an6 "9terna- stora'e stora'e 1-ass8 )4 Stati1 stora'e 1-ass* Stora'e :e7a :e7auu-tt vava-ue ue S1o%e #i7eti&e
* * * *
main memory. ero local to the block in #hich the "ariable is defined. till the "alue of the "ariable persists bet#een different function calls.
/4 "9terna- stora'e 1-ass* Stora'e :e7a :e7auu-tt vava-ue ue S1o%e #i7eti&e
* * * *
main memory ero global as long as the program execution doesn@t come to an end.
?4 $at is is t$e 6i77ere 6i77eren1e n1e ,etween ,etween @,reak@ @,reak@ an6 an6 @1ontinu @1ontinue@ e@ state&ent state&ents8 s8 :i77eren1es ,etween @,reak@ an6 @1ontinue@ @1ontinue@ state&ents ,reak 9. break is a key#ord used to terminate the loop or exit from the block. The control )umps to next statement after the loop or block. /.yntax2
1ontinue
9. continue is a key#ord used for skipping the current iteration and go to next iteration of the loop /.yntax2
C tatement 9 tatement / tatement n break
C tatement 9 continue tatement /
;. break can be used #ith for+ for+ #hile+ do& #hile+ and s#itch statements. When break is used in nested loops i.e. #ithin the inner most loop then only the innermost loop is terminated.
;. This statement #hen occurs in a loop does not terminate it but skips the statements after this continue statement. The control goes to the next iteration. continue can be used #ith for+ #hile and dohile.
>. Example2
>. Example2
i F 9+ ) F A #hileGiF0H C iFiN9 ifGiFF /H
i F 9+ ) F A #hileGiF0H C iFiN9 ifGiFF /H
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
break )F)N9
continue )F)N9
)04 $at is t$e 6i77eren1e 6i77eren1e ,etween ,etween @7or@ an6 @w$i-e@ -oo%s8 -oo%s8 7or -oo%* When it is desired to do initialiation+ condition check and increment3decrement in a single statement of an iterati"e loop+ it is recommended to use @for@ loop. S=nta9* forGinitialiationconditionincrement3decrementH C 33block of statements increment or decrement Pro'ra&* Program Pro'ra&* Program to illustrate for loop Vincludestdio.hX int mainGH C int i for Gi F 9 i F 0 iNNH C 33print the number printfGYn Od+ iH return A Out%ut* 9 / ; > 0 "9%-anation* The loop repeats for 0 times and prints "alue of @i@ each time. @i@ increases by 9 for e "ery cycle of loop. w$i-e -oo%* When -oo%* When it is not necessary to do initialiation+ initialiation+ condition check and increment3decrement in a single statement of an iterati"e loop+ #hile loop could be used. In #hile loop statement+ only condition statement is present. S=nta9* Vincludestdio.hX int mainGH C int i F A+ flag F A int aJ9AK F C A+ 9+ >+ 7+ ?<+ 0>+ :?+ /0+ 7;0+ 0AA 33This loop is repeated until the condition is false.
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
#hile Gflag FF AH C if GaJiK FF 0>H C 33as element element is found+ flag F 9+the loop terminates terminates flag F 9 else C iNN printfGElement found at Od th location+ iH return A Out%ut* Element found at 0th location "9%-anation* Bere flag is initialied to ero. @#hile@ loop repeats until the "alue of flag is ero+ increments i by 9. @if@ condition checks #hether number 0> is found. If found+ "alue of flag is set to 9 and @#hile@ loop terminates.
CHAPT"R /* O%erators Constants . Stru1tures )4 $i1$ ,itwise ,itwise o%erator o%erator is suita,-e suita,-e 7or 1$e1kin' w$et$er w$et$er a %arti1u-ar ,it is O! or OFF8 OFF8 Bitwise A!: o%erator4 "9a&%-e* uppose "9a&%-e* uppose in byte that has a "alue 9A9A99A9 . We #ish to check #hether bit number ; is 8* G9H or 866 GAH . ince #e #ant to check the bit number ;+ the second operand for %*D operation #e choose is binary AAAA9AAA+ #hich is e'ual to ? in decimal. "9%-anation* %*Ding operation 2 9A9A99A9 original bit pattern AAAA9AAA %*D mask &&&&&&&&& AAAA9AAA resulting bit pattern &&&&&&&&& The resulting "alue #e get in this case is ?+ i.e. the "alue of the second operand. The result turned out to be a ? since the third bit of operand #as 8*. Bad it been 866+ the bit number ; in the resulting bit pattern #ould ha"e e"aluated to A and complete bit pattern #ould ha"e been AAAAAAAA. Thus depending upon the bit number to be checked in the first operand #e decide the second operand+ and on %*Ding these t#o operands the result decides #hether the bit #as 8* or 866. /4 $i1$ ,itwise ,itwise o%erator o%erator is is suita,-e suita,-e 7or turnin' OFF a %arti1u-ar ,it in a nu&,er8 nu&,er8 it#ise %*D %*D operator G5H+ one@s complement operatorG\H "9a&%-e* To unset the >th bit of byte]data or to turn off a particular bit in a number. number. "9%-anation* (onsider+
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
char byte]dataF AbAAA9A999 AbAAA9A999 byte]dataF Gbyte]dataH5G\G9>HH 9 can be represented in binary as AbAAAAAAA9 F G9>H is a left bit shift operator+ it shifts the bit 9 by > places to#ards left. G9>H becomes AbAAA9AAAA %nd \ is the one@s complement complement operator in ( language. o \G9>H F complement of AbAAA9AAAA F Ab999A999 Ab 999A9999 9 Replacing "alue of byte]data and and \G9>H in Gbyte]dataH5G\G9>HH #e get g et GAbAAA9A999H GA bAAA9A999H 5 GAb99 G Ab999A99 9A9999H 99H Perform %*D operation to belo# bytes. AAA9A999 999A9999 &&&&&&&&&&& AAAAA999 &&&&&&&&&&& Thus the >th bit is unset. 24 $at is euiva-ent euiva-ent o7 &u-ti%-=in' &u-ti%-=in' an unsi'ne6 unsi'ne6 int ,= /* -e7t s$i7t o7 o7 nu&,er ,= ) or ri'$t ri'$t s$i7t o7 nu&,er ,= )8 1eft shifting of an unsigned integer is e'ui"alent to multiplying an unsigned int by /. Eg92 9>9 (onsider a number 9>&&&&&AAAA999A 9>&&&&&AAAA999A G?N>N/His its binary e'ui"alent left shift it by 9&&&&&&&&&&&&&&AAA999 9&&&&&&&&&&&&&&AAA999AAG97N?N>H AAG97N?N>H #hich is /?. Eg/2 99 consider the number as 9&&&AAAAAAA9GANAN9H. left shift that by 9&&&&&&&&&&&&AAAAAA9AGAN/NAH #hich is /. left shift by 9 bit of a numberF/Lnumber left shift by 9 bit of /LnumberF/L/Lnumber left shift by n bits of numberFG/^nHLnumber Pro'ra&* Program Pro'ra&* Program to illustrate left shift and right shift operations. Vincludestdio.hX int mainG"oidH C int xF9A+yF9A printfGleft shift of 9A is Od Yn+x9H printfGright shift of 9A is Od Yn+yXX9H return A Out%ut* left shift of 9A is /A right shift of 9A is 0 "9%-anation* 1eft shift Gby 9 positionH multiplies a number by t#o. Right shift di"ides a number by /.
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
34 $at $at is an an "nu& "nu&era eratio tion n Const Constant ant8 8 Enumeration is a data type. We can create our o#n data type and define "alues that the "ariable can take. This can help in making program more readable. enum definition is similar to that of a structure. "9a&%-e* consider "9a&%-e* consider light]status as a data type. It can ha"e t#o possible "alues & on or off. enum light]status C on+ off enum light]status bulb9+ bulb/ 3L bulb9+ bulb/ are the "ariables L3 :e1-aration o7 enu& $as two %arts* aH 6irst part declares the data type and specifies the possible "alues+ called @enumerators@. bH econd part declares the "ariables of this data type. We can gi"e "alues to these "ariables2 bulb9 F on bulb/ F off 54 $at $at is a stru stru1t 1tur ure8 e8 % structure structure is a collection collection of pre&defined data types to create a user&defined data type. 1et us say #e need to create records of students. Each student has three fields2 int roll]number char nameJ;AK int total]marks This concept #ould be particularly useful in grouping data types. Sou could declare a structure student as2 struct student C int roll]number char nameJ;AK int total]marks student9+ student/ The abo"e snippet of code #ould declare a structure by name student and it initialies t#o ob)ects student9+ student/. *o# these ob)ects and their fields could be accessed by saying student9.roll]number for accesing roll number field of student9 ob)ect+ similarly student/.name for accesing name field of student/ ob)ect. ;4 $at are are t$e t$e 6i77eren1 6i77eren1es es ,etween ,etween a stru1t stru1ture ure an6 an6 a union union8 8 tructures and Znions are used to store members of different data types. STRUCTUR" aH:e1-aration* aH:e1-aration* aH:e1-aration* aH:e1-aration*
U!IO!
struct C data type member9 data type member/
union C data type member9 data type member/
bHE"ery structure member is allocated memory #hen a structure "ariable is defined. "9a&%-e*
bHThe memory e'ui"alent to the largest item is allocated commonly for all members. "9a&%-e*
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
struct emp C char nameJ0K int age float sal struct emp e9 Memory allocated for structure is 9N/N>F: bytes. 9 byte for name+ / bytes for age and > bytes for sal. cH%ll structure "ariables can be initialied at a time struct st C int a float b struct st s F C .aF>+ .bF9A.0 tructure is used #hen all members are to be independently used in a program.
union emp9 C char nameJ0K int age float sal union emp9 e/ Memory allocated to a union is e'ual to sie of the largest member. member. In this case+ float is the largest&sied data type. Bence memory allocated to this union is > bytes. cH8nly one union member can be initialied at a time union un C int a float b union un un9 F C .aF9A Znion is used #hen members of it are not re'uired to be accessed at the same time.
<4 $at $at are t$e t$e a6vant a6vanta'e a'es s o7 unio unions8 ns8 Znion is a collection of data items of different data types. It can hold data of only one member at a time though it has members of different data types. If a union has t#o members of different data types+ they are allocated the same memory. The memory allocated is e'ual to maximum sie of the members. The data is interpreted in bytes depending on #hich member is being accessed. "9a&%-e* union pen C char name float point Bere name and point are union members. 8ut of these t#o "ariables+ @point@ is larger "ariable #hich is of float data type and it #ould need > bytes of memory. memory. Therefore > bytes space is allocated for both the "ariables. oth the "ariables ha"e the same memory location. They are accessed according to their type. Znion is efficient #hen members of it are not re'uired to be accessed a t the same time. >4 How 1an t=%e6e t=%e6e77 ,e to to 6e7ine 6e7ine a t=%e o7 stru1tu stru1ture8 re8 typedef declaration helps to make source code of a ( program more readable. Its purpose is to redefine the name of an existing "ariable type. It pro"ides a short and meaningful #ay to call a data type. typedef is useful #hen the name of the data type is long. Zse of typedef can reduce length and complexity of data t ypes. *ote2 Zsually uppercase letters are used to make it clear that #e are dealing #ith our o#n data type. "9a&%-e* struct employee C char nameJ/AK int age
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
struct employee e The abo"e declaration of the structure #ould be easy to use #hen renamed using typedef as2 struct employee C char nameJ/AK int age typedef struct employee EMP EMP e9+ e/ ?4 rite rite a %ro'ra& %ro'ra& t$at return returns s 2 nu&,ers nu&,ers 7ro& a 7un1tio 7un1tion n usin' usin' a stru1ture4 stru1ture4 % function function in ( can return return only one "alue. If If #e #ant the function function to return multiple multiple "alues+ #e #e need to create a structure "ariable+ #hich has three integer members and return this structure. Pro'ra&* Pro'ra& wit$ a 7un1tion to return 2 va-ues Vincludestdio.hX 33sample structure #hich has three integer "ariables. struct sample C int a+ b+ c 33this is function #hich returns three "alues. struct sample return;"alGH C struct sample s9 s9.a F 9A s9.b F /A s9.c F ;A 33return structure s9+ #hich means return s9.a +s9.b and s9.c return s9 int mainGH C struct sample accept;"al 33three "alues returned are accepted by structure accept;"al. accept;"al F return;"alGH 33prints the "alues printfG Yn Od+ accept;"al.aH printfGYn Od+ accept;"al.bH printfG Yn Od+ accept;"al.cH return A Out%ut* 9A /A ;A. "9%-anation* In this program+ #e use ( structure to return multiple "alues from a function. Bere #e ha"e a structure holding three int "ariables and a function #hich returns it. @return;"al@ is a function #hich assigns 9A+ /A+ ;A to its integer "ariables and returns this structure. In this program+ @accept;"al@ is a structure used to accept the "alues returned by the function. It accepts those "alues and sho#s the output.
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
)04 In 1o6e 1o6e sni%%et sni%%et ,e-ow* ,e-ow* stru1t :ate int =r int 6a= int &ont$ D 6ate)6ate/ 6ate)4=r E /003 6ate)46a= E 3 6ate)4&ont$ E )/ rite a 7un1tion t$at assi'ns va-ues to 6ate/4 Ar'u&ents to t$e 7un1tion &ust ,e %ointers to t$e stru1ture :ate an6 inte'er varia,-es 6ate &ont$ =ear4 =ear4 Date is a structure #ith three int "ariables as members. set]dateG..H is a function used to assign "alues to the structure "ariable. Pro'ra&* Pro'ra& to i--ustrate a 7un1tion t$at assi'ns va-ue to t$e stru1ture4 Vincludestdio.hX Vincludestdlib.hX 33declare structure Date struct Date C int yr int day int month date9+ date/ 33declare function to assign date to structure "ariable "oid set]dateGstruct Date Ldte+ int dt+ int mnt+ int yearH C dte&Xday F dt dte&Xyr F year dte&Xmonth F mnt int mainG"oidH C date9.yr F /AA> date9.day F > 33assigning "alues one by one date9.month F 9/ 33assigning "alues in a single statement set]dateG5date/+ A0+ 9/+ /AA?H 33prints both dates in date3month3year format printfGYn Od Od Od + date9.day+ date9.month+ date9.yrH printfGYn Od Od Od + date/.day+ date/.month+ date/.yrH return A Out%ut* > 9/ /AA> 0 9/ /AA? "9%-anation* T#o "ariables of type Date are created and named @date9@+ @date/@. @date/@ is assigned by using the function set]dateG..H. %ddress %ddress of @date/@ is passed to set]date function.
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
CHAPT"R 2* Fun1tions )4 $at is is t$e %ur%ose %ur%ose o7 &ainG &ainG 7un1ti 7un1tion8 on8 In (+ program execution starts from the mainGH function. E"ery ( program must contain a mainGH function. The main function may contain any number of statements. These statements are executed se'uentially in the order #hich they are #ritten. The main function can in&turn call other functions. When main calls a function+ it passes the execution control to that function. The function returns control to main #hen a return statement is executed or #hen end of function is reached. In (+ the function prototype of the @main@ is one of the follo#ing2 int mainGH 33main #ith no arguments int mainGint argc+ char Larg"JKH 33main #ith arguments The parameters argc and arg" respecti"ely gi"e the number and "alue of the program@s command&line arguments. "9a&%-e* Vinclude stdio.hX 3L program section begins here L3 int mainGH C 33 opening brace & program execution starts here printfGWelcome printfGWelcome to the #orld of (H return A 33 closing brace & program terminates here Out%ut* Welcome to the #orld of ( /4 "9%-ain 1o&&an6 -ine ar'u&ents ar'u&ents o7 &ain 7un1tion8 In (+ #e can supply arguments to @main@ function. The arguments that #e pass to main G H at command prompt are called command line arguments. These arguments are supplied at the time of in"oking the program. The main G H function can take arguments as2 mainGint argc+ char Larg"JKH C The first argument argc is kno#n as @argument counter@. It represents the number of arguments in the command line. The second argument arg" is kno#n as @argument "ector@. It is an a rray of char type pointers that points to the command line arguments. ie of this array #ill be e'ual to the "alue of argc. "9a&%-e* at the command prompt if #e gi"e2 (2YX fruit.exe apple mango then argc #ould contain "alue ; arg" JAK #ould contain base address of string fruit.exe #hich is the command name that in"okes the program. arg" J9K #ould contain base address of string apple arg" J/K #ould contain base address of string mango here apple and mango are the a rguments passed to the program fruit.exe Pro'ra&* Vinclude stdio.hX int mainGint argc+ char Larg"JKH C
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
int n printfG6ollo#ing are the arguments entered in the command lineH for Gn F A n argc nNNH C printfGYn Os+ arg"JnKH printfGYn *umber of arguments entered areYn OdYn+ argcH return A Out%ut* 6ollo#ing are the arguments entered in the command line (2Ytestpro)ect.exe apple mango *umber of arguments entered are ; 24 $at are $ea6er $ea6er 7i-es8 Are 7un1tions 7un1tions 6e1-are6 or 6e7ine6 in $ea6er 7i-es 8 6unctions and macros are declared in header files. Beader files #ould be included in source files by the compiler at the time of compilation. Beader files are included in source code using Vinclude directi"e.Vincludesome.hX directi"e.Vincludesome.hX includes all the declarations present in the header file @some.h@. % header header file may contain contain declarations of sub&routines+ sub&routines+ functions+ macros macros and also "ariables "ariables #hich #e may #ant #ant to use in our program. Beader files help in reduction of repetiti"e code. S=nta9 o7 in1-u6e 6ire1tive* Vincludestdio.hX 33includes the header file stdio.h+ standard input output header into the source code 6unctions can be declared as #ell as defined in header files. ut it is recommended only to declare functions and not to define in the header files. When #e include a header file in our program #e actually are including all the functions+ macros and "ariables declared in it. In case of pre&defined ( standard library header files exGstdio.hH+ the functions calls are replaced by e'ui"alent binary code present in the pre&compiled libraries. (ode for ( standard functions are linked and then the program is executed. Beader files #ith custom names can also be created. Pro'ra&* Custo& $ea6er 7i-es e9a&%-e 3LLLLLLLLLLLLLLLL Index2 restaurant.h LLLLLLLLLLLLLLLL3 int bill%llGint food]cost+ int tax+ int tipH 3LLLLLLLLLLLLLLLL Index2 restaurant.c LLLLLLLLLLLLLLLL3 Vincludestdio.hX int bill%llGint food]cost+ int tax+ int tipH C int result result F food]cost N tax N tip printfGTotal bill is OdYn+resultH return result
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
3LLLLLLLLLLLLLLLL Index2 main.c LLLLLLLLLLLLLLLL3 Vincludestdio.hX Vincluderestaurant.h int mainGH C int food]cost+ tax+ tip food]cost F 0A tax F 9A tip F 0 bill%llGfood]cost+tax+tipH bill%llGfood]cost+tax+tipH return A 34 $at are t$e 6i77eren1es 6i77eren1es ,etween ,etween 7or&a- ar'u&ents ar'u&ents an6 a1tua- ar'u&ents ar'u&ents o7 a 7un1tion8 7un1tion8 %rgument2 %n argument is an an expression #hich is is passed to a function by its caller Gor macro macro by its in"okerH in"okerH in order for the functionGor macroH to perform its task. It is an expression in the comma&separated list bound by the parentheses in a function call expression. A1tua- ar'u&ents* The arguments that are passed in a function call are called actual arguments. These arguments are defined in the calling function. For&a- ar'u&ents* The formal arguments are the parameters3arguments in a function declaration. The scope of formal arguments is local to the function definition in #hich they are used. 6ormal arguments belong to the called function. 6ormal arguments are a cop y of the actual arguments. % change in formal arguments #ould not be reflected in the actual arguments. "9a&%-e* Vinclude stdio.hX "oid sumGint i+ int )+ int kH 3L calling function L3 int mainGH C int a F 0 33 actual arguments sumG;+ / L a+ aH return A 3L called function L3 3L formal argumentsL3 "oid sumGint i+ int )+ int kH C int s s F i N ) N k printfGsum is Od+ sH
Bere ;+/La+a are actual arguments a rguments and i+)+k are formal arguments. 54 $at is %ass %ass ,= va-ue va-ue in 7un1t 7un1tion ions8 s8 Pass by 4alue2 4alue2 In this method+ the "alue of each of the actual arguments in the calling function is copied into
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
corresponding formal arguments of the called function. In pass by "alue+ the changes made to formal arguments in the called function ha"e no effect on the "alues of actual arguments in the calling function.
"9a&%-e* Vinclude stdio.hX "oid s#apGint x+ int yH C int t t F x x F y y F t int mainGH C int m F 9A+ n F /A printfGefore executing s#ap mFOd nFOdYn+ m+ nH s#apGm+ nH printfG%fter executing s#ap mFOd nFOdYn+ m+ nH return A Out%ut* efore executing s#ap mF9A nF/A %fter executing s#ap s#ap mF9A nF/A "9%-anation* In the main function+ "alue of "ariables m+ n are not changed though they are passed to function @s#ap@. #ap function has a copy of m+ n and hence it can not manipulate the actual "alue of arguments passed to it.
;4 $at is is %ass ,= re7eren re7eren1e 1e in 7un1ti 7un1tions ons8 8 Pass ,= Re7eren1e* In Re7eren1e* In this method+ the addresses of actual arguments in the calling function are copied into formal arguments of the called function. This means that using these addresses+ #e #ould ha"e an access to the actual arguments and hence #e #ould be able to manipulate them. ( does not support (all by reference. ut it can be simulated using pointers. "9a&%-e* Vinclude stdio.hX 3L function definition L3 "oid s#apGint Lx+ int LyH C int t t F Lx 3L assign the "alue at address x to t L3 Lx F Ly 3L put the "alue at y into x L3 Ly F t 3L put the "alue at to y L3 int mainGH C int m F 9A+ n F /A printfGefore executing s#ap mFOd nFOdYn+ m+ nH s#apG5m+ 5nH printfG%fter executing s#ap mFOd nFOdYn+ m+ nH return A
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
Out%ut* efore executing s#ap mF9A nF/A %fter executing s#ap s#ap mF/A nF9A "9%-anation* In the main function+ address of "ariables m+ n are sent as arguments to the function @s#ap@. %s s#ap function has the access to address of the arguments+ manipulation of passed arguments inside s#ap function #ould be directly reflected in the "alues of m+ n.
<4 $at are t$e 6i77eren1es 6i77eren1es ,etween ,etween 'et1$arG an6 an6 s1an7G 7un1tions 7un1tions 7or 7or rea6in' strin's8 strin's8 Differences bet#een getchar and scanf functions for reading strings2 s1an7
'et1$ar
9. Entering of each character should be follo#ed by return key.
9. *eed not type return key.
/. (ontinuous stream of characters cannot be directly supplied using scanf function.
/. (ontinuous stream of characters can be directly supplied using getchar function
;. canf function can be used to p ro"ide data at execution time irrespecti"e of its typeGint+ char+ floatH. Example2 Vincludestdio.hX int mainGH C char aJ9AK printfGEnter a2 YnH scanfGOs+aH return A >. scanfGH returns the number of items read successfully. successfully. % return "alue A indicates that no fields #ere read. E86Gend of fileH is returned in case of an error or if end&of&file3end&of&string character is encountered.
;. getcharGH function is used only #ith character type. Example2 Vincludestdio.hX int mainGH C char a printfGEnter any character2 YnH a F getcharGH printfG(haracter entered2Oc Yn+aH return A
>. getcharGH returns the character entered as the "alue of the function. It returns E86 in case of an error. It is recommeded to use getchar instead of scanf.
>4 Out o7 t$e t$e 7un1tions 7un1tions 7'etsG an6 'etsG w$i1$ w$i1$ one is sa7er sa7er to use an6 w$=8 8ut of functions fgetsG H and getsG H+ fgetsG H is safer to use. getsG H recei"es a string from the keyboard and it is terminated only #hen the enter key is hit. There is no limit for the input string. The string can be too long and may lead to buffer o"erflo#. "9a&%-e* getsGsH 3L s is the input string L3 Whereas fgetsG H reads string #ith a specified limit+ from a file and displays it on screen.The function fgetsG H takes three arguments. 6irst argument 2 address #here the string is stored. econd argument 2 maximum length of the string. Third argument 2 pointer to a 6I1E.
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
"9a&%-e* fgetsGs+/A+fpH 3L s2 address of the string+ /A2 maximum length of string+ fp2 pointer to a file L3 The second argument limits the length of string to be read. Thereby it a"oids o"erflo# of input buffer. buffer. Thus fgetsG H is preferable to getsG H.
!. $at is t$e 6i77eren1e ,etween t$e 7un1tions str6u%G an6 str1%=G8 str1%= 7un1tion* copies 7un1tion* copies a source string to a destination defined by user. In strcpy function function both source and destination strings are passed as arguments. Zser should make sure that destination has enough space to accommodate the string to be copied. @strcpy@ sounds like short form of string copy. S=nta9* strcpyGchar Ldestination+ const char LsourceH ource string is the string to be copied and destination string is string into #hich source string is copied. If successful+ strcpy subroutine returns the address of the copied string. 8ther#ise+ a null pointer is returned. "9a&%-e Pro'ra&* Vincludestdio.hX Vincludestring.hX int mainGH C char mynameJ9AK 33copy contents to myname strcpyGmyname+ inter"ie#mantra.netH 33print the string putsGmynameH return A Out%ut* inter"ie#mantra.net "9%-anation* If the string to be copied has more than 9A letters+ strcpy cannot copy this string into the string @myname@. This is because string @myname@ is declared to be of sie 9A characters only. only. In the abo"e program+ string nodalo is copied in myname and is printed on output screen. str6u% 7un1tion* duplicates 7un1tion* duplicates a string to a location that #ill be decided by the function itself. 6unction #ill copy the contents of string to certain memory location and returns the address to that location. @strdup@ sounds like short form of string duplicate S=nta9* strdup Gconst char LsH strdup returns a pointer to a character or base address of an array. 6unction 6unction returns address of the memory location #here the string has been copied. In case free space could not be created then it returns a null po inter. inter. oth strcpy and strdup functions are present in header file string.hX Pro'ra&* Pro'ra& to i--ustrate str6u%G4 Vincludestdio.hX Vincludestring.hX Vincludestdlib.hX int mainGH C char mynameJK F inter"ie#mantra.net inter"ie#mantra.net
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
33name is pointer "ariable #hich can store the address of memory location of string charL name 33contents of myname are copied in a memory address and are assigned to name name F strdupGmynameH 33prints the contents of @name@ putsGnameH 33prints the contents of @myname@ putsGmynameH 33memory allocated to @name@ is no# freed freeGnameH return A Out%ut* inter"ie#mantra.net inter"ie#mantra.net "9%-anation* tring myname consists of inter"ie#mantra.net stored in it. (ontents of myname are copied in a memory address and memory is assigned to name. %t the end of the program+ memory can be freed using freeGnameH
CHAPT"R 3* Pointers )4 $at $at is is a %oint %ointer er in C8 % pointer pointer is a special "ariable in ( language language meant )ust to store store address of any other "ariable "ariable or function. function. Pointer "ariables unlike ordinary "ariables cannot be operated #ith all the arithmetic operations such as @L@+@O@ operators. It follo#s a special arithmetic called as pointer arithmetic. A %ointer is 6e1-are6 as* int Lap int a F 0 In the abo"e t#o statements an integer a #as declared and initialied to 0. % pointer to an integer #ith name ap #as declared. *ext before ap is used apF5a This operation #ould initialie the declared pointer to int. The pointer ap is no# said to point to a. O%erations on a %ointer* •
:ere7eren1in' o%erator o%erator @ @* This @* This operator gi"es the "alue at the address pointed by the pointer . 6or example after the abo"e ( statements if #e gi"e printfGOd+LapH %ctual "alue of a that is 0 #ould be printed. That is because ap points to a.
•
A66ition o%erator @ @* Pointer arithmetic is different from ordinary arithmetic.
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
apFapN9 %bo"e expression #ould #ould not increment the "alue of ap by one+ but #ould increment itit by the number of bytes of the data type it is pointing to. Bere ap is pointing to an integer "ariable hence ap is incremented by / or > b ytes depending upon the compiler. /4 $at are are t$e a6vanta' a6vanta'es es o7 usin' usin' %ointers8 %ointers8 Pointers are special "ariables #hich store address of some other "ariables. S=nta9* datatype S=nta9* datatype Lptr Bere L indicates that ptr is a pointer "ariable #hich represents "alue stored at a particular address. "9a&%-e* int "9a&%-e* int Lp @p@ is a pointer "ariable pointing to address location #here an integer type is stored. A6vanta'es* reference. This is useful #hen large sied 1. Pointers allo# us to pass "alues to functions using call by reference. arrays are passed as arguments to functions. % function function can return more than one "alue by using call by reference. reference. /. Dynamic allocation allocation of memory is possible #ith #ith the help of pointers. ;. We can resie data data structures. 6or instance+ instance+ if an array@s array@s memory is fixed+ it cannot be resied. resied. ut in case of an array #hose memory is created out of malloc can be resied. >. Pointers point to physical memory memory and allo# 'uicker 'uicker access to data.
24 $at are t$e 6i77eren1es 6i77eren1es ,etween ,etween &a--o1G &a--o1G an6 1a--o1G8 %llocation of memory memory at the time time of execution is called called dynamic memory allocation. allocation. It is done using the standard library functions mallocGH and callocGH. It is defined in stdlib.h. &a--o1G* used &a--o1G* used to allocate re'uired number of bytes in memory at runtime. It takes one argument+ "i. sie in bytes to be allocated. S=nta9* "oid L mallocGsie]t sieH "9a&%-e* a F GintLH mallocG>H > is the sie Gin bytesH of memory to be allocated. 1a--o1G* used 1a--o1G* used to allocate re'uired number of bytes in memory at runtime. It needs two arguments "i.+ arguments "i.+ 9. total number of data and /. sie of each data. S=nta9* "oid L callocGsie]t nmemb+ sie]t sieH "9a&%-e* a F GintLH callocG?+ sieofGintHH Bere sieof indicates the sie of the data type and ? indicates that #e #ant to reser"e space for storing ? integers. :i77eren1es ,etween &a--o1G an6 1a--o1G are*
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
9. *umber of arguments differ. /. y default+ memory allocated by mallocGH contains garbage "alues. Whereas memory allocated b y callocGH contains all eros. 34 How to use use rea--o1G to 6=na&i1a--= 6=na&i1a--= in1rease in1rease siJe o7 an a-rea6= a--o1ate6 a--o1ate6 arra=8 rea--o1G* This rea--o1G* This function is used to increase or decrease the sie of any dynamic memory #hich is allocated using mallocGH or callocGH functions. S=nta9* "oid S=nta9* "oid LreallocG"oid Lptr+ sie]t ne#sieH The first argument @ptr@ is a pointer to the memory pre"iously allocated by the malloc or calloc functions. The second argument @ne#sie@ is the sie in bytes+ of a ne# memory region to be allocated by realloc. This "alue can be larger or smaller than the pre"iously a llocated memory. memory. The realloc function ad)usts the old memory region if ne#sie is smaller than the sie of old memory. memory. If the ne#sie is larger than the existing memory sie+ it increases the sie by copying the contents of old memory region to ne# memory region. The function then deallocates the old memory region. realloc function is helpful in managing a dynamic array #hose sie may change during execution. Example2 a program that reads input from standard input may not kno# the sie of data in ad"ance. In this case+ dynamically allocated array can be used so that it is possible allocate the exact amount of memory using realloc function. 54 $at is t$e euiva-ent euiva-ent %ointer e9%ression e9%ression 7or re7errin' re7errin' an e-e&ent aiLMLkL-L aiLMLkL-L in a 7our 7our 6i&ensiona6i&ensiona- arra=8 (onsider a multidimensional array aJ#KJxKJyKJK. In this array+ aJiK gi"es address of aJiKJAKJAKJAK and aJiKN) gi"es the address of aJiKJ)KJAKJAK imilarly+ imilarly+ aJiKJ)K gi"es a ddress of aJiKJ)KJAKJAK and aJiKJ)KNk gi"es the address of aJiKJ)KJkKJAK aJiKJ)KJkK gi"es address of aJiKJ)KJkKJAK aJiKJ)KJkKJAK and aJiKJ)KJkKNl gi"es address of aJiKJ)KJkKJlK aJiKJ)KJkKJlK Bence aJiKJ)KJkKJlK can be accessed using pointers as LGaJiKJ)KJkKNlH #here L stands for "alue at address and aJiKJ)KJkKNl gi"es the address location of aJiKJ)KJkKJlK. Pro'ra&* "9a&%-e %ro'ra& to i--ustrate %ointer 6enotation o7 &u-ti(6i&ensiona- arra=s4 Vincludestdio.hX Vincludestring.hX int mainGH C int aJ;KJ;KJ;KJ;K 33it gi"es address of aJAKJAKJAKJAK . printfG Yn address of array a is Ou+ aH printfGYn address of aJ/KJAKJAKJAK is Ou +gi"en by aJ/K+ Ou gi"en by aN/+ aJ/K+ a N /H printfGYn address of aJ/KJ/KJAKJAK is Ou +gi"en by aJ/KJ/K+ Ou gi"en by aJ/KN/+ aJ/KJ/K+ aJ/K N /H printfGYn address of aJ/KJ/KJ9KJAK is Ou +gi"en by aJ/KJ/KJ9K + Ou gi"en by aJ/KJ/KN9+ aJ/KJ/KJ9K+ aJ/KJ/K N 9H return A Out%ut* address of array a is 70;>A
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
address of aJ/KJAKJAKJAK is 70>>?+ gi"en by aJ/K + 70>>? gi"en by aN/ address of aJ/KJ/KJAKJAK is 70>?>+ gi"en by aJ/KJ/K +70>?> gi"en by aJ/KN/ address of aJ/KJ/KJ9KJAK is 70>
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
return type 2 integer pointer. pJ9AK 2 array of function pointers char L 2 arguments passed to the function Pro'ra&* "9a&%-e %ro'ra& to e9%-ain 7un1tion %ointers4 Vincludestdio.hX Vincludestdlib.hX int LGLpJ9AKHGchar L+ char LH 33a"erage function #hich returns pointer to integer #hose "alue is a"erage of ascii "alue of characters passed by pointers int La"erageGchar L+ char LH 33function #hich returns pointer to integer #hose "alue is sum of ascii "alue of characters passed by pointers int LsumGchar L+ char LH int retrn int mainG"oidH C int i for Gi F A i 0 iNNH C 33pJAK to pJ>K are pointers to a"erage function. function. pJiK F 5Ga"erageH 5Ga"erageH for Gi F 0 i 9A iNNH C 33pJ0K to pJK a"erage function function is called+ from from pJ0K sum is is called. intstrJiK F pJiKG5strJiK+ pJiKG5strJiK+ 5strJi 5strJi N 9KH if Gi 0H C 33prints the a"erage of ascii of both both characters printfG Yn a"erage of Oc and Oc is Od+ Od+ strJiK+ strJi N 9K+LintstrJiKH 9K+LintstrJiKH else C 33prints the sum of ascii ascii of both characters. characters. printfG Yn sum of Oc and Oc is Od+ strJiK+ strJi N 9K+ LintstrJiKH return A 33function a"erage is defined here int La"erageGchar Larg9+ char Larg/H C retrn F GLarg9 N Larg/H 3 / return G5retrnH 33function sum is defined here int LsumGchar Larg9+ char Larg/H C retrn F GLarg9 N Larg/H return G5retrnH
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
Out%ut* a"erage of n and o is 99A a"erage of o and d is 9A0 a"erage of d and a is a"erage of d and a is a"erage of a and l is 9A/ a"erage of l and o is 9A< sum of o and . is 90: sum of . and c is 9>0 sum of c and o is /9A sum of o and m is //A "9%-anation* In this program pJ9AK is an array of function pointers. 6irst fi"e elements of pJ9AK point to the function2 int La"erageGchar Larg9+char Larg/H. *ext fi"e elements point to the function int LsumGchar Larg9+char Larg/H. They return pointer to an integer and accept pointer to char as arguments. Fun1tion avera'e* int La"erageGchar Larg9+char Larg/H This function finds the a"erage of the t#o "alues of the addresses passed to it as arguments and returns address of the a"erage "alue as an integer pointer. Fun1tion su&* int LsumGchar Larg9+char Larg/H This function finds the sum of the t#o "alues of the addresses passed to it as arguments and returns address of the sum "alue as an integer pointer. >4 $at $at is is t$e t$e va-ue va-ue o7 siJeo7aG NsiJeo71$ar G in a 1o6e sni%%et* 1$ar a3LEsri6$arra'$avas$as$ a3LEsri6$arra'$avas$as$isrikant$D isrikant$D "9%-anation* Bere aJ>K is an array #hich holds the address of strings. trings are character arrays themsel"es. Memory re'uired to store an address is > bits. o memory re'uired to store > addresses is e'ual to >L>F97 bits. char L is a pointer "ariable #hich stores the address of a char "ariable. o sieofGchar LH is > bits. Therefore sieofGaH 3sieofGchar LH F 973> F > bytes. ?4 iG $at are t$e 6i77eren1es 6i77eren1es ,etween ,etween t$e C state&ents state&ents ,e-ow* 1$ar str E He--o 1$ar arrL E He--o iiG $et$er 7o--owin' state&ents 'et 1o&%-ie6 or not8 "9%-ain ea1$ state&ent4 arr arr )G E @s@ %rint7sarrG GiH char LstrFBello Bello is an anonymous string present in the memory. @str@ is a pointer "ariable that holds the address of this string. char arrJKFBello This statement assigns space for six characters2 @B@ @e@ @l@ @l@ @o@ @YA@ . @arr@ is the "ariable name assigned to this
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
array of characters. strJ>K and arrJ>K also ha "e different meanings. strJ>K2 adds > to the "alue of @str@ and points to the address same as "alue of str N >. arrJ>K2 points to the fourth element in array named @arr@. GiiH @arr@ is "ariable name of an array. % "ariable name can not be incremented or decremented. Bence arrNN is an in"alid statement and #ould result in a compilation error. LGarrN9HF@s@ @arr@ is the name of a character array that holds string Bello. Zsually+ Zsually+ name of an array points to its base address. Bence "alue of arr is same as 5arrJAK. arrN9 is address of the next element2 5arrJ9K (haracter @s@ is assigned to the second element in a rray @arr@+ thereby string changes from Bello to Bsllo. printfGOs+arr H This statement prints the string stored in character array @arr@.
CHAPT"R 5* Pro'ra&s )4 rite a %ro'ra& to 7in6 7a1toria- o7 t$e 'iven nu&,er nu&,er44 Re1ursion* % Re1ursion* % function function is called @recursi"e@ if a statement #ithin the body of a function calls the same function. It is also called @circular definition@. Recursion is thus a process of defining something in terms of itself. Pro'ra&* To 1a-1u-ate t$e 7a1toria- va-ue usin' re1ursion4 Vinclude stdio.hX int factGint nH int mainGH C int x+ i printfGEnter a "alue for x2 YnH scanfGOd+ 5xH i F factGxH printfGYn6actorial of Od is Od+ x+ iH return A int factGint nH C 3L nFA indicates a terminating condition L3 if Gn F AH C return G9H else C 3L function function calling itself L3 return Gn L factGn & 9HH 3LnLfactGn&9H is is a recursi"e recursi"e expression L3 Out%ut* Enter a "alue for x2 >
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
6actorial of > is /> "9%-anation* factGnH F n L factGn&9H If nF> factG>H F > L factG;H there is a call to factG;H factG;H F ; L factG/H factG/H F / L factG9H factG9H F 9 L factGAH factGAH F 9 factG9H F 9 L 9 F 9 factG/H F / L 9 F / factG;H F ; L / F 7 Thus factG>H F > L 7 F /> Terminating conditionGn F A hereH is a must for a recursi"e program. 8ther#ise the program enters into an infinite loop. /4 rite a %ro'ra& %ro'ra& to 1$e1k 1$e1k w$et$er t$e t$e 'iven nu&,er nu&,er is even or or o664 Pro'ra&* Vinclude stdio.hX int mainGH C int a printfGEnter a2 YnH scanfGOd+ 5aH 3L logic L3 if Ga O / FF AH C printfGThe gi"en number is E4E*YnH else C printfGThe gi"en number is 8DDYnH return A Out%ut* Enter a2 / The gi"en number is E4E* "9%-anation wit$ e9a&%-es* "9a&%-e )* If )* If entered number is an e"en number 1et "alue of @a@ entered is > ifGaO/FFAH then a is an e"en number+ else odd. i.e. ifG>O/FFAH then > is an an e"en number+ number+ else odd. To check #hether > is e"en or odd+ #e need to calculate G>O/H. 3L O GmodulusH implies remainder "alue. L3 3L Therefore if the remainder obtained #hen > is di"ided by / is A+ then > is e"en. L3 >O/FFA is true Thus > is an e"en number. "9a&%-e /* If entered number is an odd number. 1et "alue of @a@ entered is :
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
ifGaO/FFAH then a is an e"en number+ else odd. i.e. ifG:O/FFAH then > is an an e"en number+ number+ else odd. To check #hether : is e"en or odd+ #e need to calculate G:O/H. :O/FFA is false 3L :O/FF9 :O/FF9 condition condition fails fails and else part part is is executed executed L3 Thus : is an odd number. number. 24 rite a %ro'ra& to swa% two nu&,ers nu&,ers usin' a te&%orar= te&%orar= varia,-e4 #apping interchanges the "alues of t#o gi"en "ariables. #o'i1* step92 tempFx step/2 xFy step;2 yFtemp "9a&%-e* if xF0 and yF?+ consider a temporary "ariable temp. step92 tempFxF0 step/2 xFyF? step;2 yFtempF0 Thus the "alues of the "ariables x and y are interchanged. Pro'ra&* Vinclude stdio.hX int mainGH C int a+ b+ temp printfGEnter the "alue of a and b2 YnH scanfGOd Od+ 5a+ 5bH printfGefore s#apping aFOd+ bFOd Yn+ a+ bH 3L#apping logic L3 temp F a a F b b F temp printfG%fter s#apping aFOd+ bFOd+ a+ bH return A Out%ut* Enter the "alues of a and b2 / ; efore s#apping aF/+ bF; %fter s#apping aF;+ bF/ 34 rite a %ro'ra& %ro'ra& to swa% swa% two nu&,ers nu&,ers wit$out wit$out usin' a te&%orar= varia,-e4 varia,-e4 #apping interchanges the "alues of t#o gi"en "ariables. #o'i1* step92 xFxNy step/2 yFx&y step;2 xFx&y "9a&%-e* if xF: and yF> step92 xF:N>F99
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
step/2 yF99&>F: step;2 xF99&:F> Thus the "alues of the "ariables x and y are interchanged. Pro'ra&* Vinclude stdio.hX int mainGH C int a+ b printfGEnter "alues of a and b2 YnH scanfGOd Od+ 5a+ 5bH printfGefore s#apping aFOd+ bFOdYn+ a+bH 3L#apping logic L3 a F a N b b F a & b a F a & b printfG%fter s#apping aFOd bFOdYn+ a+ bH return A Out%ut* Enter "alues of a and b2 / ; efore s#apping aF/+ bF; The "alues after s#apping are aF; bF/
54 rite a %ro'ra& to swa% two nu&,ers nu&,ers usin' ,itwise o%erators4 Pro'ra&* Vinclude stdio.hX int mainGH C int i F 70 int k F 9/A printfGYn "alue of iFOd kFOd before s#apping+ i+ kH i F i ^ k k F i ^ k i F i ^ k printfGYn "alue of iFOd kFOd after s#apping+ i+ kH return A
"9%-anation* i F 70 binary e'ui"alent of 70 is A9AA AAA9 k F 9/A binary e'ui"alent of 9/A is A999 A999 9AAA i F i^k i...A9AA AAA9 k...A999 k...A999 9AAA 9A AA &&&&&&&&& "al of i F AA99 9AA9 &&&&&&&&& k F i^k i...AA99 9AA9
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
k...A999 k...A999 9AAA 9A AA &&&&&&&&& "al of k F A9AA AAA9 binary e'ui"alent of this is 70 &&&&&&&&&Gthat is the initial "alue of iH i F i^k i...AA99 9AA9 k...A9AA AAA9 &&&&&&&&& "al of i F A999 A999 9AAA binary e'ui"alent of this is 9/A &&&&&&&&& Gthat is the initial "alue of of kH
;4 rite a %ro'ra& to 7in6 t$e 'reatest 'reatest o7 t$ree t$ree nu&,ers4 nu&,ers4 Pro'ra&* Vinclude stdio.hX int mainGHC int a+ b+ c printfGEnter a+b+c2 YnH scanfGOd Od Od+ 5a+ 5b+ 5cH if Ga X b 55 a X cH C printfGa is [reater than b and cH else if Gb X a 55 b X cH C printfGb is [reater than a and cH else if Gc X a 55 c X bH C printfGc is [reater than a and bH else C printfGall are e'ual or any t#o "alues are e'ualH return A Out%ut* Enter a+b+c2 ; 0 ? c is [reater than a and b "9%-anation wit$ e9a&%-es* (onsider three numbers aF0+bF>+cF? ifGaXb 55 aXcH then a is greater than b and c no# check this condition for the three numbers 0+>+? i.e. ifG0X> 55 0X?H 3L 0X> is true but 0X? fails L3 so the control shifts to else if condition else ifGbXa 55 bXcH then b is greater than a and c no# checking this condition for 0+>+? i.e. else ifG>X0 55 >X?H 3L both the conditions fail L3 no# the control shifts to the next else if condition else ifGcXa 55 cXbH then c is greater than a and b
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
no# checking this condition for 0+>+? i.e. else ifG?X0 55 ?X>H 3L both conditions are satisfied L3 Thus c is greater than a and b. <4 rite a %ro'ra& to 7in6 t$e 'reatest 'reatest a&on' ten nu&,ers4 nu&,ers4 Pro'ra&* Vinclude stdio.hX int mainGH C int aJ9AK int i int greatest printfGEnter ten "alues2H 33tore 9A numbers in an array for Gi F A i 9A iNNH C scanfGOd+ 5aJiKH 33%ssume that aJAK is greatest greatest F aJAK for Gi F A i 9A iNNH C if GaJiK X greatestH C greatest F aJiK printfGYn[reatest of ten numbers is Od+ greatestH return A
Out%ut* Enter ten "alues2 / 0; 70 ; ?? ? 9> 0 :: 7> [reatest of ten numbers is ?? "9%-anation wit$ e9a&%-e* Entered "alues are /+ 0;+ 70+ ;+ ??+ ?+ 9>+ 0+ ::+ 7> They are stored in an array of sie 9A. let aJK be an array holding these "alues. 3L ho# the greatest among ten numbers is found L3 1et us consider a "ariable @greatest@. %t the beginning of the loop+ "ariable @greatest@ is assinged #ith the "alue of first element in the array greatestFaJAK. Bere "ariable @greatest@ is assigned / as aJAKF/. elo# loop is executed until end of the array @aJK@. forGiFA i9A iNNH C ifGaJiKXgreatestH C greatestF aJiK 6or each "alue of @i@+ "alue of aJiK is compared #ith "alue of "ariable @greatest@. If any "alue greater than the "alue of @greatest@ is encountered+ it #ould be replaced by aJiK. %fter %fter completion of @for@ loop+ the "alue of "ariable @greatest@ holds the greatest number in the array. In this case ?? is the greatest of all the numbers.
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
>4 rite a %ro'ra& to 1$e1k w$et$er t$e t$e 'iven nu&,er is is a %ri&e4 %ri&e4 % prime prime number is a natural natural number that has only only one and itself as factors. Examples2 Examples2 /+ ;+ 9; are prime numbers. Pro'ra&* Vinclude stdio.hX mainGH C int n+ i+ c F A printfGEnter any number n2 YnH scanfGOd+ 5nH 3LlogicL3 for Gi F 9 i F n iNNH C if Gn O i FF AH C cNN if Gc FF /H C printfGn is is a Prime Prime numberH numberH else C printfGn is not a Prime Prime numberH return A
Out%ut* Enter any number n2 : n is Prime "9%-anation wit$ e9a&%-es* consider a number nF0 forGiFAiFniNNH 3L for loop is executed until the n "alue e'uals i L3 i.e. forGiFAiF0iNNH 3L here the for loop is executed until i is e'ual to n L3 9st iteration2 iF9iF0iNN here i is incremented i.e. i "alue for next iteration is / no# ifGnOiFFAH then c is incremented i.e.ifG0O9FFAHthen c is incremented+ here 0O9FA thus c is incremented. no# cF9 /nd iteration2 iF/iF0iNN here i is incremented i.e. i "alue for next iteration is ; no# ifGnOiFFAH then c is incremented i.e.ifG0O/FFAH then c is incremented+ but 0O/FA and so c is not incremented+ c remains 9 cF9 ;rd iteration2 iF;iF0iNN here i is incremented i.e. i "alue for next iteration is > no# ifGnOiFFAH then c is incremented i.e.ifG0O;FFAH then c ic incremented+ but 0O;FA and so c is not incremented+ c remains 9 cF9
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
>th iteration2 iF>iF0iNN here i is incremented i.e. i "alue for next iteration is 0 no# ifGnOiFFAH then c is incremented i.e. ifG0O>FFAH then c is incremented+ but 0O>FA and so c is not incremented+ c remains 9 cF9 0th iteration2 iF0iF0iNN here i is incremented i.e. i "alue for next iteration is 7 no# ifGnOiFFAH then c is incremented i.e. ifG0O0FFAH then c is incremented+ 0O0FA and so c is incremented. i.e. cF/ 7th iteration2 iF7iF0iNN here i "alue is 7 and 7F0 is false thus the condition fails and control lea"es the for loop. no# ifGcFF/H then n is a prime number #e ha"e cF/ from the 0th iteration and thus nF0 is a Prime number. ?4 rite a %ro'ra& %ro'ra& to 1$e1k w$et$er t$e t$e 'iven nu&,er nu&,er is a %a-in6ro&i1 %a-in6ro&i1 nu&,er4 nu&,er4 If a number+ #hich #hen read in both for#ard and back#ard #ay is same+ then such a n umber is called a palindrome number. Pro'ra&* Vinclude stdio.hX int mainGH C int n+ n9+ re" F A+ rem printfGEnter any number2 YnH scanfGOd+ 5nH n9 F n 3L logic L3 #hile Gn X AHC rem F n O 9A re" F re" re" L 9A N rem rem n F n 3 9A if Gn9 FF re"HC printfG[i"en number number is a palindromic numberH numberH elseC printfG[i"en number is not a palindromic palindromic numberH return A Out%ut* Enter any number2 9/9 [i"en number is a palindrome "9%-anation wit$ an e9a&%-e* (onsider a number nF9/9+ re"erseFA+ remainder numberF9/9 no# the #hile loop is executed 3L the condition GnXAH is satisfied L3
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
3L calculate remainder L3 remainder of 9/9 di"ided by 9AFG9/9O9AHF9 no# re"erseFGre"erseL9AHNremainder FGAL9AHN9 3L #e ha"e initialied re"erseFA L3 F9
numberFnumber39A F9/939A F9/ no# the number is 9/+ greater than A. The abo"e process is repeated for numberF9/. remainderF9/O9AF/ re"erseFG9L9AHN/F9/ numberF9/39AF9 no# the number number is 9+ greater than A. A. The abo"e abo"e process is repeated repeated for numberF9. numberF9. remainderF9O9AF9 re"erseFG9/L9AHN9F9/9 numberF939A 3L the condition nXA is not satisfied+control lea"es the #hile loop L3
Program stops here. The gi"en numberF9/9 e'uals the re"erse of the number. Thus the gi"en number is a palindrome number.
)04rite a %ro'ra& to 1$e1k w$et$er t$e 'iven strin' is a %a-in6ro&e4 %a-in6ro&e4 Palindrome is a string+ #hich #hen read in both for#ard and back#ard #ay is same. "9a&%-e* radar+ "9a&%-e* radar+ madam+ pop+ lol+ rubber+ etc.+ Pro'ra&* Vinclude stdio.hX Vinclude string.hX int mainGH C char string9J/AK int i+ length int flag F A printfGEnter a string2 YnH scanfGOs+ string9H length F strlenGstring9H forGiFAi length iNNHC ifGstring9JiK F string9Jlength&i&9KHC string9Jlength&i&9KHC flag F 9 break if GflagH C printfGOs is not a palindromeYn+ palindromeYn+ string9H string9H else C printfGOs is a palindromeYn+ palindromeYn+ string9H return A
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
Out%ut* Enter a string2 radar radar is a palindrome "9%-anation wit$ e9a&%-e* To check if a string is a palindrome or not+ a string needs to be compared #ith the re"erse of itself. (onsider a palindrome string2 radar+ &&&&&&&&&&&&&&&&&&&&&&&&&&& index2 A 9 / ; > "alue2 r a d a r &&&&&&&&&&&&&&&&&&&&&&&&&&& To compare it #ith the re"erse of itself+ the follo#ing logic is used2 Ath character in the char array+ string9 is same as >th character in the same string. 9st character is same as ;rd character. /nd character is same as /nd character. .... ith character is same as @length&i&9@th character. character. If any one of the abo"e condition fails+ flag is set to trueG9H+ #hich implies that the string is not a palindrome. y default+ the "alue of flag is falseGAH. Bence+ if all the conditions are satisfied+ the string is a palindrome. ))4rite a %ro'ra& to 'enerate t$e Fi,ona11i series4 the series is obtained by adding the pre"ious t#o t#o numbers of the series. series. Fi,ona11i series* %ny series* %ny number in the 1et fGnH be n@th term. fGAHFA fG9HF9 fGnHFfGn&9HNfGn&/H Gfor nXF/H eries is as follo#s A 9 9 G9NAH / G9N9H ; G9N/H 0 G/N;H ? G;N0H 9; G0N?H /9 G?N9;H ;> G9;N/9H ...and so on Pro'ra&* to 'enerate Fi,ona11i Series)0 ter&sG Vincludestdio.hX int mainGH C 33array fib stores numbers of fibonacci series int i+ fibJ/0K 33initialied first element to A fibJAK F A
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
33initialied 33initialied second element e lement to 9 fibJ9K F 9 33loop to generate ten elements for Gi F / i 9A iNNH C 33i@th element of series is e'ual to the the sum of i&9@th element and i&/@th element. fibJiK F fibJi & 9K N fibJi & /K printfGThe fibonacci series is as follo#s YnH 33print all numbers in the series for Gi F A i 9A iNNH C printfGOd Yn+ fibJiKH return A Out%ut* The fibonacci series is as follo#s A 9 9 / ; 0 ? 9; /9 ;> "9%-anation* The first t#o elements are initialied to A+ 9 respecti"ely. 8ther elements in the series are generated by looping and adding pre"ious t#o numbes. These numbers are stored in an array and ten elements of the series are printed as output. )/4rite a %ro'ra& to %rint He--o or-6 wit$out usin' se&i1o-on an=w$ere in t$e 1o6e4 [enerally #hen #e use printfGH statement+ #e ha"e to use a semicolon at the end. If printf is used inside an if condition+ semicolon can be a"oided. Pro'ra&* Pro'ra& to %rint so&e t$in' wit$ out usin' se&i1o-onG Vinclude stdio.hX int mainGH C 33printf returns the length of string being printed if GprintfGBello WorldYnHH WorldYnHH 33prints Bello World and returns 99 C 33do nothing return A Out%ut* Bello World "9%-anation* The if statement checks for condition #hether the return "alue of printfGBello WorldH is greater than A. p rintf
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
function returns the length of the string printed. Bence the statement if GprintfGBello WorldHH prints the string Bello World. )24rite a %ro'ra& to %rint a se&i1o-on wit$out usin' a se&i1o-on an=w$ere in t$e 1o6e4 [enerally #hen use printfGH statement #e ha"e to use semicolon at the end. If #e #ant to print a semicolon+ #e use the statement2 printfGH In abo"e statement+ #e are using t#o semicolons. The task of printing a semicolon #ithout using semicolon any#here in the code can be accomplished by using the ascii "alue of @ @ #hich is e'ual to 0<. Pro'ra&* Pro'ra& to %rint a se&i1o-on wit$out usin' se&i1o-on in t$e 1o6e4 Vinclude stdio.hX int mainG"oidH C 33prints the character #ith ascii "alue 0<+ i.e.+ semicolon if GprintfGOcYn+ 0
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
int k F strlenGs/H int bigger if Gi kH C bigger F k k else if Gi X kH C bigger F ii else C bigger F ii 33loops @bigger@ times for Gi F A i bigger iNNH C 33if ascii "alues "alues of characters s9JiK+ s9JiK+ s/JiK are e'ual do nothing if Gs9JiK Gs9JiK FF s/JiKH s/JiKH C 33else return the ascii difference difference else C return Gs9JiK & s/JiKH 33return A #hen both strings are same 33This statement is executed only #hen both strings are e'ual return GAH Out%ut* &;/ "9%-anation* cmpstrGH is a function that illustrates ( standard function strcmpGH. trings to be compared are sent as arguments to cmpstrGH. Each character in string9 is compared to its corresponding character in string/. 8nce the loop encounters a differing character in the strings+ it #ould return the ascii difference of the differing characters and exit. )54rite a %ro'ra& to 1on1atenate two strin's wit$out usin' str1atG 7un1tion4 strcatGstring9+string/H strcatGstring9+string/H is a ( standard function declared in the header file string.h The strcatGH function concatenates string/+ string9 and returns string9. Pro'ra&* Pro'ra& to 1on1atenate two strin's Vincludestdio.hX Vincludestring.hX char LstrctGchar Lc9+ char Lc/H char LstrctGchar Lc9+ char Lc/H C 33strlen function returns length of argument string int i F strlenGc9H int k F A 33loops until null is encountered and appends string c/ to c9 #hile Gc/JkK F @YA@H C c9Ji N kK F c/JkK kNN
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
return c9 int mainGH C char string9J90K F first char string/J90K F second char Lfinalstr printfGefore concatenation2 Yn string9 F Os Yn string/ F Os+ string9+ string/H 33addresses of string9+ string/ are passed to strctGH finalstr F strctGstring9+ string/H printfGYn%fter concatenation2H 33prints the contents of string #hose address is in finalstr printfGYn finalstr F Os+ finalstrH 33prints the contents of string9 printfGYn string9 F Os+ string9H 33prints the contents of string/ printfGYn string/ F Os+ string/H return A Out%ut* efore concatenation2 string9 F first string/ F second %fter concatenation2 finalstr F firstsecond string9 F firstsecond string/ F second "9%-anation* string/ is appended at the end of string9 and contents of string/ are unchanged. In strctGH function+ using a for loop+ all the characters of string @c/@ are copied at the end of c9. return Gc9H is e'ui"alent to return 5c9JAK and it returns the base address of @c9@. @finalstr@ stores that address returned by the function strctGH. );4rite a %ro'ra& to 6e-ete a s%e1i7ie6 -ine 7ro& a te9t 7i-e4 In this program+ user is asked for a filename he needs to change. Zser is also asked for the line number that is to be deleted. The filename is stored in @filename@. The file is opened and all the data is transferred to another file except that one line the user specifies to delete. Pro'ra&* Pro'ra& to 6e-ete a s%e1i7i1 -ine4 Vinclude stdio.hX int mainGH C 6I1E Lfp9+ Lfp/ 33consider >A character string to store filename char filenameJ>AK char c int del]line+ temp F 9 33asks user for file name printfGEnter file name2 H
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
33recei"es file name from user and stores in @filename@ scanfGOs+ filenameH 33open file in read mode fp9 F fopenGfilename+ rH c F getcGfp9H 33until the last character of file is obtained #hile Gc F E86H C printfGOc+ cH 33print current character and read next character c F getcGfp9H 33re#ind re#indGfp9H printfG Yn Enter line number of the line to be deleted2H 33accept number from user. scanfGOd+ 5del]lineH 33open ne# file in #rite mode fp/ F fopenGcopy.c+ fopenGcopy.c+ #H c F getcGfp9H #hile Gc F E86H C c F getcGfp9H if Gc FF @Yn@H tempNN 33except the line to be deleted if Gtemp F del]lineH C 33copy all lines in file copy.c putcGc+ fp/H 33close both the files. fcloseGfp9H fcloseGfp/H 33remo"e original file remo"eGfilenameH 33rename the file copy.c copy.c to original name renameGcopy.c+ renameGcopy.c+ filenameH printfGYn The contents of file after being modified are as follo#s2YnH fp9 F fopenGfilename+ rH c F getcGfp9H #hile Gc F E86H C printfGOc+ cH c F getcGfp9H fcloseGfp9H return A
Out%ut* Enter file name2abc.txt hi. hello
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
ho# are you= I am fine hope the same Enter line number of the line to be deleted2> The contents of file after being modified are as follo#s2 hi. hello ho# are you= hope the same "9%-anation* In this program+ user is asked for a filename that needs to be modified. Entered file name is stored in a char array @filename@. This file is opened in read mode using file pointer @fp9@. (haracter @c@ is used to read characters from the file and print them to the output. Zser is asked for the line number in the file to be deleted. The file pointer is re#inded back and all the lines of the file except for the line to be deleted are copied into another file copy.c. copy.c. *o# copy.c is renamed to the o riginal filename. The original file is opened in read mode and the modified contents of the file are displayed on the screen. )<4rite a %ro'ra& to re%-a1e a s%e1i7ie6 -ine in a te9t 7i-e4 Pro'ra&* Pro'ra& Pro'ra& to re%-a1e a s%e1i7ie6 -ine in a te9t 7i-e4 Vinclude stdio.hX int mainG"oidH C 6I1E Lfp9+ Lfp/ 33@filename@is a >A character string to store filename char filenameJ>AK char c int del]line+ temp F 9 33asks user for file name printfGEnter file name2 H 33recei"es file name from user and stores in @filename@ scanfGOs+ filenameH fp9 F fopenGfilename+ rH 33open file in read mode c F getcGfp9H 33print the contents of file . #hile Gc F E86H C printfGOc+ cH c F getcGfp9H 33ask user for line number to be deleted. printfG Yn Enter line number to be deleted and replacedH scanfGOd+ 5del]lineH 33take fp9 to start point. re#indGfp9H 33open copy.c in #rite mode fp/ F fopenGcopy.c+ fopenGcopy.c+ #H c F getcGfp9H #hile Gc F E86H C if Gc FF @Yn@H C tempNN 33till the line to be deleted comes+copy the content from one file to other if Gtemp F del]lineHC putcGc+ fp/H
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
else 33#hen the line to be deleted comes C #hile GGc F getcGfp9HH F @Yn@H C 33read and skip the line ask for ne# text printfGEnter ne# textH 33flush the input stream fflushGstdinH fflushGstdinH putcG@Yn@+ fp/H 33put @Yn@ in ne# file #hile GGc F getcharGHH F @Yn@H putcGc+ fp/H 33take the data from user and place it in ne# file fputsGYn+ fp/H tempNN 33continue this till E86 is encountered c F getcGfp9H 33close both files fcloseGfp9H fcloseGfp/H 33remo"e original file remo"eGfilenameH 33rename ne# file #ith old name opens the file in read mode renameGcopy.c+ renameGcopy.c+ filenameH fp9 F fopenGfilename+ rH 33reads the character from file c F getcGfp9H 33until last character of file is encountered #hile Gc F E86HC printfGOc+ cH 33all characters are printed c F getcGfp9H 33close the file pointer fcloseGfp9H return A Out%ut* Enter file name2abc.txt hi. hello ho# are you= hope the same Enter line number of the line to be deleted and replaced2> Enter ne# text2 sayonara see you soon hi. hello ho# are you= sayonara see you soon
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
"9%-anation* In this program+ the user is asked to type the name of the file. The 6ile by name entered by user is opened in read mode. The line number of the line to be replaced is asked as input. *ext the data to be replaced is asked. % ne# file is opened in #rite mode named copy.c. copy.c. *o# the contents of original file are transferred into ne# file and the line to be modified is deleted. *e# data is stored in its place and remaining lines of the original file are also transferred. The copied file #ith modified contents is replaced #ith the original file@s name. oth the file pointers are closed and the original file is again opened in read mode and the contents of the original file is printed as output. )>4rite a %ro'ra& to 7in6 t$e nu&,er o7 -ines in a te9t 7i-e4 *umber of lines in a file can be determined by counting the number of ne# line characters present. Pro'ra&* Pro'ra& to 1ount nu&,er o7 -ines in a 7i-e4 Vinclude stdio.hX int mainGH 3L %sk for a filename and count number of lines in the fileL3 C 33a pointer to a 6I1E structure 6I1E Lfp int no]lines F A 33consider >A character string to store filename char filenameJ>AK+ sample]chr 33asks user for file name printfGEnter file name2 H 33recei"es file name from user and stores in a string named @filename@ scanfGOs+ filenameH 33open file in read mode fp F fopenGfilename+ rH 33get character from file and store in sample]chr sample]chr F getcGfpH #hile Gsample]chr F E86H C 33(ount #hene"er sample]chr is @Yn@Gne# lineH is encountered if Gsample]chr FF @Yn@H C 33increment "ariable @no]lines@ by 9 no]linesFno]linesN9 33take next character from file. sample]chr F getcGfpH fcloseGfpH 33close file. printfGThere are Od lines in Os Yn+ no]lines+ filenameH return A Out%ut* Enter file name2abc.txt There are > lines in abc.txt "9%-anation* In this program+ name of the file to be read is taken as input. % file file by the gi"en name is opened in read&mode using a 6ile pointer @fp@. (haracters from the file are read into a char "ariable @sample]chr@ #ith the help of getc function. If a ne# line characterG@Yn@H is encountered+ the integer "ariable @no]lines@ is incremented. If the
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
character read into @sample]char@ is not a ne# line character+ next character is read from the file. This process is continued until the last character of the fileGE86H is encountered. The file pointer is then closed and the total number of lines is sho#n as output. )?4rite a C %ro'ra& w$i1$ asks t$e user 7or a nu&,er ,etween ) to ? an6 s$ows t$e nu&,er4 nu&,er4 I7 t$e user in%uts a nu&,er out o7 t$e s%e1i7ie6 ran'e t$e %ro'ra& s$ou-6 s$ow an error an6 %ro&%t t$e user 7or a va-i6 in%ut4 Pro'ra&* Pro'ra& 7or a11e%tin' a nu&,er in a 'iven ran'e4 Vincludestdio.hX int getnumberGH int mainGH C int input F A 33call a function to input number from key board input F getnumberGH 33#hen input is not in the range of 9 to <+print error message #hile GGGinput F 0 JERR8RK The number you entered is out of range Enter a number bet#een 9 to < > The number you entered is > "9%-anation* getfunctionGH function accepts input from user. @#hile@ loop checks #hether the number falls #ithin range or not and accordingly either prints the numberGIf the number falls in desired rangeH or sho#s error messageGnumber is out of rangeH. /04rite a %ro'ra& to 6is%-a= t$e &u-ti%-i1ation ta,-e o7 a 'iven nu&,er4 Pro'ra&* u-ti%-i1ation ta,-e o7 a 'iven nu&,er Vinclude stdio.hX int mainGH C int num+ i F 9 printfGYn Enter any *umber2H
Material from Interview Mantra. Mantra . Subscribe to free updates via email.
scanfGOd+ 5numH printfGMultiplication printfGMultiplication table of Od2 Yn+ numH #hile Gi F 9AH C printfGYn Od x Od F Od+ num+ i+ num L iH iNN return A
Out%ut* Enter any *umber20 0 x 9 F 0 0 x / F 9A 0 x ; F 90 0 x > F /A 0 x 0 F /0 0 x 7 F ;A 0 x : F ;0 0 x ? F >A 0 x < F >0 0 x 9A F 0A "9%-anation* We need to multiply the gi"en number Gi.e. the number for #hich #e #ant the multiplication tableH #ith "alue of @i@ #hich increments from 9 to 9A.
reetin's Ho%e =ou ,ene7ite6 usin' t$is 7ree eBook4 -a6 to ,e o7 servi1e to =ou4 Re&e&,er to Su,s1ri,e to Interview antra via antra via e&ai-4 −
ridhar !ammalamadaka+ Inter"ie# Mantra
rite 7or us %re you a passionate ( programmer= Would Would you like to #rite #rite articles for Inter"ie# Mantra Mantra and earn money= (ontact us "ia email sria"r,gmail.com 3 Zse our contact form to form to get in touch #ith us. We don@t look at 'ualifications+ #e #ant people #ho are really interested in computer programming. Many students #ork for Inter"ie# Mantra part time and get paid for their #ork. We also are looking for students #ith good English #ritten communication skills #ho can #rite articles related to the topics career and education.