You are on page 1of 48

Material from Interview Mantra. Subscribe to free updates via email.

Material from Interview 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 help 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 the 'uestions ha"e been neatly ans#ered and ha"e been supported #ith example code #here"er applicable. % lot of effort has been put into this book to make the ans#ers as accurate as 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

COPYRI HT I!FO
( language - Inter"ie# $uestion .ank by ridhar !ammalamadaka is licensed under a (reati"e (ommons %ttribution& hare %like /.0 India 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 #ork to the o#ner & ridhar !ammalamadaka.

CO!T"!TS AT A
1. 2. 3. 4. .

#A!C"

C$a%ter !a&e %'(no 4ariables 5 (ontrol 6lo# . . . . . . . . . . . . . . . . . . . . 7 8perators+ (onstants 5 tructures . . . . . . . . . . . .99 6unctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9: Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ./; Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ./<

Material from Interview Mantra. Subscribe to free updates via email.

TAB#" OF CO!T"!TS
CHAPT"R )* +aria,-es . Contro- F-ow 9. What is the difference bet#een declaring a "ariable and defining a "ariable= /. What is a static "ariable= ;. What is a register "ariable= >. Where is an auto "ariable stored= 0. What is scope 5 storage allocation of extern and global "ariables= 7. What is scope 5 storage allocation of register+ static and local "ariables= :. What are storage memory+ default "alue+ scope and life of %utomatic and Register storage class= ?. What are storage memory+ default "alue+ scope and life of tatic and External storage class= <. What is the difference bet#een @break@ and @continue@ statements= 9A. What is the difference bet#een @for@ and @#hile@ loops= CHAPT"R /* O%erators0 Constants . Stru1tures 9. Which bit#ise operator is suitable for checking #hether a particular bit is 8* or 866= /. Which bit#ise operator is suitable for turning 866 a particular bit in a number= ;. What is e'ui"alent of multiplying an unsigned int by /2 left shift of number by 9 or right shift of number by 9= >. What is an Enumeration (onstant= 0. What is a structure= 7. What are the differences bet#een a structure and a union= :. What are the ad"antages of unions= ?. Bo# can typedef be to define a type of structure= <. Write a program that returns ; numbers from a function using a structure. 9A. In code snippet belo#2 struct Date C int yrD int dayD int monthD E date9+date/D date9.yr F /AA>D date9.day F >D date9.month F 9/D Write a function that assigns "alues to date/. %rguments to the function must be pointers to the structure+ Date and integer "ariables date+ month+ year.

Material from Interview Mantra. Subscribe to free updates via email.

CHAPT"R 2* Fun1tions 9. What is the purpose of mainGH function= /. Explain command line arguments of main function= ;. What are header files= %re functions declared or defined in header files = >. What are the differences bet#een formal arguments and actual arguments of a function= 0. What is pass by "alue in functions= 7. What is pass by reference in functions= :. What are the differences bet#een getcharGH and scanfGH functions for reading strings= ?. 8ut of the functions fgetsGH and 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 is a pointer in (= /. What are the ad"antages of using pointers= ;. What are the differences bet#een mallocGH and callocGH= >. Bo# to use reallocGH to dynamically increase siIe of an already allocated array= 0. What is the e'ui"alent pointer expression for referring an element aJiKJ)KJkKJlK+ in a four dimensional array= 7. Declare an array of three function pointers #here each function recei"es t#o integers and returns float. :. Explain the "ariable assignment in the declaration int LGLpJ9AKHGchar L+ char LHD ?. What is the "alue of siIeofGaH 3siIeofGchar LH in a code snippet2 char LaJ>KFCMsridharM+Mragha"aM+MshashiM+MsrikanthMED <. GiH What are the differences bet#een the ( statements belo#2 char Lstr F MBelloMD char arrJK F MBelloMD GiiH Whether follo#ing statements get complied or not= Explain each statement. arrNND LGarr N 9H F @s@D printfGMOsM+arrHD CHAPT"R 5* Pro'ra&s 9. Write a program to find factorial of the gi"en number. /. Write a program to check #hether the gi"en number is e"en or odd. ;. Write a program to s#ap t#o numbers using a temporary "ariable. >. Write a program to s#ap t#o numbers #ithout using a temporary "ariable.

Material from Interview Mantra. Subscribe to free updates via email.

0. Write a program to s#ap t#o numbers using bit#ise operators. 7. Write a program to find the greatest of three numbers. :. Write a program to find the greatest among ten numbers. ?. Write a program to check #hether the gi"en number is a prime. <. Write a program to check #hether the gi"en number is a palindromic 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 MBello WorldM #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 file. 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
PThank you soooo much for all these 'uestions+ along #ith the solutions. ItQs a great compilation. Thanks a lot guys. 2H R

Anonymous says
P%#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 again.R

Urmi says
PThank Sou..It@s *ice..It sa"ed my "aluable Time.. Thanks a lotTR

Rajakumari says
PThank you so ... much Mr. ridhar. *o #ords to say + lot of thanksUU 4ery useful to freshers 5 experienced.R

Material from Interview Mantra. Subscribe to free updates via email.

CHAPT"R )* +aria,-es . Contro- F-ow


)4 5$at is t$e 6i77eren1e ,etween 6e1-arin' a varia,-e an6 6e7inin' a varia,-e8 Declaration of a "ariable in ( hints the compiler about the type and siIe of the "ariable in compile time. imilarly+ declaration of a function hints about type and siIe of function parameters. *o space is reser"ed in memory for any "ariable in case of declaration. "9a&%-e* int aD 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 MDefinition F Declaration N pace reser"ationM. "9a&%-e* int a F 9AD Bere "ariable MaM is described as an int to the compiler and memory is allocated to hold "alue 9A. /4 5$at is a stati1 varia,-e8 % static "ariable is a special "ariable that is stored in the data segment unlike the default automatic "ariable that is stored in stack. % static "ariable can be initialiIed by using key#ord static before "ariable name. "9a&%-e* static int a F 0D % static "ariable beha"es in a different manner depending upon #hether it is a global "ariable or a local "ariable. % static global "ariable is same as an ordinary global "ariable except that it cannot be accessed by other files in the same program 3 pro)ect e"en #ith the use of key#ord extern. % static local "ariable is different from local "ariable. It is initialiIed 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 Wstdio.hX 33program in file f9.c "oid countG"oidH C static int count9 F AD int count/ F AD count9NND count/NND printfGMYn4alue of count9 is Od+ 4alue of count/ is OdM+ count9+ count/HD E 3LMain functionL3 int mainGHC countGHD countGHD countGHD return AD E Out%ut* 4alue of count9 is 9+ 4alue of count/ is 9 4alue of count9 is /+ 4alue of count/ is 9

Material from Interview Mantra. Subscribe to free updates via email.

4alue of count9 is ;+ 4alue of count/ is 9

24 5$at is a re'ister varia,-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. 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 xF0D 4ariables for loop counters can be declared as register. *ote that register key#ord may be ignored by some compilers. 34 5$ere is an auto varia,-es store68 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 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. :e7au-t va-ue * garbage "alue. S1o%e * local to the block in #hich the "ariable is defined. #i7eti&e * till the control remains #ithin the block in #hich the "ariable is defined. 54 5$at is s1o%e . stora'e a--o1ation o7 e9tern an6 '-o,a- varia,-es8 "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 Wstdio.hX extern int xD int mainGH C printfGM"alue of x OdM+ xHD return AD E Index2 f/.c LLLLLLLLLLLLLLLL3 int x F ;D 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.

Material from Interview Mantra. Subscribe to free updates via email.

-o,a- 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 Iero.

"9a&%-e* Vinclude Wstdio.hX int x F AD 3L 4ariable x is a global "ariable. It can be accessed throughout the program L3 "oid incrementG"oidH C x F x N 9D printfGMYn "alue of x2 OdM+ xHD E int mainGHC printfGMYn "alue of x2 OdM+ xHD incrementGHD return AD E ;4 5$at is s1o%e . stora'e a--o1ation o7 re'ister0 stati1 an6 -o1a- varia,-es8 Re'ister 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 yF7D Stati1 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 Wstdio.hX "oid decrementGHC static int aF0D a&&D printfGM4alue of a2OdYnM+ aHD E int mainGHC decrementGHD return AD E Bere @a@ is initialiIed only once. E"ery time this function is called+ @a@ does not get initialiIed. so output #ould be > ; / etc.+ #o1a- 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 5$at are stora'e &e&or=0 6e7au-t va-ue0 s1o%e an6 -i7e o7 Auto&ati1 an6 Re'ister stora'e 1-ass8 )4 Auto&ati1 stora'e 1-ass* Stora'e * :e7au-t va-ue * main memory. garbage "alue.

Material from Interview Mantra. Subscribe to free updates via email.

S1o%e #i7eti&e Stora'e :e7au-t va-ue S1o%e #i7eti&e

* * * * * *

local to the block in #hich the "ariable is defined. till control remains #ithin the block. (PZ registers. garbage "alue. local to the block in #hich the "ariable is defined. till control remains #ithin the block.

/4 Re'ister stora'e 1-ass*

>4 5$at are stora'e &e&or=0 6e7au-t va-ue0 s1o%e an6 -i7e o7 Stati1 an6 "9terna- stora'e 1-ass8 )4 Stati1 stora'e 1-ass* Stora'e :e7au-t va-ue S1o%e #i7eti&e Stora'e :e7au-t va-ue S1o%e #i7eti&e * * * * * * * * main memory. Iero local to the block in #hich the "ariable is defined. till the "alue of the "ariable persists bet#een different function calls. main memory Iero global as long as the program execution doesn@t come to an end.

/4 "9terna- stora'e 1-ass*

?4 5$at is t$e 6i77eren1e ,etween @,reak@ an6 @1ontinue@ state&ents8 :i77eren1es ,etween @,reak@ an6 @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 C tatement 9D tatement /D tatement nD breakD E ;. break can be used #ith 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. >. Example2 i F 9+ ) F AD #hileGiWF0H C iFiN9D ifGiFF /H 1ontinue

9. continue is a key#ord used for skipping the current iteration and go to next iteration of the loop /. yntax2 C tatement 9D continueD tatement /D E ;. 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 do&#hile. >. Example2 i F 9+ ) F AD #hileGiWF0H C iFiN9D ifGiFF /H

Material from Interview Mantra. Subscribe to free updates via email.

breakD )F)N9D E

continueD )F)N9D E

)04 5$at is t$e 6i77eren1e ,etween @7or@ an6 @w$i-e@ -oo%s8 7or -oo%* When it is desired to do initialiIation+ condition check and increment3decrement in a single statement of an iterati"e loop+ it is recommended to use @for@ loop. S=nta9* forGinitialiIationDconditionDincrement3decrementH C 33block of statements increment or decrement E Pro'ra&* Program to illustrate for loop VincludeWstdio.hX int mainGH C int iD for Gi F 9D i WF 0D iNNH C 33print the number printfGMYn OdM+ iHD E return AD E 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 it is not necessary to do initialiIation+ 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* VincludeWstdio.hX int mainGH C int i F A+ flag F AD int aJ9AK F C A+ 9+ >+ 7+ ?<+ 0>+ :?+ /0+ 7;0+ 0AA ED 33This loop is repeated until the condition is false.

Material from Interview Mantra. Subscribe to free updates via email.

#hile Gflag FF AH C if GaJiK FF 0>H C 33as element is found+ flag F 9+the loop terminates flag F 9D E else C iNND E E printfGMElement found at Od th locationM+ iHD return AD E Out%ut* Element found at 0th location "9%-anation* Bere flag is initialiIed to Iero. @#hile@ loop repeats until the "alue of flag is Iero+ 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%erators0 Constants . Stru1tures


)4 5$i1$ ,itwise o%erator is suita,-e 7or 1$e1kin' w$et$er a %arti1u-ar ,it is O! or OFF8 Bitwise A!: o%erator4 "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 5$i1$ ,itwise o%erator is suita,-e 7or turnin' OFF a %arti1u-ar ,it in a nu&,er8 .it#ise %*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. "9%-anation* (onsider+

Material from Interview Mantra. Subscribe to free updates via email.

char byte]dataF AbAAA9A999D byte]dataF Gbyte]dataH5G\G9WW>HHD 9 can be represented in binary as AbAAAAAAA9 F G9WW>H WW is a left bit shift operator+ it shifts the bit 9 by > places to#ards left. G9WW>H becomes AbAAA9AAAA %nd \ is the one@s complement operator in ( language. o \G9WW>H F complement of AbAAA9AAAA F Ab999A9999 Replacing "alue of byte]data and \G9WW>H in Gbyte]dataH5G\G9WW>HHD #e get GAbAAA9A999H 5 GAb999A9999H Perform %*D operation to belo# bytes. AAA9A999 999A9999 &&&&&&&&&&& AAAAA999 &&&&&&&&&&& Thus the >th bit is unset. 24 5$at is eAuiva-ent o7 &u-ti%-=in' an unsi'ne6 int ,= /* -e7t s$i7t o7 nu&,er ,= ) or 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>WW9D (onsider a number 9>&&&&&AAAA999A G?N>N/His its binary e'ui"alent left shift it by 9&&&&&&&&&&&&&&AAA999AAG97N?N>H #hich is /?. Eg/2 9WW9D 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 to illustrate left shift and right shift operations. VincludeWstdio.hX int mainG"oidH C int xF9A+yF9AD printfGMleft shift of 9A is Od YnM+xWW9HD printfGMright shift of 9A is Od YnM+yXX9HD return AD E 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. Subscribe to free updates via email.

34 5$at is an "nu&eration Constant8 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 light]status as a data type. It can ha"e t#o possible "alues & on or off. enum light]status C on+ off ED enum light]status bulb9+ bulb/D 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 onD bulb/ F offD 54 5$at is a stru1ture8 % structure is a 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]numberD char nameJ;AKD int total]marksD This concept #ould be particularly useful in grouping data types. Sou could declare a structure student as2 struct student C int roll]numberD char nameJ;AKD int total]marksD E student9+ student/D The abo"e snippet of code #ould declare a structure by name student and it initialiIes 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 5$at are t$e 6i77eren1es ,etween a stru1ture an6 a union8 tructures and Znions are used to store members of different data types. STRUCTUR" aH:e1-aration* aH:e1-aration* struct C data type member9D data type member/D ED union C data type member9D data type member/D ED U!IO!

bHE"ery structure member is allocated memory #hen bHThe memory e'ui"alent to the largest item is allocated a structure "ariable is defined. commonly for all members. "9a&%-e* "9a&%-e*

Material from Interview Mantra. Subscribe to free updates via email.

struct emp C char nameJ0KD int ageD float salD ED struct emp e9D 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 initialiIed at a time struct st C int aD float bD ED struct st s F C .aF>+ .bF9A.0 ED tructure is used #hen all members are to be independently used in a program.

union emp9 C char nameJ0KD int ageD float salD ED union emp9 e/D Memory allocated to a union is e'ual to siIe of the largest member. In this case+ float is the largest&siIed data type. Bence memory allocated to this union is > bytes. cH8nly one union member can be initialiIed at a time union un C int aD float bD ED union un un9 F C .aF9A ED Znion is used #hen members of it are not re'uired to be accessed at the same time.

<4 5$at are t$e a6vanta'es o7 unions8 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 siIe of the members. The data is interpreted in bytes depending on #hich member is being accessed. "9a&%-e* union pen C char nameD float pointD ED 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. 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 at the same time. >4 How 1an t=%e6e7 ,e to 6e7ine a t=%e o7 stru1ture8 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 types. *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/AKD int ageD ED

Material from Interview Mantra. Subscribe to free updates via email.

struct employee eD The abo"e declaration of the structure #ould be easy to use #hen renamed using typedef as2 struct employee C char nameJ/AKD int ageD ED typedef struct employee EMPD EMP e9+ e/D ?4 5rite a %ro'ra& t$at returns 2 nu&,ers 7ro& a 7un1tion usin' a stru1ture4 % function in ( can return only one "alue. If #e #ant the function to return multiple "alues+ #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 VincludeWstdio.hX 33sample structure #hich has three integer "ariables. struct sample C int a+ b+ cD ED 33this is function #hich returns three "alues. struct sample return;"alGH C struct sample s9D s9.a F 9AD s9.b F /AD s9.c F ;AD 33return structure s9+ #hich means return s9.a +s9.b and s9.c return s9D E int mainGH C struct sample accept;"alD 33three "alues returned are accepted by structure accept;"al. accept;"al F return;"alGHD 33prints the "alues printfGM Yn OdM+ accept;"al.aHD printfGMYn OdM+ accept;"al.bHD printfGM Yn OdM+ accept;"al.cHD return AD E 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. Subscribe to free updates via email.

)04 In 1o6e sni%%et ,e-ow* stru1t :ate B int =rC int 6a=C int &ont$C D 6ate)06ate/C 6ate)4=r E /003C 6ate)46a= E 3C 6ate)4&ont$ E )/C 5rite a 7un1tion t$at assi'ns va-ues to 6ate/4 Ar'u&ents to t$e 7un1tion &ust ,e %ointers to t$e stru1ture0 :ate an6 inte'er varia,-es 6ate0 &ont$0 =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 VincludeWstdio.hX VincludeWstdlib.hX 33declare structure Date struct Date C int yrD int dayD int monthD E date9+ date/D 33declare function to assign date to structure "ariable "oid set]dateGstruct Date Ldte+ int dt+ int mnt+ int yearH C dte&Xday F dtD dte&Xyr F yearD dte&Xmonth F mntD E int mainG"oidH C date9.yr F /AA>D date9.day F >D 33assigning "alues one by one date9.month F 9/D 33assigning "alues in a single statement set]dateG5date/+ A0+ 9/+ /AA?HD 33prints both dates in date3month3year format printfGMYn Od Od Od M+ date9.day+ date9.month+ date9.yrHD printfGMYn Od Od Od M+ date/.day+ date/.month+ date/.yrHD return AD E 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 of @date/@ is passed to set]date function.

Material from Interview Mantra. Subscribe to free updates via email.

CHAPT"R 2* Fun1tions
)4 5$at is t$e %ur%ose o7 &ainFG 7un1tion8 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 mainGHD 33main #ith no arguments int mainGint argc+ char Larg"JKHD 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 Wstdio.hX 3L program section begins here L3 int mainGH C 33 opening brace & program execution starts here printfGMWelcome to the #orld of (MHD return AD E 33 closing brace & program terminates here Out%ut* Welcome to the #orld of ( /4 "9%-ain 1o&&an6 -ine 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 E 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 array of char type pointers that points to the command line arguments. iIe 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 M fruit.exeM #hich is the command name that in"okes the program. arg" J9K #ould contain base address of string MappleM arg" J/K #ould contain base address of string MmangoM here apple and mango are the arguments passed to the program fruit.exe Pro'ra&* Vinclude Wstdio.hX int mainGint argc+ char Larg"JKH C

Material from Interview Mantra. Subscribe to free updates via email.

int nD printfGM6ollo#ing are the arguments entered in the command lineMHD for Gn F AD n W argcD nNNH C printfGMYn OsM+ arg"JnKHD E printfGMYn *umber of arguments entered areYn OdYnM+ argcHD return AD E Out%ut* 6ollo#ing are the arguments entered in the command line (2Ytestpro)ect.exe apple mango *umber of arguments entered are ; 24 5$at are $ea6er 7i-es8 Are 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.VincludeWsome.hX includes all the declarations present in the header file @some.h@. % header file may contain declarations of sub&routines+ functions+ macros and also "ariables #hich #e may #ant to use in our program. Beader files help in reduction of repetiti"e code. S=nta9 o7 in1-u6e 6ire1tive* VincludeWstdio.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 tipHD 3LLLLLLLLLLLLLLLL Index2 restaurant.c LLLLLLLLLLLLLLLL3 VincludeWstdio.hX int bill%llGint food]cost+ int tax+ int tipH C int resultD result F food]cost N tax N tipD printfGMTotal bill is OdYnM+resultHD return resultD E

Material from Interview Mantra. Subscribe to free updates via email.

3LLLLLLLLLLLLLLLL Index2 main.c LLLLLLLLLLLLLLLL3 VincludeWstdio.hX VincludeMrestaurant.hM int mainGH C int food]cost+ tax+ tipD food]cost F 0AD tax F 9AD tip F 0D bill%llGfood]cost+tax+tipHD return AD E 34 5$at are t$e 6i77eren1es ,etween 7or&a- ar'u&ents an6 a1tua- ar'u&ents o7 a 7un1tion8 %rgument2 %n argument is an expression #hich is passed to a function by its caller Gor macro by its 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 copy of the actual arguments. % change in formal arguments #ould not be reflected in the actual arguments. "9a&%-e* Vinclude Wstdio.hX "oid sumGint i+ int )+ int kHD 3L calling function L3 int mainGH C int a F 0D 33 actual arguments sumG;+ / L a+ aHD return AD E 3L called function L3 3L formal argumentsL3 "oid sumGint i+ int )+ int kH C int sD s F i N ) N kD printfGMsum is OdM+ sHD E

Bere ;+/La+a are actual arguments and i+)+k are formal arguments. 54 5$at is %ass ,= va-ue in 7un1tions8 Pass by 4alue2 In this method+ the "alue of each of the actual arguments in the calling function is copied into

Material from Interview 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 Wstdio.hX "oid s#apGint x+ int yH C int tD t F xD x F yD y F tD E int mainGH C int m F 9A+ n F /AD printfGM.efore executing s#ap mFOd nFOdYnM+ m+ nHD s#apGm+ nHD printfGM%fter executing s#ap mFOd nFOdYnM+ m+ nHD return AD Out%ut* .efore executing s#ap mF9A nF/A %fter executing 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 5$at is %ass ,= re7eren1e in 7un1tions8 Pass ,= 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 Wstdio.hX 3L function definition L3 "oid s#apGint Lx+ int LyH C int tD t F LxD 3L assign the "alue at address x to t L3 Lx F LyD 3L put the "alue at y into x L3 Ly F tD 3L put the "alue at to y L3 E int mainGH C int m F 9A+ n F /AD printfGM.efore executing s#ap mFOd nFOdYnM+ m+ nHD s#apG5m+ 5nHD printfGM%fter executing s#ap mFOd nFOdYnM+ m+ nHD return AD E

Material from Interview Mantra. Subscribe to free updates via email.

Out%ut* .efore executing s#ap mF9A nF/A %fter executing 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 5$at are t$e 6i77eren1es ,etween 'et1$arFG an6 s1an7FG 7un1tions 7or rea6in' strin's8 Differences bet#een getchar and scanf functions for reading strings2 s1an7 9. Entering of each character should be follo#ed by return key. /. (ontinuous stream of characters cannot be directly supplied using scanf function. ;. canf function can be used to pro"ide data at execution time irrespecti"e of its typeGint+ char+ floatH. Example2 VincludeWstdio.hX int mainGH C char aJ9AKD printfGMEnter a2 YnMHD scanfGMOsM+aHD return AD E >. scanfGH returns the number of items read 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. 'et1$ar

9. *eed not type return key. /. (ontinuous stream of characters can be directly supplied using getchar function ;. getcharGH function is used only #ith character type. Example2 VincludeWstdio.hX int mainGH C char aD printfGMEnter any character2 YnMHD a F getcharGHD printfGM(haracter entered2Oc YnM+aHD return AD E

>. 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 7un1tions 7'etsFG an6 'etsFG0 w$i1$ one is 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. Subscribe to free updates via email.

"9a&%-e* fgetsGs+/A+fpHD 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. Thus fgetsG H is preferable to getsG H.

!. 5$at is t$e 6i77eren1e ,etween t$e 7un1tions str6u%FG an6 str1%=FG8


str1%= 7un1tion* copies a source string to a destination defined by user. In strcpy 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 Mstring copyM. S=nta9* strcpyGchar Ldestination+ const char LsourceHD 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&* VincludeWstdio.hX VincludeWstring.hX int mainGH C char mynameJ9AKD 33copy contents to myname strcpyGmyname+ Minter"ie#mantra.netMHD 33print the string putsGmynameHD return AD E 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 siIe 9A characters only. In the abo"e program+ string MnodaloM is copied in myname and is printed on output screen. str6u% 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 Mstring duplicateM S=nta9* strdup Gconst char LsHD strdup returns a pointer to a character or base address of an array. 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 pointer. .oth strcpy and strdup functions are present in header file Wstring.hX Pro'ra&* Pro'ra& to i--ustrate str6u%FG4 VincludeWstdio.hX VincludeWstring.hX VincludeWstdlib.hX int mainGH C char mynameJK F Minter"ie#mantra.netMD

Material from Interview Mantra. Subscribe to free updates via email.

33name is pointer "ariable #hich can store the address of memory location of string charL nameD 33contents of myname are copied in a memory address and are assigned to name name F strdupGmynameHD 33prints the contents of @name@ putsGnameHD 33prints the contents of @myname@ putsGmynameHD 33memory allocated to @name@ is no# freed freeGnameHD return AD E Out%ut* inter"ie#mantra.net inter"ie#mantra.net "9%-anation* tring myname consists of Minter"ie#mantra.netM 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 freeGnameHD

CHAPT"R 3* Pointers
)4 5$at is a %ointer in C8 % pointer is a special "ariable in ( language meant )ust to store address of any other "ariable or 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 LapD int a F 0D In the abo"e t#o statements an integer a #as declared and initialiIed to 0. % pointer to an integer #ith name ap #as declared. *ext before ap is used apF5aD This operation #ould initialiIe the declared pointer to int. The pointer ap is no# said to point to a. O%erations on a %ointer*

:ere7eren1in' o%erator @ H @* This operator gi"es the "alue at the address pointed by the pointer . 6or
example after the abo"e ( statements if #e gi"e printfGMOdM+LapHD %ctual "alue of a that is 0 #ould be printed. That is because ap points to a.

A66ition o%erator @ I @* Pointer arithmetic is different from ordinary arithmetic.

Material from Interview Mantra. Subscribe to free updates via email.

apFapN9D %bo"e expression #ould not increment the "alue of ap by one+ but #ould increment it 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 > bytes depending upon the compiler. /4 5$at are t$e a6vanta'es o7 usin' %ointers8 Pointers are special "ariables #hich store address of some other "ariables. S=nta9* datatype LptrD Bere L indicates that ptr is a pointer "ariable #hich represents "alue stored at a particular address. "9a&%-e* int LpD @p@ is a pointer "ariable pointing to address location #here an integer type is stored. A6vanta'es* 1. Pointers allo# us to pass "alues to functions using call by reference. This is useful #hen large siIed arrays are passed as arguments to functions. % function can return more than one "alue by using call by reference. /. Dynamic allocation of memory is possible #ith the help of pointers. ;. We can resiIe data structures. 6or instance+ if an array@s memory is fixed+ it cannot be resiIed. .ut in case of an array #hose memory is created out of malloc can be resiIed. >. Pointers point to physical memory and allo# 'uicker access to data. 24 5$at are t$e 6i77eren1es ,etween &a--o1FG an6 1a--o1FG8 %llocation of memory at the time of execution is called dynamic memory allocation. It is done using the standard library functions mallocGH and callocGH. It is defined in Mstdlib.hM. &a--o1FG* used to allocate re'uired number of bytes in memory at runtime. It takes one argument+ "iI. siIe in bytes to be allocated. S=nta9* "oid L mallocGsiIe]t siIeHD "9a&%-e* a F GintLH mallocG>HD > is the siIe Gin bytesH of memory to be allocated. 1a--o1FG* used to allocate re'uired number of bytes in memory at runtime. It needs two arguments "iI.+ 9. total number of data and /. siIe of each data. S=nta9* "oid L callocGsiIe]t nmemb+ siIe]t siIeHD "9a&%-e* a F GintLH callocG?+ siIeofGintHHD Bere siIeof indicates the siIe of the data type and ? indicates that #e #ant to reser"e space for storing ? integers. :i77eren1es ,etween &a--o1FG an6 1a--o1FG are*

Material from Interview Mantra. Subscribe to free updates via email.

9. *umber of arguments differ. /. .y default+ memory allocated by mallocGH contains garbage "alues. Whereas memory allocated by callocGH contains all Ieros. 34 How to use rea--o1FG to 6=na&i1a--= in1rease siJe o7 an a-rea6= a--o1ate6 arra=8 rea--o1FG* This function is used to increase or decrease the siIe of any dynamic memory #hich is allocated using mallocGH or callocGH functions. S=nta9* "oid LreallocG"oid Lptr+ siIe]t ne#siIeHD The first argument @ptr@ is a pointer to the memory pre"iously allocated by the malloc or calloc functions. The second argument @ne#siIe@ is the siIe in bytes+ of a ne# memory region to be allocated by realloc. This "alue can be larger or smaller than the pre"iously allocated memory. The realloc function ad)usts the old memory region if ne#siIe is smaller than the siIe of old memory. If the ne#siIe is larger than the existing memory siIe+ it increases the siIe 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 siIe may change during execution. Example2 a program that reads input from standard input may not kno# the siIe 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 5$at is t$e eAuiva-ent %ointer e9%ression 7or re7errin' an e-e&ent aKiLKMLKkLK-L0 in a 7our 6i&ensiona- arra=8 (onsider a multidimensional array aJ#KJxKJyKJIK. In this array+ aJiK gi"es address of aJiKJAKJAKJAK and aJiKN) gi"es the address of aJiKJ)KJAKJAK imilarly+ aJiKJ)K gi"es address of aJiKJ)KJAKJAK and aJiKJ)KNk gi"es the address of aJiKJ)KJkKJAK aJiKJ)KJkK gi"es address of aJiKJ)KJkKJAK and aJiKJ)KJkKNl gi"es address of 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 VincludeWstdio.hX VincludeWstring.hX int mainGH C int aJ;KJ;KJ;KJ;KD 33it gi"es address of aJAKJAKJAKJAK . printfGM Yn address of array a is OuM+ aHD printfGMYn address of aJ/KJAKJAKJAK is Ou +gi"en by aJ/K+ Ou gi"en by aN/M+ aJ/K+ a N /HD printfGMYn address of aJ/KJ/KJAKJAK is Ou +gi"en by aJ/KJ/K+ Ou gi"en by aJ/KN/M+ aJ/KJ/K+ aJ/K N /HD printfGMYn address of aJ/KJ/KJ9KJAK is Ou +gi"en by aJ/KJ/KJ9K + Ou gi"en by aJ/KJ/KN9M+ aJ/KJ/KJ9K+ aJ/KJ/K N 9HD return AD E Out%ut* address of array a is 70;>A

Material from Interview 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><A+ gi"en by aJ/KJ/KJ9K + 70><A gi"en by aJ/KJ/KN9 "9%-anation* This output may differ from computer to computer as the address locations are not same for every computer. ;4 :e1-are an arra= o7 t$ree 7un1tion %ointers w$ere ea1$ 7un1tion re1eives two inte'ers an6 returns 7-oat4 :e1-aration* float GLfnJ;KHGint+ intHD Pro'ra&* Illustrates the usage of abo"e declaration VincludeWstdio.hX float GLfnJ;KHGint+ intHD float addGint+ intHD int mainGH C int x+ y+ I+ )D for G) F AD ) W ;D )NNHC fnJ)K F 5addD E x F fnJAKG9A+ /AHD y F fnJ9KG9AA+ /AAHD I F fnJ/KG9AAA+ /AAAHD printfGMsum9 is2 Od YnM+ xHD printfGMsum/ is2 Od YnM+ yHD printfGMsum; is2 Od YnM+ IHD return AD E float addGint x+ int yH C float f F x N yD return fD E Out%ut* sum9 is2 ;A sum/ is2 ;AA sum; is2 ;AAA "9%-anation* Bere @fnJ;K@ is an array of function pointers. Each element of the array can store the address of function @float addGint+ intH@. fnJAKFfnJ9KFfnJ/KF5add Where"er this address is encountered addGint+ intH function is called. <4 "9%-ain t$e varia,-e assi'n&ent in t$e 6e1-aration int HFH%K)0LGF1$ar H0 1$ar HGC It is an array of function pointers that returns an integer pointer. Each function has t#o arguments #hich in turn are pointers to character type "ariable. pJAK+ pJ9K+.....+ pJ<K are function pointers.

Material from Interview 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 VincludeWstdio.hX VincludeWstdlib.hX int LGLpJ9AKHGchar L+ char LHD 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 LHD 33function #hich returns pointer to integer #hose "alue is sum of ascii "alue of characters passed by pointers int LsumGchar L+ char LHD int retrnD int mainG"oidH C int iD for Gi F AD i W 0D iNNH C 33pJAK to pJ>K are pointers to a"erage function. pJiK F 5Ga"erageHD E for Gi F 0D i W 9AD iNNH C 33pJ0K to pJ<K are pointers to sum function pJiK F 5GsumHD E char strJ9AK F Mnodalo.comMD int LintstrJ9AKD for Gi F AD i W <D iNNH C 33upto pJ>K a"erage function is called+ from pJ0K sum is called. intstrJiK F pJiKG5strJiK+ 5strJi N 9KHD if Gi W 0H C 33prints the a"erage of ascii of both characters printfGM Yn a"erage of Oc and Oc is OdM+ strJiK+ strJi N 9K+LintstrJiKHD E else C 33prints the sum of ascii of both characters. printfGM Yn sum of Oc and Oc is OdM+ strJiK+ strJi N 9K+ LintstrJiKHD E E return AD E 33function a"erage is defined here int La"erageGchar Larg9+ char Larg/H C retrn F GLarg9 N Larg/H 3 /D return G5retrnHD E 33function sum is defined here int LsumGchar Larg9+ char Larg/H C retrn F GLarg9 N Larg/HD return G5retrnHD E

Material from Interview 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 5$at is t$e va-ue o7 siJeo7FaG NsiJeo7F1$ar HG in a 1o6e sni%%et* 1$ar HaK3LEBOsri6$arO0Ora'$avaO0Os$as$iO0Osrikant$ODC "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 LD is a pointer "ariable #hich stores the address of a char "ariable. o siIeofGchar LH is > bits. Therefore siIeofGaH 3siIeofGchar LH F 973> F > bytes. ?4 FiG 5$at are t$e 6i77eren1es ,etween t$e C state&ents ,e-ow* 1$ar Hstr E OHe--oOC 1$ar arrKL E OHe--oOC FiiG 5$et$er 7o--owin' state&ents 'et 1o&%-ie6 or not8 "9%-ain ea1$ state&ent4 arrIIC HFarr I )G E @s@C %rint7FOPsO0arrGC GiH char LstrFMBelloMD MBelloM is an anonymous string present in the memory. @str@ is a pointer "ariable that holds the address of this string. char arrJKFMBelloMD 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. 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@D @arr@ is the name of a character array that holds string MBelloM. 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 array @arr@+ thereby string changes from MBelloM to MBslloM. printfGMOsM+arr HD This statement prints the string stored in character array @arr@.

CHAPT"R 5* Pro'ra&s
)4 5rite a %ro'ra& to 7in6 7a1toria- o7 t$e 'iven nu&,er4 Re1ursion* % 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 Wstdio.hX int factGint nHD int mainGH C int x+ iD printfGMEnter a "alue for x2 YnMHD scanfGMOdM+ 5xHD i F factGxHD printfGMYn6actorial of Od is OdM+ x+ iHD return AD E int factGint nH C 3L nFA indicates a terminating condition L3 if Gn WF AH C return G9HD E else C 3L function calling itself L3 return Gn L factGn & 9HHD 3LnLfactGn&9H is a recursi"e expression L3 E E Out%ut* Enter a "alue for x2 >

Material from Interview 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 WF A hereDH is a must for a recursi"e program. 8ther#ise the program enters into an infinite loop. /4 5rite a %ro'ra& to 1$e1k w$et$er t$e 'iven nu&,er is even or o664 Pro'ra&* Vinclude Wstdio.hX int mainGH C int aD printfGMEnter a2 YnMHD scanfGMOdM+ 5aHD 3L logic L3 if Ga O / FF AH C printfGMThe gi"en number is E4E*YnMHD E else C printfGMThe gi"en number is 8DDYnMHD E return AD E Out%ut* Enter a2 / The gi"en number is E4E* "9%-anation wit$ e9a&%-es* "9a&%-e )* 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 e"en 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. 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 e"en 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 condition fails and else part is executed L3 Thus : is an odd number. 24 5rite a %ro'ra& to swa% two nu&,ers usin' a te&%orar= varia,-e4 #apping interchanges the "alues of t#o gi"en "ariables. #o'i1* step92 tempFxD step/2 xFyD step;2 yFtempD "9a&%-e* if xF0 and yF?+ consider a temporary "ariable temp. step92 tempFxF0D step/2 xFyF?D step;2 yFtempF0D Thus the "alues of the "ariables x and y are interchanged. Pro'ra&* Vinclude Wstdio.hX int mainGH C int a+ b+ tempD printfGMEnter the "alue of a and b2 YnMHD scanfGMOd OdM+ 5a+ 5bHD printfGM.efore s#apping aFOd+ bFOd YnM+ a+ bHD 3L #apping logic L3 temp F aD a F bD b F tempD printfGM%fter s#apping aFOd+ bFOdM+ a+ bHD return AD E Out%ut* Enter the "alues of a and b2 / ; .efore s#apping aF/+ bF; %fter s#apping aF;+ bF/ 34 5rite a %ro'ra& to swa% two nu&,ers wit$out usin' a te&%orar= varia,-e4 #apping interchanges the "alues of t#o gi"en "ariables. #o'i1* step92 xFxNyD step/2 yFx&yD step;2 xFx&yD "9a&%-e* if xF: and yF> step92 xF:N>F99D

Material from Interview Mantra. Subscribe to free updates via email.

step/2 yF99&>F:D step;2 xF99&:F>D Thus the "alues of the "ariables x and y are interchanged. Pro'ra&* Vinclude Wstdio.hX int mainGH C int a+ bD printfGMEnter "alues of a and b2 YnMHD scanfGMOd OdM+ 5a+ 5bHD printfGM.efore s#apping aFOd+ bFOdYnM+ a+bHD 3L #apping logic L3 a F a N bD b F a & bD a F a & bD printfGM%fter s#apping aFOd bFOdYnM+ a+ bHD return AD E Out%ut* Enter "alues of a and b2 / ; .efore s#apping aF/+ bF; The "alues after s#apping are aF; bF/

54 5rite a %ro'ra& to swa% two nu&,ers usin' ,itwise o%erators4 Pro'ra&* Vinclude Wstdio.hX int mainGH C int i F 70D int k F 9/AD printfGMYn "alue of iFOd kFOd before s#appingM+ i+ kHD i F i ^ kD k F i ^ kD i F i ^ kD printfGMYn "alue of iFOd kFOd after s#appingM+ i+ kHD return AD E

"9%-anation* i F 70D binary e'ui"alent of 70 is A9AA AAA9 k F 9/AD binary e'ui"alent of 9/A is A999 9AAA i F i^kD i...A9AA AAA9 k...A999 9AAA &&&&&&&&& "al of i F AA99 9AA9 &&&&&&&&& k F i^k i...AA99 9AA9

Material from Interview Mantra. Subscribe to free updates via email.

k...A999 9AAA &&&&&&&&& "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 9AAA binary e'ui"alent of this is 9/A &&&&&&&&& Gthat is the initial "alue of kH ;4 5rite a %ro'ra& to 7in6 t$e 'reatest o7 t$ree nu&,ers4 Pro'ra&* Vinclude Wstdio.hX int mainGHC int a+ b+ cD printfGMEnter a+b+c2 YnMHD scanfGMOd Od OdM+ 5a+ 5b+ 5cHD if Ga X b 55 a X cH C printfGMa is [reater than b and cMHD E else if Gb X a 55 b X cH C printfGMb is [reater than a and cMHD E else if Gc X a 55 c X bH C printfGMc is [reater than a and bMHD E else C printfGMall are e'ual or any t#o "alues are e'ualMHD E return AD E 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. 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 5rite a %ro'ra& to 7in6 t$e 'reatest a&on' ten nu&,ers4 Pro'ra&* Vinclude Wstdio.hX int mainGH C int aJ9AKD int iD int greatestD printfGMEnter ten "alues2MHD 33 tore 9A numbers in an array for Gi F AD i W 9AD iNNH C scanfGMOdM+ 5aJiKHD E 33%ssume that aJAK is greatest greatest F aJAKD for Gi F AD i W 9AD iNNH C if GaJiK X greatestH C greatest F aJiKD E E printfGMYn[reatest of ten numbers is OdM+ greatestHD return AD E

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 siIe 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@D. forGiFAD iW9AD iNNH C ifGaJiKXgreatestH C greatestF aJiKD E E 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 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. Subscribe to free updates via email.

>4 5rite a %ro'ra& to 1$e1k w$et$er t$e 'iven nu&,er is a %ri&e4 % prime number is a natural number that has only one and itself as factors. Examples2 /+ ;+ 9; are prime numbers. Pro'ra&* Vinclude Wstdio.hX mainGH C int n+ i+ c F AD printfGMEnter any number n2 YnMHD scanfGMOdM+ 5nHD 3LlogicL3 for Gi F 9D i WF nD iNNH C if Gn O i FF AH C cNND E E if Gc FF /H C printfGMn is a Prime numberMHD E else C printfGMn is not a Prime numberMHD E return AD E

Out%ut* Enter any number n2 : n is Prime "9%-anation wit$ e9a&%-es* consider a number nF0 forGiFADiWFnDiNNH 3L for loop is executed until the n "alue e'uals i L3 i.e. forGiFADiWF0DiNNH 3L here the for loop is executed until i is e'ual to n L3 9st iteration2 iF9DiWF0DiNN 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# cF9D /nd iteration2 iF/DiWF0DiNN 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/TFA and so c is not incremented+ c remains 9 cF9D ;rd iteration2 iF;DiWF0DiNN 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;TFA and so c is not incremented+ c remains 9 cF9D

Material from Interview Mantra. Subscribe to free updates via email.

>th iteration2 iF>DiWF0DiNN 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>TFA and so c is not incremented+ c remains 9 cF9D 0th iteration2 iF0DiWF0DiNN 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 iF7DiWF0DiNN here i "alue is 7 and 7WF0 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 5rite a %ro'ra& to 1$e1k w$et$er t$e 'iven nu&,er is a %a-in6ro&i1 nu&,er4 If a number+ #hich #hen read in both for#ard and back#ard #ay is same+ then such a number is called a palindrome number. Pro'ra&* Vinclude Wstdio.hX int mainGH C int n+ n9+ re" F A+ remD printfGMEnter any number2 YnMHD scanfGMOdM+ 5nHD n9 F nD 3L logic L3 #hile Gn X AHC rem F n O 9AD re" F re" L 9A N remD n F n 3 9AD E if Gn9 FF re"HC printfGM[i"en number is a palindromic numberMHD E elseC printfGM[i"en number is not a palindromic numberMHD E return AD E 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+ remainderD numberF9/9 no# the #hile loop is executed 3L the condition GnXAH is satisfied L3

Material from Interview Mantra. Subscribe to free updates via email.

3L calculate remainder L3 remainder of 9/9 di"ided by 9AFG9/9O9AHF9D no# re"erseFGre"erseL9AHNremainder FGAL9AHN9 3L #e ha"e initialiIed 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/D re"erseFG9L9AHN/F9/D numberF9/39AF9D no# the number is 9+ greater than A. The abo"e process is repeated for numberF9. remainderF9O9AF9D re"erseFG9/L9AHN9F9/9D 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. )045rite a %ro'ra& to 1$e1k w$et$er t$e 'iven strin' is a %a-in6ro&e4 Palindrome is a string+ #hich #hen read in both for#ard and back#ard #ay is same. "9a&%-e* radar+ madam+ pop+ lol+ rubber+ etc.+ Pro'ra&* Vinclude Wstdio.hX Vinclude Wstring.hX int mainGH C char string9J/AKD int i+ lengthD int flag F AD printfGMEnter a string2 YnMHD scanfGMOsM+ string9HD length F strlenGstring9HD forGiFADi W length DiNNHC ifGstring9JiK TF string9Jlength&i&9KHC flag F 9D breakD E E if GflagH C printfGMOs is not a palindromeYnM+ string9HD E else C printfGMOs is a palindromeYnM+ string9HD E return AD

Material from Interview Mantra. Subscribe to free updates via email.

E Out%ut* Enter a string2 radar MradarM 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 MradarM+ &&&&&&&&&&&&&&&&&&&&&&&&&&& 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. 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. ))45rite a %ro'ra& to 'enerate t$e Fi,ona11i series4 Fi,ona11i series* %ny number in the series is obtained by adding the pre"ious t#o numbers of the series. 1et fGnH be n@th term. fGAHFAD fG9HF9D fGnHFfGn&9HNfGn&/HD 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 SeriesF)0 ter&sG VincludeWstdio.hX int mainGH C 33array fib stores numbers of fibonacci series int i+ fibJ/0KD 33initialiIed first element to A fibJAK F AD

Material from Interview Mantra. Subscribe to free updates via email.

33initialiIed second element to 9 fibJ9K F 9D 33loop to generate ten elements for Gi F /D i W 9AD iNNH C 33i@th element of series is e'ual to the sum of i&9@th element and i&/@th element. fibJiK F fibJi & 9K N fibJi & /KD E printfGMThe fibonacci series is as follo#s YnMHD 33print all numbers in the series for Gi F AD i W 9AD iNNH C printfGMOd YnM+ fibJiKHD E return AD E Out%ut* The fibonacci series is as follo#s A 9 9 / ; 0 ? 9; /9 ;> "9%-anation* The first t#o elements are initialiIed 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. )/45rite a %ro'ra& to %rint OHe--o 5or-6O wit$out usin' se&i1o-on an=w$ere in t$e 1o6e4 [enerally #hen #e use printfGMMH 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-onFCG Vinclude Wstdio.hX int mainGH C 33printf returns the length of string being printed if GprintfGMBello WorldYnMHH 33prints Bello World and returns 99 C 33do nothing E return AD E Out%ut* Bello World "9%-anation* The if statement checks for condition #hether the return "alue of printfGMBello WorldMH is greater than A. printf

Material from Interview Mantra. Subscribe to free updates via email.

function returns the length of the string printed. Bence the statement if GprintfGMBello WorldMHH prints the string MBello WorldM. )245rite 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 printfGMMH statement #e ha"e to use semicolon at the end. If #e #ant to print a semicolon+ #e use the statement2 printfGMDMHD 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 @ D @ #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 Wstdio.hX int mainG"oidH C 33prints the character #ith ascii "alue 0<+ i.e.+ semicolon if GprintfGMOcYnM+ 0<HH C 33prints semicolon E return AD E Out%ut* D "9%-anation* If statement checks #hether return "alue of printf function is greater than Iero or not. The return "alue of function call printfGMOcM+0<H is 9. %s printf returns the length of the string printed. printfGMOcM+0<H prints ascii "alue that corresponds to 0<+ that is semicolonGDH. )345rite a %ro'ra& to 1o&%are two strin's wit$out usin' str1&%FG 7un1tion4 strcmpGH function compares t#o strings lexicographically. strcmp is declared in stdio.h Case )* #hen the strings are e'ual+ it returns Iero. Case /* #hen the strings are une'ual+ it returns the difference bet#een ascii "alues of the characters that differ. aH When string9 is greater than string/+ it returns positi"e "alue. bH When string9 is lesser than string/+ it returns negati"e "alue. S=nta9* int strcmp Gconst char Ls9+ const char Ls/HD Pro'ra&* to 1o&%are two strin's4 VincludeWstdio.hX VincludeWstring.hX int cmpstrGchar s9J9AK+ char s/J9AKHD int mainGH C char arr9J9AK F M*odaloMD char arr/J9AK F MnodaloMD printfGM OdM+ cmpstrGarr9+ arr/HHD 33cmpstrGH is e'ui"alent of strcmpGH return AD E 33s9+ s/ are strings to be compared int cmpstrGchar s9J9AK+ char s/J9AKH C 33strlen function returns the length of argument string passed int i F strlenGs9HD

Material from Interview Mantra. Subscribe to free updates via email.

int k F strlenGs/HD int biggerD if Gi W kH C bigger F kD E else if Gi X kH C bigger F iD E else C bigger F iD E 33loops @bigger@ times for Gi F AD i W biggerD iNNH C 33if ascii "alues of characters s9JiK+ s/JiK are e'ual do nothing if Gs9JiK FF s/JiKH C E 33else return the ascii difference else C return Gs9JiK & s/JiKHD E E 33return A #hen both strings are same 33This statement is executed only #hen both strings are e'ual return GAHD E 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. )545rite a %ro'ra& to 1on1atenate two strin's wit$out usin' str1atFG 7un1tion4 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 VincludeWstdio.hX VincludeWstring.hX char LstrctGchar Lc9+ char Lc/HD char LstrctGchar Lc9+ char Lc/H C 33strlen function returns length of argument string int i F strlenGc9HD int k F AD 33loops until null is encountered and appends string c/ to c9 #hile Gc/JkK TF @YA@H C c9Ji N kK F c/JkKD kNND

Material from Interview Mantra. Subscribe to free updates via email.

E return c9D E int mainGH C char string9J90K F MfirstMD char string/J90K F MsecondMD char LfinalstrD printfGM.efore concatenation2M M Yn string9 F Os Yn string/ F OsM+ string9+ string/HD 33addresses of string9+ string/ are passed to strctGH finalstr F strctGstring9+ string/HD printfGMYn%fter concatenation2MHD 33prints the contents of string #hose address is in finalstr printfGMYn finalstr F OsM+ finalstrHD 33prints the contents of string9 printfGMYn string9 F OsM+ string9HD 33prints the contents of string/ printfGMYn string/ F OsM+ string/HD return AD E 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. );45rite 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 Wstdio.hX int mainGH C 6I1E Lfp9+ Lfp/D 33consider >A character string to store filename char filenameJ>AKD char cD int del]line+ temp F 9D 33asks user for file name printfGMEnter file name2 MHD

Material from Interview Mantra. Subscribe to free updates via email.

33recei"es file name from user and stores in @filename@ scanfGMOsM+ filenameHD 33open file in read mode fp9 F fopenGfilename+ MrMHD c F getcGfp9HD 33until the last character of file is obtained #hile Gc TF E86H C printfGMOcM+ cHD 33print current character and read next character c F getcGfp9HD E 33re#ind re#indGfp9HD printfGM Yn Enter line number of the line to be deleted2MHD 33accept number from user. scanfGMOdM+ 5del]lineHD 33open ne# file in #rite mode fp/ F fopenGMcopy.cM+ M#MHD c F getcGfp9HD #hile Gc TF E86H C c F getcGfp9HD if Gc FF @Yn@H tempNND 33except the line to be deleted if Gtemp TF del]lineH C 33copy all lines in file copy.c putcGc+ fp/HD E E 33close both the files. fcloseGfp9HD fcloseGfp/HD 33remo"e original file remo"eGfilenameHD 33rename the file copy.c to original name renameGMcopy.cM+ filenameHD printfGMYn The contents of file after being modified are as follo#s2YnMHD fp9 F fopenGfilename+ MrMHD c F getcGfp9HD #hile Gc TF E86H C printfGMOcM+ cHD c F getcGfp9HD E fcloseGfp9HD return AD E

Out%ut* Enter file name2abc.txt hi. hello

Material from Interview 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 Mcopy.cM. *o# Mcopy.cM is renamed to the original filename. The original file is opened in read mode and the modified contents of the file are displayed on the screen. )<45rite a %ro'ra& to re%-a1e a s%e1i7ie6 -ine in a te9t 7i-e4 Pro'ra&* Pro'ra& to re%-a1e a s%e1i7ie6 -ine in a te9t 7i-e4 Vinclude Wstdio.hX int mainG"oidH C 6I1E Lfp9+ Lfp/D 33@filename@is a >A character string to store filename char filenameJ>AKD char cD int del]line+ temp F 9D 33asks user for file name printfGMEnter file name2 MHD 33recei"es file name from user and stores in @filename@ scanfGMOsM+ filenameHD fp9 F fopenGfilename+ MrMHD 33open file in read mode c F getcGfp9HD 33print the contents of file . #hile Gc TF E86H C printfGMOcM+ cHD c F getcGfp9HD E 33ask user for line number to be deleted. printfGM Yn Enter line number to be deleted and replacedMHD scanfGMOdM+ 5del]lineHD 33take fp9 to start point. re#indGfp9HD 33open copy.c in #rite mode fp/ F fopenGMcopy.cM+ M#MHD c F getcGfp9HD #hile Gc TF E86H C if Gc FF @Yn@H C tempNND E 33till the line to be deleted comes+copy the content from one file to other if Gtemp TF del]lineHC putcGc+ fp/HD

Material from Interview Mantra. Subscribe to free updates via email.

E else 33#hen the line to be deleted comes C #hile GGc F getcGfp9HH TF @Yn@H C E 33read and skip the line ask for ne# text printfGMEnter ne# textMHD 33flush the input stream fflushGstdinHD putcG@Yn@+ fp/HD 33put @Yn@ in ne# file #hile GGc F getcharGHH TF @Yn@H putcGc+ fp/HD 33take the data from user and place it in ne# file fputsGMYnM+ fp/HD tempNND E 33continue this till E86 is encountered c F getcGfp9HD E 33close both files fcloseGfp9HD fcloseGfp/HD 33remo"e original file remo"eGfilenameHD 33rename ne# file #ith old name opens the file in read mode renameGMcopy.cM+ filenameHD fp9 F fopenGfilename+ MrMHD 33reads the character from file c F getcGfp9HD 33until last character of file is encountered #hile Gc TF E86HC printfGMOcM+ cHD 33all characters are printed c F getcGfp9HD E 33close the file pointer fcloseGfp9HD return AD E 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. 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 Mcopy.cM. *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. )>45rite 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 Wstdio.hX int mainGH 3L %sk for a filename and count number of lines in the fileL3 C 33a pointer to a 6I1E structure 6I1E LfpD int no]lines F AD 33consider >A character string to store filename char filenameJ>AK+ sample]chrD 33asks user for file name printfGMEnter file name2 MHD 33recei"es file name from user and stores in a string named @filename@ scanfGMOsM+ filenameHD 33open file in read mode fp F fopenGfilename+ MrMHD 33get character from file and store in sample]chr sample]chr F getcGfpHD #hile Gsample]chr TF 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]linesN9D E 33take next character from file. sample]chr F getcGfpHD E fcloseGfpHD 33close file. printfGMThere are Od lines in Os YnM+ no]lines+ filenameHD return AD E 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 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. 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. )?45rite a C %ro'ra& w$i1$ asks t$e user 7or a nu&,er ,etween ) to ? an6 s$ows t$e nu&,er4 I7 t$e user in%uts a nu&,er out o7 t$e s%e1i7ie6 ran'e0 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 VincludeWstdio.hX int getnumberGHD int mainGH C int input F AD 33call a function to input number from key board input F getnumberGHD 33#hen input is not in the range of 9 to <+print error message #hile GTGGinput WF <H 55 Ginput XF 9HHH C printfGMJERR8RK The number you entered is out of rangeMHD 33input another number input F getnumberGHD E 33this function is repeated until a "alid input is gi"en by user. printfGMYnThe number you entered is OdM+ inputHD return AD E 33this function returns the number gi"en by user int getnumberGH C int numberD 33asks user for a input in gi"en range printfGMYnEnter a number bet#een 9 to < YnMHD scanfGMOdM+ 5numberHD return GnumberHD E Out%ut* Enter a number bet#een 9 to < >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. /045rite a %ro'ra& to 6is%-a= t$e &u-ti%-i1ation ta,-e o7 a 'iven nu&,er4 Pro'ra&* Qu-ti%-i1ation ta,-e o7 a 'iven nu&,er Vinclude Wstdio.hX int mainGH C int num+ i F 9D printfGMYn Enter any *umber2MHD

Material from Interview Mantra. Subscribe to free updates via email.

scanfGMOdM+ 5numHD printfGMMultiplication table of Od2 YnM+ numHD #hile Gi WF 9AH C printfGMYn Od x Od F OdM+ num+ i+ num L iHD iNND E return AD E Out%ut* Enter any *umber20 0x9F0 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 ridhar !ammalamadaka+ Inter"ie# Mantra Re&e&,er to Su,s1ri,e to Interview Qantra via e&ai-4

5rite 7or us
%re you a passionate ( programmer= Would you like to #rite articles for Inter"ie# Mantra and earn money= (ontact us "ia email sria"r,gmail.com 3 Zse our contact 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.

You might also like