Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore C_questions

C_questions

Published by Mukesh Kumar, 2022-05-04 11:27:22

Description: C_questions

Search

Read the Text Version

PART-I TYPICALQUESTIONS&ANSWERS OBJECTIVETYPEQUESTIONS EachQuestioncarries2marks. Choosecorrectorthebestalternativeinthefollowing: Q.1 Whatistheoutputofthefollowingprogram? main() { intx=2,y=5; (B)z1z2 if(x<y)return(x=x+y);elseprintf(“z1”); (D)Noneofthese printf(“z2”); } (A)z2 (C) Compilationerror Ans:D Thereisnocompilationerrorbuttherewillnooutputbecausefunctionis returningavalueandifstatementistrueinthiscase. Q.2 Choosethecorrectone (A)Addressoperatorcannotbeappliedtoregistervariables (B)Addressoperatorcanbeappliedtoregistervariables (C)Useofregisterdeclarationwillincreasetheexecutiontime (D)Noneoftheabove Ans:D Aregisteraccessismuchfasterthanamemoryaccess,keepingthefrequently accessedvariablesintheregisterwillleadtofasterexecutionofprograms. Q.3 Whatisthefollowingprogramdoing? (B)Addingintegersfrom main() (D)Noneofthese {intd=1; do printf(“%d\\n”,d++); while(d<=9);} (A)Adding9integers 1to9 (C)Displayingintegersfrom 1to9 Ans:C dstartingfrom 1isincrementingonebyonetilld=9sotheprintfstatement isprintingnumbersfrom 1to9. Q.4 Whatistheoutputofthefollowingprogram? main() { externintx; x=20; printf(“\\n%d”,x); }

(A)0 (B)20 (C) error (D)garbage value Ans:C Outputofthe given program willbe “Linkererror-undefined symbolx”. Externalvariablesaredeclaredoutsideafunction. Q.5 Ifxisonedimensionalarray,thenpickupthecorrectanswer (A) *(x+i)issameas&x[i] (B)*&x[i]issameasx+i (C)*(x+i)issameasx[i]+1 (D)*(x+i)issameas*x[i] Ans:A num[i]issameas*(num+i) Q.6 Considerthefollowingdeclaration (B)assignsaddressofctoa inta,*b=&a,**c=&b; (D)assigns5toa Thefollowingprogram fragment a=4; **c=5; (A) doesnotchangethevalueofa (C)assignsthevalueofbtoa Ans:D Thegivenstatementsassigns5toa Q.7 Choosethecorrectanswer (A) enum variablecannotbeassignednewvalues (B) enum variablecanbecompared (C) enumerationfeatureincreasethepowerofC (D) Noneoftheabove Ans:C Theenumerated data typesgive an opportunityto inventourown data typeanddefinewhatvaluethevariableofthisdatatypecantake. Q.8 Thecontentoffilewillbelostifitisopenedin (B)w+mode (A) wmode (D)a+mode (C)amode Ans:A Whenthemodeiswriting,thecontentsaredeletedandthefileisopenedasanew file. Q.9 Considerthefollowingcodesegment: inta[10],*p1,*p2; p1=&a[4]; p2=&a[6]; Whichofthefollowingstatementsisincorrectw.r.t.pointers? (A)p1+2 (B)p2–2 (C)p2+p1 (D)p2–p1 Ans:C

Additionoftwopointersisnotallowed. Q.10 Thesecondexpression(j–k)inthefollowingexpressionwillbeevaluated (i+5)&&(j–k) (A)ifexpression(i+5)istrue. (B)ifexpression(i+5)isfalse. (C)irrespectiveofwhether(i+5)istrueorfalse. (D)willnotbeevaluatedinanycase. Ans:A Inacompoundlogicalexpressioncombinedwith&&,thesecondexpressionis evaluatedonlyiffirstisevaluatedintrue. Q.11 Intheforstatement:for(exp1;exp2;exp3){…} whereexp1,exp2andexp3areexpressions.Whatisoptional? (A) Noneoftheexpressionsisoptional. (B) Onlyexp1isoptional. (C) Onlyexp1andexp3areoptional. (D)Alltheexpressionsareoptional. Ans:D Alltheexpressionsareoptional.For(;;)isavalidstatementinC. Q.12 Theoutputofthefollowingcodesegmentwillbe (B)b } charx=‘B’; (D)bc switch(x){ case‘A’:printf(“a”); case‘B’:printf(“b”); case‘C’:printf(“c”); (A)B (C)BC Ans:D Sincethereisnobreakstatement,allthestatementaftercase’B’areexecuted. Q.13 Whatwillbetheoutputofthefollowingcodesegment? main(){ char s[10]; strcpy(s,“abc”); printf(“%d%d”,strlen(s),sizeof(s)); } (A) 310 (B)33 (C)103 (D)1010 Ans:A strlen(s)givethelengthofthestring,thatis3andsizeof(s)givethesizeofarray sthatis10. Q.14 Whichofthefollowingistheoddoneout? (A)j=j+1; (B)j=+1; (C)j++; (D)j+=1; Ans:B

j=+1isoddoneoutasrestallmeansincrementingthevalueofvariableby1. Q.15 Whichofthefollowingistrueforthestatement: NurseryLand.Nursery.Students=10; (A)ThestructureStudentsisnestedwithinthestructureNursery. (B)ThestructureNurseryLandisnestedwithinthestructureNursery. (C)ThestructureNurseryisnestedwithinthestructureNurseryLand. (D)ThestructureNurseryisnestedwithinthestructureStudents. Ans:C ThestructureNurseryisnestedwithinthestructureNurseryLand. Q.16 Whatwillbetheoutputofthefollowingcodesegment,ifany? myfunc(structtestt){ strcpy(t.s,“world”); } main(){ structtest{chars[10];}t; strcpy(t.s,“Hello”); printf(“%s”,t.s); myfunc(t); printf(“%s”,t.s); } (A) HelloHello (B)worldworld (C)Helloworld (D)theprogram will notcompile Ans:D Theprogram willnotcompilebecauseundefinedsymbolsformyfunc()function. Structureshouldbedefinedbeforethemainandthefunctionwhereitiscalled. Q.17 Ifafunctionisdeclaredasvoidfn(int*p),thenwhichofthefollowingstatements isvalidtocallfunctionfn? (A)fn(x)wherexisdefinedasintx; (B)fn(x)wherexisdefinedasint*x; (C)fn(&x)wherexisdefinedasint*x; (D)fn(*x)wherexisdefinedasint*x; Ans:B Functionvoidfn(int*p)needspointertointasargument.Whenxisdefinedasint *x,thenxispointertointegerandnot*x. Q.18 Whatisthefollowingfunctioncomputing?Assumeaandbarepositiveintegers. intfn(inta,intb){ if(b==0) returnb; else return(a*fn(a,b-1)); } (A)Outputwillbe0always (B)Outputwillalwaysbeb (C)Computingab (D)Computinga+b

Ans:A Theoutputisalways be 0 because b isdecremented in recursive function fn eachtimeby1tilltheterminatingconditionb==0whereitwillreturn0. Q.19 WhatistheoutputofthefollowingCprogram? (B)25 #include<stdio.h> (D)90 main() { inta,b=0; staticintc[10]={1,2,3,4,5,6,7,8,9,0}; for(a=0;a<10;++a) if((c[a]%2)==0)b+=c[a]; printf(“%d”,b); } (A)20 (C)45 Ans:A printfstatementwillprintbwhichissum ofthethosevaluesfrom arraycwhichget dividedby2,thatis2+4+6+8=20. Q.20 Ifa,bandcareintegervariableswiththevaluesa=8,b=3andc=-5.Thenwhatis thevalueofthearithmeticexpression: 2*b+3*(a-c) (A)45 (B)6 (C)-16 (D)-1 Ans:A thevalueofthearithmeticexpressionis45as2*3+3*(8—5)=6+3*13=6+39=45 Q.21 Aglobalvariableisavariable (A)declaredinthemain()function. (B)declaredinanyfunctionotherthanthemain()function. (C)declaredoutsidethebodyofeveryfunction. (D)declaredanywhereintheCprogram. Ans:C Aglobalvariableisdeclaredoutsidethebodyofeveryfunction. Q.22 main()isanexampleof (B)userdefined (A)libraryfunction (D)statement function (C)header Ans:A main()isaspecialfunctionusedbyC system totellthecomputerwherethe program starts. Q.23 Whileincrementingapointer,itsvaluegetsincreasedbythelengthofthedata typetowhichitpoints.Thislengthiscalled (A)scalefactor (B)lengthfactor (C)pointerfactor (D)incrementfactor Ans:D

Whileincrementingapointer,itsvaluegetsincreasedbythelengthofthedata typetowhichitpoints. Q.24 Thefirstdigitofadecimalconstantmustbe (B)anonzero (A)azero (D)aninteger number (C)anegativenumber Ans:D Decimalconstantsconsistofasetofdigit,0to9,precededbyanoptional–or+ sign. Q.25 Whatistheoutputofthefollowingstatement: printf(“%-3d”,12345); (B)-123 (A)123 (D)12 (C)12345 Ans:C printfstatementwouldprint12345. Q.26 Asinglecharacterinputfrom thekeyboardcanbeobtainedbyusingthefunction. (A)printf() (B)scanf() (C)putchar() (D)getchar() Ans:D Readingasinglecharactercanbedonebyusingthefunctiongetchar(). Q.27 Thefunctionftell() (A)readsacharacterfrom afile (B)readsanintegerfromafile (C)givesthecurrentpositioninthefile (D)setsthepositiontothebeginningofthefile. Ans:C ftell()takesafilepointerandreturnsanumberoftypelong,thatcorresponds tothecurrentposition. Q.28 Ifthevariablesi,jandkareassignedthevalues5,3and2respectively,thenthe expressioni=j+(k++=6)+7 (A)givesanerrormessage (B)assignsavalue16toi (C)assignsavalue18toi (D)assignsavalue19toi Ans:A Itgivesanerrormessage-Lvaluerequired. Q.29 Ifanintegerneedstwobytesofstorage,thenthemaximum valueofasigned integeris (A)216-1 (B)215-1 (C)216 (D)215 Ans:B Ifweusea16bitwordlength,thesizeoftheintegervalueislimitedtothe range

-215to215-1 (A)astring (B)astringconstant Q.30 Literalmeans (D)analphabet (C)acharacter Ans:B Literalmeansastringconstant. Q.31 If‘y’isofintegertypethentheexpressions (A)mustyieldthesamevalue. (B)mustyielddifferentvalues. (C)mayormaynotyieldthesamevalue. (D)noneoftheabove. Ans:C Theexpressionmayormaynotyieldthesamevalue. Q.32 Inthefollowingcodefragment intx,y=2,z,a; x=(y*=2)+(z=a=y); printf(‘%d’,x); (A)prints8 (B)prints6 (C)prints6or8dependingonthecompiler (D)issyntacticallywrong Ans:A Itwillprint8becausex=(y*=2)+(z=a=y)=4+4=8. Q.33 Apossibleoutputofthefollowingprogram fragmentis for(i=getchar();;i=get.char()) if(i==‘x’)break; (B)mix elseputchar(i); (D)noneofthe (A) mi (C)mixx above Ans:D Noneoftheaboveasitiswrongsyntax. Q.34 Inaforloop,iftheconditionismissing,then, (A)Itisassumedtobepresentandtakentobefalse. (B) Itisassumedtobepresentandtakentobetrue. (C) Itresultsinasyntaxerror. (D)Executionwillbeterminatedabruptly. Ans:B Q.35 Ifstorageclassismissinginthearraydefinition,bydefaultitwillbetakentobe (A)automatic (B)external

(C)static (D)eitherautomaticorexternaldependingontheplaceofoccurrence. Ans:A A variable declaredinside inside a function without storage class specificationis,bydefault,anautomaticvariable. Q.36 Themaximum numberofdimensionsanarraycanhaveinCis (A)3 (B)4 (C)5 (D)compilerdependent Ans:D Callowsarraysofthreeormoredimensions.Theexactlimitisdeterminedbythe compiler. Q.37 puts(argv[0]); (A)printsthenameofthesourcecodefile. (B)printsargv. (C)printsthenumberofcommandlinearguments. (D)printsthenameoftheexecutablecodefile. Ans:D argv[0]representthefilenamewheretheexecutablecodeoftheprogram isstored. Q.38 printf(“%–10s”,“ABDUL”);displays (B)bbbbbABDUL (A)ABDULbbbbb (D)bbbbbbbbbbABDUL (C)ABDULbbbbbbbbbb Ans:A -10swillprintABDULin10spaceABDULfollowedby5blankspace. Q.39 Whichamongstthefollowingexpressionusesbitwiseoperator? (A)a++ (B)!a>5 (C)a|b (D)a!=b Ans:C |isbitwiseOR. Q.40 Theoutputofthefollowingprogram is main() { floaty; y=198.7361; printf(“%7.2f”,y); } (A) 1 9 (C) 1 9 8 . 7 4 (D) 1 9 8 . 7 4 Ans:C Theprintfstatementisgivingformattedoutputtilltwoplacesofdecimal.

Q.41 Whichisnotdynamicmemoryallocationfunction? (B)free (A)malloc (D)calloc (C) alloc Ans:C Threedynamicmemoryallocationfunctionsare:malloc,callocandfree Q.42 Whichheaderfileisusedforscreenhandlingfunction:- (B)STDLIB.H (A) IO.H (D)STDIO.H (C)CONIO.H Ans:D Theheaderfilestdio.hcontainsdefinitionsofconstants,macrosandtypes,along withfunctiondeclarationsforstandardI/Ofunctions. Q.43 Choosethedirectivethatisusedtoremovepreviouslydefineddefinitionofthe macronamethatfollowsit- (A)#remdef (B)#pragma (C)#undef (D)#define Ans:C Thepreprocessordirective#undefOKAYwouldcausethedefinitionofOKAYto beremovedfrom thesystem. Q.44 Theoutputofthefollowingis x=‘a’; printf(“%d”,x); (A)‘a’ (B)a (C)97 (D)Noneof theabove Ans:C Theprintfstatementisprintingasciivalueofa,thatis97. Q.45 Considerthefollowingstatement (B)a=2,p=3 intj,k,p; (D)a=1,p=3 floatq,r,a; a=j/k; p=q/r; Ifq=7.2,r=20,j=3,k=2 Thevalueofaandpis (A)a=1.5,p=3.6 (C)a=1.5,p=4 Ans:C a=3/2=1.5andp=q/r=7.2/2=3.6isroundedoffto4. Q.46 Choosethefunctionthatreturnsremainderofx/y- (A)remainder() (B)mod() (C)modulus() (D)rem()

Ans:C modulus()functionproducesthereminderofanintegerdivision. Q.47 Whatistheoutputoffollowingprogram:- intq,*p,n; q=176; Iftheaddressofqis2801 p=&q; andpis2600 n=*p; printf(“%d”,n); (A)2801 (B)176 (C)2600 (D)Noneofthe above Ans:B nisassignedathevaluewhichispresentattheaddressofqandthatvalueis176. Q.48 Considerthefollowingstatements- x=5; y=x>3?10:20; (B)20 (D)3 Thevalueofyis (A)10 (C)5 Ans:A Sincex=5isgreaterthan3so yisassignedvalue10.Itisequivalentto if- elsestatements. Q.49 Determinewhichofthefollowingisaninvalidcharacterconstant. (A)‘\\a’ (B)‘T’ (C)‘\\0’ (D)‘/n’ Ans:D newlinecharacterconstantis“\\n”not“/n”. Q.50 Whatisthenameofbuilt-infunctionforfindingsquareroots? (A)square(x) (B)sqr(x) (C)sqrt(x) (D)Nobuilt-in function Ans:C sqrt(x)isabuilt-infunctionforfindingsquareroots. Q.51 Whatistheoutputoffollowingstatement? for(i=1;i<4;i++) printf(“%d”,(i%2)?i:2*i); (A)143 (B)123 (C)246 (D)226 Ans:A fori=1,(i%2)istruesothestatementwillprint1;forfori=2,(i%2)isfalsesothe statementwillprint2*i=2*2=4;forfori=3,(i%2)isagaintruesothestatementwill print3;fori=4,thestatementisoutfrom theloop.

Q.52 Whichofthefollowingstatementistrueaboutafunction? (A)Aninvokingfunctionmustpassargumentstotheinvokedfunction. (B) Everyfunctionreturnsavaluetotheinvoker. (C) Afunctionmaycontainmorethanonereturnstatement. (D)Everyfunctionmustbedefinedinitsownseparatefile. Ans:A Aninvokingfunctionmustpassargumentstotheinvokedfunction. Q.53 Whatistheoutputofthefollowingprogram? main() (B)hye { (D)hellohye inti=4,z=12; if(i=5||z>50) printf(“hello”); else printf(“hye”); } (A)hello (C)syntaxerror Ans:A i=5willassign value 5 to iso the if statement (i=5||z>50) is true so “printf”statementwillprinthello. Q.54 Forimplementingrecursivefunctionthedatastructureusedis: (A)Queue (B)Stack (C)LinkedList (D)Tree Ans:B Forimplementingrecursivefunction,stackisusedasadatastructure. Q.55 Thesizeofarrayinta[5]={1,2}is (B)12 (A)4 (D)6 (C)10 Ans:C Thesizeofintarrayis2*5=10bytesasinttakes2bytesofstorage. Q.56 Whichofthefollowingisnotanescapesequence? (B)\\r (A)\\n (D)\\p (C) \\’ Ans:D \\pisnotanescapesequence. Q.57 Theoutputofthefollowingstatementsis (B)end0p charch[6]={‘e’,‘n’,‘d’,‘\\0’,‘p’}; (D)error printf(“%s”,ch); (A)endp (C)end Ans:C

printfstatementwillprintendbecausestringisterminatedat“\\0”andinarrayafter d,wehavenullcharacter. Q.58 Howmanytimesthefollowingcodeprintsthestring“hello”. for(i=1;i<=1000;i++); printf(“hello”); (A)1 (B)1000 (C)Zero (D)Syntax error Ans:A The“for”loopisterminatedbyasemicolonsothenextstatementisexecutethatis printinghello. Q.59 Findtheinvalididentifiersfrom thefollowing:- (i)nA (ii)2nd (iii)ROLLNO (iv)case (A) (i),(ii)and(iv) (B)(i)and(iii) (C)(ii),(iii)and(iv) (D)(ii),(i)and(iii) Ans:C Identifiercannotstartwithadigit;itcannothaveaspaceandcaseisakeyword. Q.60 Thevoidtypeisusedfor (A)Returningthevalue (B)creatinggeneric pointers (D)Avoiderror (C)Creatingfunctions Ans:B Thevoidtypeisusedtocreategenericpointers. Q.61 Thevalidoctalconstantsfromthefollowing (iv)–0467 (B)(iii)and(iv) (i)0245 (ii)0387 (iii)04.32 (D)(i)and(iv) (A)(i)and(ii) (C)(ii)and(iii) Ans:D (i)and(iv)arevalidoctalconstants. Q.62 Thevariablethataredeclaredoutsideallthefunctionsarecalled______. (A)Localvariable (B)Globalvariable (C)Autovariable (D)Noneoftheabove Ans:B Thevariablesthataredeclaredoutsideallfunctionsarecalledglobalvariable. Q.63 Considerthefollowingstatements:- intx=6,y=8,z,w; y=x++; z=++x; Thevalueofx,y,zbycalculatingtheaboveexpressionsare:- (A)y=8,z=8,x=6 (B)y=6,x=8,z=8 (C)y=9,z=7,x=8 (D)y=7,x=8,z=7 Ans:B

yisassignedvalueofxthatis6,thenxinincrementedthatisvalueofx=7,zis assignedvalueofxafterincrementingthatisz=8sovalueofx=8. Q.64 TodeclareanarraySthatholdsa5-characterstring,youwouldwrite (A)charS[5] (B)StringS[5] (C)charS[6] (D)StringS[6] Ans:A Astringisnothingbutachararray. Q.65 Thefunctionusedtoreadacharacterfrom afilethathasbeenopenedinread modeis (A)putc (B)getc (C)getchar (D)putchar Ans:B getcisusedtoreadacharacterfrom afilethathasbeenopenedinreadmode. Q.66 Thefunctionthatallocatesrequestedsizeofbytesandreturnsapointertothe firstbyteoftheallocatedspaceis- (A)realloc (B)malloc (C)calloc (D)noneofthe above Ans:B mallocallocatesrequestedsizeofbytesandreturnsapointertothefirst byteoftheallocatedspace. Q.67 TheconstructeddatatypeofCisknownas (B)String (A)Pointers (D)Array (C)Structure Ans:C StructureisaconstructeddatatypeofC Q.68 Thepostfixformofthefollowinginfixnotationis: (B) (A) (D) (C) Ans:(A) Q.69 Thenumberofnodesinacompletebinarytreeofdepthd(withrootatdepth0)is (A) (B) (C) (D) Ans:(B) Q.70 Theaveragecaseofquicksorthasorder (A) (B)

(C) (D) Ans:(C) Q.71 InordertogettheinformationstoredinaBSTinthedescendingorder, oneshouldtraverseitinwhichofthefollowingorder? (A)left,root,right (B)root,left,right (C)right,root,left (D)right,left,root Ans:(C) Q.72 EveryinternalnodeinaB-treeofminimum degree2canhave (A) 2,3or4children (B)1,2or3children (C)2,4or6children (D)0,2or4children Ans:(B) Q.73 Whichsortingalgorithm isthebestifthelistisalreadyinorder? (A)Quicksort (B)Mergesort (C)Insertionsort (D)Heapsort Ans:(C) Q.74 In_________thedifferencebetweentheheightoftheleftsubtreeandheight ofrightsubtree,foreachnode,isnotmorethanone (A) BST (B)Complete BinaryTree (C)AVL-tree (D)B-tree Ans:(C) Q.75 Thenumberofcomparisonsrequiredtosort5numbersinascendingorderusing bubblesortis (A) 7 (B)6 (C)10 (D)5 Ans:(C) Q.76 Thecomplexityofaddingtwomatricesoforderm*nis (B)mn (A)m +n (C)max(m,n) (D)min(m,n) Ans:(B) Q.77 Thesecondlargestnumberfrom asetofndistinctnumberscanbefoundin (A)O(n) (B)O(2n) (C) (D)O(logn) Ans:(A) Q.78 IftheinorderandpreordertraversalofabinarytreeareD,B,F,E,G,H,A,C

and A,B,D,E,F,G,H,Crespectivelythenthepostordertraversalofthattree is (A)D,F,G,A,B,C,H,E (B)F,H,D,G,E,B,C,A (C)C,G,H,F,E,D,B,A (D)D,F,H,G,E,B,C,A Ans:(D) Q.79 Inabinarytree,thenumberofterminalorleafnodesis10.Thenumberofnodes withtwochildrenis (A)9 (B)11 (C)15 (D)20 Ans:(A) Q.80 WhichamongstthefollowingcannotbeabalancefactorofanynodeofanAVLtree? (A) 1 (B)0 (C)2 (D)–1 Ans:(C) Q.81 Howmanydistinctbinarysearchtreescanbeformedwhichcontainsthe integers1,2,3? (A)6 (B)5 (C)4 (D)3 Ans:(B) Q.82 Thesortwhich insertseachelementsA(K)into properposition in the previouslysortedsubarrayA(1),...,A(K–1) (A) Insertionsort (B)Radixsort (C)Mergesort (D)Bubblesort Ans:(A) Q.83 Directorrandom accessofelementsisnotpossiblein (B)Array (A) Linkedlist (D)Noneofthese (C)String Ans:(A) Q.84 Levelofanynodeofatreeis (A) Heightofitsleftsubtreeminusheightofitsrightsubtree (B) Heightofitsrightsubtreeminusheightofitsleftsubtree (C) Itsdistancefrom theroot (D)Noneofthese Ans:(C) Q.85 Adesirablechoiceforthepartitioningelementinquicksortis (A) Firstelementofthelist (B) Lastelementofthelist (C)Randomlychosenelementofthelist (D) Medianofthelist

Ans:(A) Q.86 lg(n!)=____________ (B)O(lgn) (D)O(nlgn) (A)O(n) (C)O(n2) Ans:(D) n!=n(n-1)(n-2)-----3X2X1 ≥(n/2)n/2 logn!≥n/2logn/2 ≥n/2(logn-log2) ≥n/2(logn-1) ≤nlogn =O(nlogn) Q.87 Theresultofevaluatingthefollowingpostfixexpressionis (B)65 5,7,9,*,+,4,9,3,/,+,- (D)69 (A)50 (C)61 Ans:(C) Q.88 Agraphwithnverticeswilldefinitelyhaveaparalleledgeorselfloopifthetotal numberofedgesare (A)morethann (B)morethann+1 (C)morethan(n+1)/2 (D)morethann(n-1)/2 Ans:(D) Q.89 Outofthefollowing,theslowestsortingprocedureis (B)HeapSort (A)QuickSort (C)ShellSort (D)BubbleSort Ans:(D) Q.90 In________,itispossibletotraverseatreewithoutusingstackseitherimplicitly orexplicitly. (A) Threadedbinarytrees. (B)AVLTree (C)B+tree (D)Heap Ans:(C) Q.91 TheorderofaB-Treewith2,3,4or5childrenineveryinternalnodeis (A) 2 (B)3 (C)4 (D)5 Ans:(C) Q.92 Thenumberofnodesthathavenosuccessorsinacompletebinarytreeof depth4is (A)0 (B)8 (C)16 (D)4 Ans:(B)

Q.93 OnecanmakeanexactreplicaofaBinarySearchTreebytraversingitin (A) Inorder (B)Preorder (C)Postorder (D)Anyorder Ans:(B) Q.94 AcompleteBinaryTreewith15nodescontains________edges (B)30 (A)15 (C)14 (D)16 Ans:(C) Q.95 Theminimum numberofcomparisonsrequiredtofindthelargestnumberfrom 4differentnumbersare (A)4 (B)3 (C)5 (D)6 Ans:(B) Q.96 Aninfixexpressioncanbeconvertedtoapostfixexpressionusinga (A)Stack (B)Queue (C)Dequeue (D)Noneofthese Ans:(A) Q.97 Adatastructureinwhichanelementisaddedandremovedonlyfromoneend,is knownas (A)Queue (B)Stack (C)In-builtstructure (D)Noneoftheabove Ans:(B) Q.98 Acompletebinarytreewiththepropertythatthevalueofeachnodeisatleastas largeas thevaluesofitschildrenisknownas (A)BinarySearchTree. (B)AVLTree. (C)Heap. (D)Threaded BinaryTree. Ans:(C) Q.99 Asortingalgorithm isstableif (A)itstimecomplexityisconstantirrespectiveofthenatureofinput. (B)preservestheoriginalorderofrecordswithequalkeys. (C)itsspacecomplexityisconstantirrespectiveofthenatureofinput. (D)itsortsanyvolumeofdatainaconstanttime. Ans:(B) Q.100 Atreeinwhich,foreverynode,thedifferencebetweentheheightofitsleftsubtree

andrightsubtreeisnotmorethanoneis (B)CompleteBinary (A) AVLTree. (D) Tree. Tree. (C)B–Tree. Ans:(A) Q.101 Thedatastructureneededtoconvertarecursiontoaniterativeprocedureis (A)Queue. (B)Graph. (C)Stack. (D)Tree. Ans:(C) Q.102 Abinary tree stored using linked representation can be converted to its mirrorimagebytraversingitin (A) Inorder. (B)Preorder. (C)Postorder. (D)Anyorder. Ans:(B) Q.103 Theprefixform ofaninfixexpressionA+B-C*Dis (A) +AB-*CD. (B)-+ABC*D. (C)-+AB*CD. (D)-+*ABCD. Ans:(C) Q.104 Thenumberofedgesinasimple,n-vertex,completegraphis (A)n*(n-2). (B)n*(n-1). (C)n*(n-1)/2. (D)n*(n-1)*(n-2) Ans:(C) Q.105 Thelargestandthesecondlargestnumberfrom asetofndistinctnumbers canbefoundin (A) O(n). (B)O(2n). (C)O . (D)O(logn). Ans:(A) Q.106 ToimplementSparsematrixdynamically,thefollowingdatastructureisused (A)Trees (B)Graphs (C)PriorityQueues (D)LinkedList Ans:(D) Q.107Thedepthdn,ofcompletebinarytreeofnnodes,wherenodesarelabeledfrom 1to nwithrootasnode1andlastleafnodeasnodenis (A) (B) (C) (D) Ans:(C) Q.108ThebalancefactorforanAVLtreeiseither

(A)0,1or–1 (D)Alltheabove (B)–2,–1or0 (C)0,1or2 Ans:(A) Q.109ApplicationsofLinkedListare (A)Simulation,eventdrivensystems (B)Postfixandprefixmanipulations (C)Dictionarysystems,polynomialmanipulations (D)Fixedblockstorageallocation,garbagecollection Ans:(D) Q.110 AVLtreeshaveLL,LR,RR,RLrotationstobalancethetreetomaintainthebalance factor(LR:InsertnodeinRightsubtreeofLeftsubtreeofnodeA,etc).Among rotationsthefollowingaresingleanddoublerotations (A) LL,RLandLR,RR (B)LL,RRandLR,RL (C)LR,RRandLL,RL (D)LR,RLandLR,RL Ans:(B) Q.111 Hashingcollisionresolutiontechniquesare (A)Huffmancoding,linearhashing (B)Bucketaddressing,Huffmancoding (C)Chaining,Huffmancoding (D)Chaining,Bucketaddressing Ans:(D) Q.112 Therunningtimeofthefollowingsorting algorithm dependsonwhetherthepartitioningisbalancedorunbalanced (A) Insertionsort (B)Selectionsort (C)Quicksort (D)Mergesort Ans:(C) Q.113 Graphsarerepresentedusing (A) Adjacencytree (B)Adjacencylinkedlist (C)Adjacencygraph (D)Adjacencyqueue Ans:(B) Q.114 TheaveragecasecomplexityofInsertionSortis (B)O(n3) (A) O(2n) (D)O(2n) (C)O(n2) Ans:(C) Q.115 Infiniterecursionleadsto (B)Underflowofregistersusage (A) Overflowofrun-timestack (D)Underflowofrun-timestack (C)OverflowofI/Ocycles Ans:(A) Q.116 Thenumberofunusedpointersinacompletebinarytreeofdepth5is (A)4 (B)8

(C)16 (D)32 Ans:(C) (B)O(logn) Q.117 Therunningtimeforcreatingaheapofsizenis (D)O(n2) (A)O(n) (C)O(nlogn) Ans:(C) Q.118 Whatwouldbereturnedbythefollowingrecursivefunctionafterwecall test(0,3) inttest(inta,intb) { if(a==b)return(1); elseif(a>b)return(0); elsereturn(a+test(a+1,b)); } (A)1 (B)2 (C)3 (D)4 Ans:(D) Q.119 Theextrakeyinsertedattheendofthe arrayiscalleda (B)StopKey (D)Transposition (A) EndKey (C)Sentinel Ans:(C) Q.120 Whichofthefollowingoperationsisperformedmoreefficientlybydoubly linkedlistthanbysinglylinkedlist (A) Deletinganodewhoselocationisgiven. (B) Searchingofanunsortedlistforagivenitem. (C) Insertinganewnodeafternodewhoselocationisgiven. (D) Traversingthelisttoprocesseachnode. Ans:(A) itin Q.121 OnecandeterminewhetheraBinarytreeisaBinarySearchTreebytraversing (A)Preorder (B)Inorder (C)Postorder (D)Anyofthethree orders Ans:(B) Q.122 Thespanningtreeofconnectedgraphwith10 verticescontains (B)11edges (D)9vertices (A)9edges (C)10edges

Ans:(A) Q.123 Asortedfilecontains16items.Usingbinarysearch,themaximum number ofcomparisonstosearchforanitem inthisfileis (A)15 (B)8 (C)1 (D)4 Ans:(D) Q.12 4 Onecandeterminewhetheraninfixexpressionhasbalancedparenthesisor notbyusing (A)Array (B)Queue (C)Stack (D)Tree Ans:(C) Q.125 Theaveragenumberofkeycomparisonsdoneinsuccessfulsequentialsearchina listof lengthnis (C)n/2 (D)(n+1)/2 Ans:(D) Q.12 6 Themaximum numberofnodesinabinarytreeofdepth5is (B)16 (A)31 (C)32 (D)15 Ans:(A) Q.127 nelementsofaQueuearetobereversedusinganotherqueue.Thenumberof“ADD” and“REMOVE”operationsrequiredtodosois (A)2*n (B)4*n (C)n (D)Thetaskcannotbeaccomplished Ans:(D) Q.128 Acompletebinarytreewithnleafnodeshas (B)2n-1nodes (A)n+1nodes (D)n(n-1)/2nodes (C)2n+1nodes Ans:(B) Q.129 Abinarytreecanbeconvertedintoitsmirrorimagebytraversingitin (A) Inorder (B)Preorder (C)Postorder (D)Anyorder Ans:(B) Q.130 Onecanconvertaninfixexpressiontoapostfixexpressionusinga (A)stack (B)Queue (C)Deque (D)noneofthese Ans:(A)

Q.131 Whichofthefollowingtypesofexpressionsdo notrequireprecedencerulesforevaluation? (A)fullyparenthesisedinfixexpression (B)postfixexpression (C)partiallyparenthesisedinfixexpression (D)morethanoneoftheabove Ans:(A) Q.132 Overflowconditioninlinkedlistmayoccurwhenattemptingto_____ (A) Createanodewhenfreespacepoolisempty. (B) Traversethenodeswhenfreespacepoolisempty. (C) Createanodewhenlinkedlistisempty. (D) Noneofthese. Ans:(A) Q.133 Linkedlistsarenotsuitabledatastructuresforwhichoneofthefollowing problems (A)insertionsort (B)binarysearch (C)radixsort (D)polynomial manipulation Ans:(B) Q.134 Thesortingtechniquewherearraytobesortedispartitionedagainandagaininsuch awaythatallelementslessthanorequaltopartitioningelementappearbeforeit andthosewhicharegreaterappearafterit,iscalled (A)mergesort (B)quicksort (C)selectionsort (D)noneofthese Ans:(B) Q.135 Thesearchtechniqueforsearchingasortedfilethatrequiresincreasedamountof spaceis (A)indexedsequentialsearch(B)interpolationsearch (C)sequentialsearch (D)treesearch Ans:(A) Thesearchtechniqueforsearchingasortedfilethatrequiresincreasedamountof spaceis indexedsequentialsearch.Becauseinthissearchtechniqueweneed tomaintainaseparateindexfilewhichrequiresadditionalstoragespace. Q.136Thepostfixform ofA^B*C-D+E/F/(G+H), (A)AB^C*D-EF/GH+/+ (B)AB^CD-EP/GH+/+* (C)ABCDEFGH+//+-*^(D)AB^D+EFGH+//*+ Ans:(A)

Q.137 Theprefixof(A+B)*(C-D)/E*F (A)/+-AB*CD. (B)/*+-ABCD*EF. (C)*/*+AB-CDEF. (D)**AB+CD/EF. Ans:(C) Prefixof(A+B)*(C-D)/E*F (+AB)*(-CD)/E*F *+AB-CDE*F */*+AB-CDEF Q.138 Asortingtechniquewhichusesthebinarytreeconceptsuchthatlabelofanynodeis largerthanallthelabelsinthesubtrees,iscalled (A)selectionsort. (B)insertion sort. (C)Heapsort. (D)quicksort. Ans:(C) ASortingtechniquewhichusesthebinarytreeconceptsuchthatlabelofanynode islargerthanallthe,labelsinthesubtrees,iscalledHeapsortbecauseheapsort worksonacompletebinarytreewiththepropertythatthevalueatanynode'N'of thetreeshouldbegreaterthanorequaltothevalueatallitschildrennodes. Q.139 Afullbinarytreewith'n'non-leafnodescontains (A)log2nnodes. (B)n+1nodes. (C)2nnodes. (D)2n+lnodes. Ans:(D) Q.140 Agraph'G'with'n'nodesisbipartiteifitcontains (A)nedges. (B)acycleofoddlength. (C)nocycleofoddlength. (D)n2edges. Ans:(C) Q.141 Recursive procedures are implemented by using____data tructure. (A)queues. (B)stacks. (C)linkedlists. (D)strings. Ans:(B) RecursiveproceduresareimplementedbyusingstacksbecausestacksareLIFO datastructureand weneed thisfeatureto storereturnaddressesofvarious recursivecallsinrecursiveprocedures. Q.142 In______,thedifferencebetweentheheightoftheleftsubtreeandheightoftheright

tree,foreachnode,isalmostone. (A)Binarysearchtree (B)AVL-tree (C)Completetree (D)Threadedbinary tree Ans:(B)

PART–II DESCRIPTIVES Q.1 WriteaC program to computethesum offirstnterms(n 1)ofthe followingseriesusing‘for’loop. 1–3+5–7+9-…… (6) Ans: ACprogram tocomputethesum offirstntermsoftheseries1-3+5- 7+9-…islistedbelow: main() { intstart=1,i=1,no=0,sum=0; clrscr(); printf(\"\\nEnternumberoftermstobeadded:->\"); scanf(\"%d\",&no); for(i=1;i<=no;i++) { if(i%2!=0) { sum+=start; if(i==1) printf(\"%d\",start); else printf(\"+%d\",start); } else { sum-=start; printf(\"-%d\",start); } start+=2; } printf(\"=%d\",sum); getch(); } Q.2 WriteaCprogram toconvertabinarynumbertoitscorrespondingoctal number. (8) Ans: ACprogram toconvertabinarynumbertoitsbinaryoctalnumberisasfollows: main() { longintbin_no,no; intoct_no,oct_p,i,rem,pow2,pow8,inter_oct; clrscr(); printf(\"\\nEntertheBinarynumber:->\"); scanf(\"%ld\",&bin_no); no=bin_no; pow8=1; oct_no=0; while(no>0) {

i=0; inter_oct=0; pow2=1; while(i<=2) { if(no==0)break; rem=no%10; inter_oct+=rem*pow2; i++; pow2*=2; no/=10; } oct_no+=inter_oct*pow8; pow8*=10; } printf(\"\\nOctalEquivalentfor%ld=%d\",bin_no,oct_no); getch(); } Q.3 WriteaCprogram toprintoutnvaluesofthefollowingsequence. 1–11–11… (6) Ans: ACprogram toprintnvaluesoffollowingsequence1–11–11…islistedbelow: #include<stdio.h> #include<conio.h> main() { inti,j,n,k; clrscr(); printf(\"\\nenternumber\\n\"); scanf(\"%d\",&n); k=1; for(i=1;i<=n;i++) { for(j=1;j<=i;j++) printf(\"%d\",k); printf(\"\\t\"); } getch(); } Q.4 WriteaCprogram totestwhetheragivenpairofnumbersareamicablenumbers. (Amicablenumberarepairsofnumberseachofwhosedivisorsadd to the othernumber) (8) Ans: ACprogram totestwhetheragivenpairofnumbersisamicablenumbersisas follows: #include<stdio.h> #include<conio.h> #include<math.h> voidmain() {

inti,j,n,sum_i=0,sum_j=0; clrscr(); printf(\"enteranytwonumbers>\"); scanf(\"%d%d\",&i,&j); for(n=1;n<i;n++) { if(i%n==0) sum_i+=n; } for(n=1;n<j;n++) { if(j%n==0) sum_j+=n; } if((sum_j==i)&&(sum_i==j)) printf(\"\\nAmicable\"); else printf(\"\\nNotAmicable\"); getch(); } Q.5 WriteaCprogram torearrangetheelementsofanarraysothatthoseoriginally (6) storedatoddsuffixesareplacedbeforethoseatevensuffixes. Ans: ACprogram torearrangetheelementsofanarraysothatthoseoriginallystoredat oddsuffixesareplacedbeforethoseatevensuffixs: main() { chara[25],ch,temp; inti; clrscr(); printf(\"\\nEnterthestring:->\"); gets(a); for(i=0;a[i]!='\\0';i++) { if(a[i+1]=='\\0')break; temp=a[i]; a[i]=a[i+1]; a[i+1]=temp; i++; } puts(a); getch(); } Q.6 Admissiontoacollegeinsciencebranchis givenifthefollowingconditionsaresatisfied (i) Mathsmarks>=80 (ii) Physicsmarks>=75 (iii) Chemistrymarks>=70 (iv) Totalpercentageinallthreesubjects>=80 Giventhemarksinthreesubjects,writeaprogram toprocesstheapplicationstolist theeligiblecandidates. (8)

Ans: A Cprogram to process the applications to listthe eligible candidates is listedbelow: #include<stdio.h> #include<conio.h> voidmain() { floatmath,phy,che; floatper; charch; clrscr(); printf(\"\\nDouwanttoenteranyrecord:->\"); ch=getch(); while(ch=='y'||ch=='Y') { clrscr(); printf(\"\\nEnterMarksinMath:->\"); scanf(\"%f\",&math); printf(\"\\nEnterMarksinPhysics:->\"); scanf(\"%f\",&phy); printf(\"\\nEnterMarksinChemistry:->\"); scanf(\"%f\",&che); per=(math+phy+che)/3.00; if(math>=80.00&&phy>=75.00&&che>=70.00&&per>=80.00) printf(\"\\nYouareeligibleforselection.\"); else printf(\"\\nSorryyouarenoteligible!!\"); printf(\"\\nDouwanttoenternewrecord:->\"); ch=getch(); } printf(\"\\nThanksforusingit!\"); getch(); } Q.7 WriteaCprogram usingwhilelooptoreversethedigitsofagivennumber.(for example,Ifnumberis=12345thenoutputnumberis=54321) (5) Ans: ACprogram toreversethedigitsofagivennumber: #include<stdio.h> #include<conio.h> voidmain() { intn,r; clrscr(); printf(\"enteraninteger\"); scanf(\"%d\",&n); printf(\"\\nreverseof%d:\",n); while(n>0) { r=n%10; printf(\"%d\",r); n=n/10; } getch();

} Q.8 WriteCprogram toproduce10rowsofthefollowingform ofFloyd’striangle (5) 1 1 0 01 1 101 0 Ans: ACprogram toproduce10rowsofFloyd’striangleis: #include<conio.h> voidmain() { inti,j; clrscr(); for(i=1;i<=10;i++) { for(j=1;j<=i;j++) { printf(\"\"); if(i%2==0) if(j%2==0) printf(\"1\"); else printf(\"0\"); else if(j%2==0) printf(\"0\"); else printf(\"1\"); } printf(\"\\n\\n\"); } getch(); } Q.9 Considerthefollowingmacrodefinition #defineroot(a,b)sqrt((a)*(a)+(b)*(b)) Whatwillbetheresultofthefollowingmacrocallstatement root(a++,b++)ifa=3andb=4 (3) Ans: Resultofthismacrois:5 sqrt(3*3+4*4) sqrt(9+16)=sqrt(25)=5 Q.10 Writeanestedmacrothatgivestheminimum ofthreevalues. (3) Ans: Anestedmacrothatgivestheminimum ofthreevariablesislistedbelow: #include<stdio.h> #include<conio.h> #definemin(a,b)((a>b)?b:a) #defineminthree(a,b,c)(min(min(a,b),c)) voidmain() {

intx,y,z,w; clrscr(); printf(\"enterthreenumbers:\\n\"); scanf(\"%d%d%d\",&x,&y,&w); z=minthree(x,y,w); printf(\"Minimum ofthreevalueis%d\",z); getch(); } Q.11 GivenaretwoonedimensionalarraysAandBwhicharestoredinascending order.Writeaprogram tomergethem intoasinglesortedarrayCthatcontains everyelementofAandBinascendingorder. (8) Ans: Aprogram tomergetwoarraysintosinglesortedarraythatcontainseveryelement ofarraysintoaascendingorder: #include<stdio.h> #include<conio.h> voidsort(int*,int); voidmerge(int*,int*,int,int); voidmain() { inta[10],b[10]; inti,j,m,n; clrscr(); printf(\"howmanynumbersuwanttoenterin1starray:\"); scanf(\"%d\",&n); printf(\"enternumbersinascendingorder:\\n\"); for(i=0;i<n;i++) scanf(\"%d\",&a[i]); printf(\"howmanynumbersuwanttoenterin2ndarray:\"); scanf(\"%d\",&m); printf(\"enternumbersinascendingorder:\\n\"); for(i=0;i<m;i++) scanf(\"%d\",&b[i]); merge(a,b,n,m); getch(); } voidmerge(int*a,int*b,intn,intm) { inti=0,c[20],j=0,k=0,count=0; while(i<=n&&j<=m) { if(a[i]<b[j]) { c[k]=a[i]; i++; k++; } if(a[i]>b[j]) { c[k]=b[j]; j++; k++; } if(a[i]==b[j])

{ c[k]=a[i]; k++; i++; j++; count++; } } if(i<=n&&j==m) { while(i<=n) { c[k]=a[i]; i++; k++; } } if(i==n&&j<=m) { while(j<=m) { c[k]=b[j]; i++; j++; } } for(i=0;i<m+n-count;i++) printf(\"%d\\t\",c[i]); } Q.12 WriteaCprogram thatreadsthetextandcountsalloccurrencesofaparticular word. (6) Ans: ACprogram thatreadsthetextandcountalloccurrencesofaparticularword: #include<string.h> voidmain() { chara[100],b[20],c[20]; inti,count=0,k=0,len; clrscr(); printf(\"\\nEnterastring:->\"); gets(a); printf(\"\\nEnterthewordtobesearched:->\"); gets(b); len=strlen(a); for(i=0;i<=len;i++) { //AssumingSpace,TabandNULLaswordseparator if(a[i]==32||a[i]=='\\t'||a[i]=='\\0') { c[k]='\\0'; if(strcmp(b,c)==0)count++; k=0; } else {

c[k]=a[i]; k++; } } printf(\"Occuranceof%sis=%d\",b,count); getch(); } Q.13 WriteaCprogram thatreadsastringfromkeyboardanddetermineswhetherthe stringispalindromeornot.(Astringispalindromeifitisreadfromleftorright givesyouthesamestring) (8) Ans: ACprogram tocheckifinputstringispalindromeornot: #include<stdio.h> #include<conio.h> voidmain() { inti,j,k,flag=1; chara[20]; clrscr(); printf(\"enteranyword:\\n\"); scanf(\"%s\",a); i=0; while(a[i]!='\\0') i++; k=i; for(j=0;j<k/2;) { if(a[j]!=a[i-1]) { flag=0; break; } if(a[j]==a[i-1]) { j++; i--; } } if(flag==0) printf(\"itisanotpalindrome\"); else printf(\"itisapalindrome\"); getch(); } Q.14 WriteaCfunctionstrend(s,t),whichreturns1ifthestringtoccursattheendofthe strings,andzerootherwise. (7) Ans: Cfunctionstrend(s,t),whichreturns1ifthestringtoccursattheendof thestrings,andzerootherwise. #include<conio.h>

#include<string.h> strend() { chars[100],t[20],c[20]; inti,j,k=0,len1,len2; clrscr(); printf(\"\\nEnterthestring:\"); gets(s); printf(\"\\nEnterthestringtobesearchedfor:\"); gets(t); len1=strlen(s); len2=strlen(t); for(i=len1-(len2);i<=len1;i++) { c[k++]=s[i]; } c[k]='\\0'; if(strcmp(t,c)==0) return1; else return0; getch(); } Q.15 Writeafunctionrightrot(x,n)thatreturnsthevalueoftheintegerxrotatedtothe rightbynpositions. (7) Ans: Afunctionrightrot(x,n)thatreturnsthevalueoftheintegerxrotatedtotheright bynpositions. #include<conio.h> rightrot(x,n) { intx,n,k=0,num,rem,i,j,dig; intarr1[10],arr2[10]; clrscr(); printf(\"\\nEntertheintegertoberotated:\"); scanf(\"%d\",&x); printf(\"\\nEnterthepositionsbywhich%distoberotated:\",x); scanf(\"%d\",&n); for(num=x;num!=0;num/=10) { rem=num%10; arr1[k++]=rem; } i=k-1; k=0; for(;i>=0;i--) arr2[k++]=arr1[i]; k-=1; for(i=1;i<=n;i++) { dig=arr2[k]; for(j=k;j>0;j--)

arr2[j]=arr2[j-1]; arr2[0]=dig; } printf(\"\\n\\nTheoriginalnumberis:“); returnx; printf(\"\\nTherotatednumberis:\"); for(i=0;i<=k;i++) printf(\"%d\",arr2[i]); getch(); } thQ.16 WriterecursivefunctioninCtoobtainn term oftheFibonacciseries. (7) Ans: recursivefunctioninCtoobtainnthterm oftheFibonacciseries #include<stdio.h> #include<conio.h> voidmain() { intn; voidfibonac(int); clrscr(); printf(\"enterthelengthfortheseries\"); scanf(\"%d\",&n); printf(\"Fibonaccisequenceupto%dtermsis:\\n\\n\",n); fibonac(n); getch(); } voidfibonac(intn) {staticintf1=0,f2=1; inttemp; if(n<2) {f1=0; f2=1; } else { fibonac(n-1); temp=f2; f2=f1+f2; f1=temp; } printf(\"%5d\",f1); } Q.17 WriteCfunctionnamed‘fiddle’thattakestwoarguments,xandyandchangesboth values.xisanintwhileyisapointertoint (7) Ans: Cfunctionnamed‘fiddle’thattakestwoarguments,xandyandchanges bothvalues.xisanintwhileyisapointertoint #include<conio.h> voidmain() { intx,z,*y,temp;

clrscr(); printf(\"\\nEntertwonumbers:\\n\"); scanf(\"%d%d\",&x,&z); y=&z; printf(\"\\n\\nx=%dandy=%d\",x,*y); fiddle(&x,y); printf(\"\\nAfterchangingtheirvalues\"); printf(\"\\nx=%dandy=%d\",x,*y); getch(); } fiddle(int*a,int*b) { inttemp; temp=*a; *a=*b; *b=temp; getch(); } Q.18 Whatisanunsignedintegerconstant?Whatisthesignificanceofdeclaringa constantasunsigned? (4) Ans: Anintegerconstantisanynumberintherange-32768to+32767,becauseaninteger constantalwaysoccupiestwobytesinmemoryandintwobyteswecannotstorea numberbiggerthan+32767orsmallerthan-32768.Outofthetwobytestostorean integer,thehighestbitisusedtostorethesignoftheinteger.Thisbitis1ifthenumber isnegativeand0ifnumberispositive.Unsignedintegerconstantisanintegerconstant whichhasthepermissiblerangefrom 0to65536.Thussignificanceofdeclaringa constantasunsigned almostdoublesthe sizeofthe largestpossible value.This happensbecauseondeclaringaconstantasunsigned,thesixteenthbitisfreeandis notusedtostorethesignoftheconstant. Q.19 Explainpointersandstructuresbygivinganexampleofpointertostructurevariable?(5) Ans: Wecan have a pointerpointing to a structure justthe same waya pointer pointingtoanint,suchpointersareknownasstructurepointers.Forexample considerthefollowingexample: #include<stdio.h> #include<conio.h> structstudent { charname[20]; introll_no; }; voidmain() { structstudentstu[3],*ptr; clrscr(); printf(\"\\nEnterdata\\n\"); for(ptr=stu;ptr<stu+3;ptr++) {printf(\"Name\"); scanf(\"%s\",ptr->name); printf(\"roll_no\"); scanf(\"%d\",&ptr->roll_no);

} printf(\"\\nStudentData\\n\\n\"); ptr=stu; while(ptr<stu+3) { printf(\"%s%5d\\n\",ptr->name,ptr->roll_no);ptr++; } getch(); } Hereptrisastructurepointernotastructurevariableanddotoperatorrequires astructurevariableonitsleft.Cprovidesarrow operator“->”torefertostructure elements.“ptr=stu”wouldassigntheaddressofthezerothelementofstutoptr.Its memberscanbeaccessedbystatementlike“ptr->name”.Whenthepointerptris incrementedbyone,itismadetopointtothenextrecord,thatisstu[1]andsoon. Q.20 Comparethefollowingpairsofstatementswithrespecttotheirsyntaxandfunction: a. breakandcontinue. b. gotoandbreak. (4) Ans: a. breakandcontinue Twokeywordsthatare veryimportantto looping are breakand continue.The breakcommandwillexitthemostimmediatelysurroundingloopregardlessofwhat theconditionsoftheloopare.Breakisusefulifwewanttoexitaloopunder specialcircumstances. #include<stdio.h> voidmain(){ inta; printf(\"Pickanumberfrom 1to4:\\n\"); scanf(\"%d\",&a); switch(a){ case1: printf(\"Youchosenumber1\\n\"); break; case2: printf(\"Youchosenumber2\\n\"); break; case3: printf(\"Youchosenumber3\\n\"); break; case4: printf(\"Youchosenumber4\\n\"); break; default: printf(\"That'snot1,2,3or4!\\n\"); } getch(); } Continueisanotherkeywordthatcontrolstheflowofloops.Ifweareexecutingaloop andhitacontinuestatement,theloopwillstopitscurrentiteration,updateitself(in thecaseofforloops)andbeginto executeagainfrom thetop.Essentially,the continuestatementissaying\"thisiterationoftheloopisdone;let'scontinuewiththe loopwithoutexecutingwhatevercodecomesafterme.\"

Thesyntaxofcontinuestatementissimple continue; b. gotoandbreak Csupportgotostatementtobranchunconditionallyfrom onepointtoanotherinthe program.Thegotokeywordisfollowedbyalabel,whichisbasicallysomeidentifier placedelsewhereintheprogram wherethecontrolistobetransferred. Duringrunningofaprogram,thestatementlike“gotolabel1;”causetheflow of controlto the statementimmediatelyfollowing the label“label1”.Wecan havea forwardjumporabackwardjump. #include<stdio.h> voidmain() { intattempt,number=46; looping:/*alabel*/ printf(\"Guessanumberfrom0-100\\n\"); scanf(\"%d\",&attempt); if(number==attempt){ printf(\"Youguessedcorrectly!\\n\\n\"); } else{ printf(\"Letmeaskagain...\\n\\n\"); gotolooping;/*Jumptothelabel*/ } getch(); } Q.21 Explainthedifferencebetweenthefollowing: (6) (i) Program testinganddebugging. (ii) Topdownandbottom upapproaches. (iii) Interpretedandcompiledlanguages. Ans: (i) Program testinganddebugging: Programtestingistheprocessofcheckingprogram,toverifythatitsatisfiesits requirementsandtodetecterrors.Theseerrorscanbeofanytype-Syntaxerrors, Run-timeerrors,LogicalerrorsandLatenterrors.Testingincludenecessarysteps todetectallpossibleerrorsintheprogram.Thiscanbedoneeitheratamodule levelknownasunittestingoratprogram levelknownasintegrationtesting. Debuggingisamethodicalprocessoffindingandreducingthenumberofbugsina computerprogrammaking it behave as expected.One simple way to find thelocation ofthe erroris to use printstatementto display the values of thevariables.Once the location ofthe erroris found,the erroris corrected anddebuggingstatementmayberemoved. (ii)TopDownandBottom upapproaches Atop-downapproachisessentiallybreakingdownasystem togaininsightintoits compositionalsub-systems.Inatop-downapproachanoverviewofthesystem is firstformulated,specifying butnotdetailing any first-levelsubsystems.Each subsystem is then refined in greaterdetail,sometimes in many additional subsystem levels,untiltheentirespecificationisreducedtobaseelements.In shortthetopdownapproachmeansdecomposingofthesolutionprocedureinto subtasks.Thisapproachproducesareadableandmodularcodethatcanbeeasily understoodandmaintained. A bottom-upapproach is essentially piecingtogethersystems to give rise to

grandersystems,thusmakingtheoriginalsystemssub-systemsoftheemergent system.Inabottom-upapproachtheindividualbaseelementsofthesystem are firstspecifiedingreatdetail.Theseelementsarethenlinkedtogethertoform largersubsystems,whichtheninturnarelinked,sometimesinmanylevels,untila completetop-levelsystemisformed. (iii)InterpretedandCompiledLanguages Ininterpretedlanguages,theinstructionsareexecutedimmediatelyafterparsing. Bothtasksareperformedbytheinterpreter.Thecodeissavedinthesameformat thatweentered.InterpretedlanguagesincludetheMS-DOSBatchlanguage(the OS itselfistheinterpreter),shellscriptsin Unix/Linuxsystems,Java,Perletc. Advantagesofinterpretedlanguagesincluderelativeeaseofprogrammingandno linkerrequirement.Disadvantagesincludepoorspeedperformanceandthatwedo notgenerateanexecutable(andthereforedistributable)program.Theinterpreter mustbepresentonasystem toruntheprogram. Incompiledlanguagestheinstructionsintomachinecodeandstorethem ina separatefileforlaterexecution.Manymoderncompilerscancompile(parse)and executeinmemory,givingthe'appearance'ofaninterpretedlanguage.However, thekeydifferenceisthatparsing and executionoccursintwo distinctsteps. Examples ofcompiled languages include VisualBasic,C/C++,Delphiand many others.Inacompiledenvironment,wehaveseveralseparatefileslike:sourcecode (thetextinstructions),objectcode(theparsedsourcecode)andtheexecutable (thelinked object code).There is definitely an increase in complexity in usingcompilers,butthe keyadvantages are speed performance and thatone candistributestand-aloneexecutables. Q.22 WriteacompleteCprogram forreadinganemployeesfilecontaining{emp_number, name,salary,address}.Create an outputfile containing the names ofthose employeesalongwiththeirsalaryandaddresswhosesalaryis>20,000. (8) Ans: #include<stdio.h> structemployee { intcode; charname[30]; charaddress[50]; charphone[10]; floatsal; }emp,tmp; FILE*fp1,*fp2; voidmain() { charch='y'; inti=1; //Assumingthatthefilealreadyexists fp1=fopen(\"employee.txt\",\"r\"); if(fp1==NULL) { fp1=fopen(\"employee.txt\",\"w\"); if(fp1==NULL) { printf(\"\\nUnabletocreateEmployee.txtfile\"); getch(); exit();

} printf(\"\\nNoDatafoundinEmployee.txt.Addnew records\"); while(1) { printf(\"\\nEnterEmployeeCode:->\"); flushall(); scanf(\"%d\",&emp.code); printf(\"\\nEnterEmployeeName:->\"); flushall(); gets(emp.name); printf(\"\\nEnterEmployeeAddress:->\"); flushall(); gets(emp.address); printf(\"\\nEnterEmployeePhoneNumber:->\"); flushall(); gets(emp.phone); printf(\"\\nEnterEmployeeSalary:->\"); flushall(); scanf(\"%f\",&emp.sal); //WritingrecordstoEmployee.txtfile fwrite(&emp,sizeof(emp),1,fp1); printf(\"\\nDouwanttoaddmorerecords(y/n):-> \"); flushall(); scanf(\"%c\",&ch); if(ch=='n'||ch=='N')break; } fclose(fp1); fp1=fopen(\"employee.txt\",\"r\"); } printf(\"\\nListofEmployeeshavingSalarygreaterthan 20000\\n\"); printf(\"\\nCode\\tName\\t\\tAddress\\tPhoneNo.\\tSalary\\n\"); i=1; fp2=fopen(\"Output.txt\",\"w\"); getch(); if(fp2==NULL) { printf(\"\\nUnabletocreateOutputfile\\n\"); getch(); exit(); } while(1) { i=fread(&emp,sizeof(emp),1,fp1); if(i==0)break; if(emp.sal>20000) fwrite(&emp,sizeof(emp),1,fp2); } fclose(fp2); fp2=fopen(\"output.txt\",\"r\"); i=1; while(1) { i=fread(&emp,sizeof(emp),1,fp2);

if(i==0)break; printf (\"\\n%d\\t%s\\t\\t%s\\t%s\\t%f\",emp.code,emp.name,emp.address,emp.phone,emp.sal); } getch(); } Q.23 Writeafunctiontodisplaythebinarynumbercorrespondingtotheintegerpassedto itasanargument. (6) Ans: #include<stdio.h> #include<conio.h> voiddis_bin(intn) { num=n; for(i=0;num!=0;i++) { q=num/2; r[i]=num%2; num=q; } clrscr(); printf(\"\\n\\nTheintegerthenumberis:%d\\n\",n); printf(\"\\nThebinaryconversionis:\"); for(i-=1;i>=0;i--) printf(\"%d\",r[i]); getch(); } Q.24 Writeafunction,my_atoi,similartothelibraryfunctionatoithatreturnsthenumeric valuecorrespondingtothestringpassedtoitasanargument. (6) Ans: #include<stdio.h> main() { longintn=0; charstr[25]; clrscr(); printf(\"\\nEnterthestring:->\"); gets(str); my_atoi(str,&n); printf(\"\\nIntegerEquvalentofstring%s=%ld\",str,n); getch(); } my_atoi(charstr[25],longint*num) { inti=1; longints=1,l=0,j; floatpo10=1; //Trimmingthestringforintegers for(i=0;str[i]!='\\0';i++) { if(str[i]=='')

{ for(j=i;str[j]!='\\0';j++) str[j]=str[j+1]; i--; } elseif(str[i]>=48&&str[j]<=57) continue; else { str[i]='\\0'; break; } } l=strlen(str); for(i=l-1;i>=0;i--) { switch(str[i]) { case48:s*=0;break; case49:s*=1;break; case50:s*=2;break; case51:s*=3;break; case52:s*=4;break; case53:s*=5;break; case54:s*=6;break; case55:s*=7;break; case56:s*=8;break; case57:s*=9;break; } *num+=s; po10*=10; s=po10; } } Q.25 Brieflyexplainwhatdoyouunderstandbystepwiserefinementoftheprogram? (4) Ans: StepwiserefinementoftheProgram: Theconceptof“Stepwiserefinement”meanstotakeanobjectandmoveitfrom a generalperspectivetoapreciselevelofdetailandthiscannotbedoneinonejump butinsteps.Thenumberofstepsneededtodecomposeanobjectintosufficient detailisultimatelybasedontheinherentnatureoftheobject.“Stepwiserefinement” ofprogram representsa\"divideandconquer\"approachtodesign.Insimplewords, breakacomplexprogram intosmaller,moremanageablemodulesthatcanbe reviewed and inspected before moving to the nextlevelofdetail.Step-wise refinementisapowerfulparadigm fordevelopingacomplexprogram from asimple program byaddingfeaturesincrementally. Someofthestepstakenforrefinementofaprogram are: 1. Analysisofthealgorithm usedtodeveloptheprogram,andanalysisof variouspartsoftheprogram and thenmaking appropriatechangesto improvetheefficiencyoftheprogram. 2. Keeptheprogram simpletoimprovememoryefficiency. 3. Evaluationandincorporationofmemorycompressionfeatures.

4. Debuggingandtestingperformedfirstto modulelevelandthento interfacelevel. 5. Takecareofcorrectworkingandclaritywhilemakingitfaster. Q.26 Writeafunctiontoremoveduplicatesfrom anorderedarray.Forexample,ifinput is:a,a,c,d,q,q,r,s,u,w,w,w,w;thentheoutputshouldbea,c,d,q,r,s,u,w. (8) Ans: ACprogram toremoveduplicatesfrom anoderedarray: #include<stdio.h> #include<conio.h> #include<string.h> voidmain() { inti,j,k,l,flag=0; chara[50]; clrscr(); printf(\"enterthecharactersinthearray\"); gets(a); l=strlen(a); for(i=0;i<l-1;i++) for(j=i+1;j<l;j++) { if(a[i]==a[j]) {l=l-1; for(k=j;k<l;k++) a[k]=a[k+1]; flag=1; j=j-1; } } if(flag==0) printf(\"Noduplicatesfound\"); else for(i=0;i<l;i++) printf(\"%c\",a[i]); getch(); } Q.27 Writeafunctiontosortthecharactersofthestringpassedtoitasargument. (8) Ans: ACfunctiontosortthecharactersofthestring: main() { chara[100],ch; inti,j; printf(\"\\nEnterthestring:->\"); gets(a); for(i=0;a[i]!='\\0';i++) { for(j=i+1;a[j]!='\\0';j++) { if(a[i]>a[j])

{ ch=a[i]; a[i]=a[j]; a[j]=ch; } } } printf(\"\\nStringaftersorting\\n\"); puts(a); getch(); } Q.28 Givetheoutputsofthefollowingcodesegments,ifanyandjustifyyouranswers. (i)#defineCUBE(x) (x*x*x) main() { printf(“%d”,CUBE(4+5)); } (ii)intj=5; printf(“%d”,j=j==6); printf(“%d”,j=++j==6); (iii)for(j=0;j=3;j++) printf(“%d”,j); (iv)main() { staticchara[]=“TestString”; staticchar*b=“TestString”; printf(“%d%d”,sizeof(a),sizeof(b)); } (v)main(){ enum test{RED,BLUE,GREEN}; enum testt=BLUE; printf(“%d”,t); } (vi)main(){ unionU{intj;charc;floatf;}u; u.j=10;u.c=‘A’;u.f=99.99; printf(“u.j=%du.c=%cu.f=%f”,u.j,u.c,u.f); } (2x6) Ans: (i) Outputis:49 macrocube(x*x*x)isexpandedinto(4+5*4+5*4+5)whichisevaluatedas 4+20+20+5=49duetopriorityofoperators.Sooutputis49. (ii) Outputis:00 Boththeexpressionsareevaluatedas0sotheoutputis0. (iii) Outputis:infiniteloop Thereisanincorrectassignment,j=3intestexpression. (iv) Outputis:122, Theprintfisprintingthesizeofchararrayaandcharb,nullcharisincluded. (v) Outputis:1, Thecompilerautomaticallyassignsintegerdigitsbeginningwith0toall theenumerationconstantssoBLUEhasvalue1.

(vi) Outputis:u.j=1311,u.c=’β’,u.f=99.989998 Thefirsttwooutputsareerroneousoutputwhichismachinedependent. Duringaccessing a union member,we should make sure thatwe are accessingthememberwhosevalueiscurrentlystoredotherwisewewill geterrors. Q.29 Whatarepreprocessordirectives? Listthree types ofthem.Whatis the differencebetween the following directives: #include <filename>and #include“filename”? (4) Ans: Preprocessordirectives:Thesearethecommandsgiventoaprogram knownas preprocessorthatprocessesthe source code before itpasses through the compiler.Eachofthesepreprocessordirectivesbeginswitha#symbol.Thesecan beplacedanywhereintheprogram butusuallyplacedbeforemain()oratthe beginningoftheprogram.Beforethesourcecodepassesthroughthecompiler,it isexaminedbythepreprocessorforanydirectives.Ifthereareany,appropriate action istaken and the source program is handed overto compiler.These directivescanbedividedintofollowingthreecategories: 1. Macrosubstitutiondirectives 2. Fileinclusiondirectives. 3. Compilercontroldirectives. #include“filename”:Thesearchforthefileismadefirstinthecurrentdirectory andtheninthestandarddirectoriesasmentionedintheincludesearchpath. #include<filename>:Thiscommandwouldlookforthefileinthestandardlist ofdirectories. Bothofthesedirectivescausetheentirecontentsoffilenameto beinserted intothesourcecodeatthatpointintheprogram. Q.30 Writeafunctiontocomputethefrequencyof‘the’inafile. (8) Ans: ACfunctiontocomputethefrequencyof‘the’: voidmain() { inti=0,j=0,k,n=0,m=0,l; chara[100],b[10],c[10]=\"the\"; clrscr(); printf(\"enterthesentence\"); gets(a); while(a[i]!='\\0') { if(a[i]==''||a[i]=='.') m++; i++; } i=0; l=0; while(l!=m+1)

{ while(a[i]!=''&&a[i]!='.'&&a[i]!='\\0') { b[j]=a[i]; j++; i++; } b[j]='\\0'; k=strcmp(b,c); if(k==0) { n++; j=0; if(a[i]!='\\0') i++; } else { j=0; i++; } l++; } if(n!=0) printf(\"itispresent%dtimes\",n); else printf(\"itisnotpresent\"); getch(); } Q.31 Writearecursivefunctiontoprintthereverseofastringpassedtoitasan argument. (8) Ans: Arecursivefunctiontoprintthereverseofastringisgivenbelow: voidmain() { charstr[100]; clrscr(); printf(\"enterastring\\n\"); gets(str); printf(\"reverseoftheenteredstringis\\n\"); rev(str); getch(); } rev(char*string) { if(*string) { rev(string+1); putchar(*string); } } Q.32 Writeaprogram whichacceptstwofilenamesfrom thecommandlineand

printswhetherthecontentsofthetwofilesaresameornot.Ifnot,thenprintthe firstlinenumberandthenthecontentsofthelinesfrom whichtheydiffer.Assume thatthelinesinboththefileshaveatmost80characters. (12) Ans: Aprogram thatacceptstwofilenamesfrom commandpromptandcheckiftwo filesaresameornot: #include<stdio.h> main(intargc,char*argv[]) { FILE*fp1,*fp2; charch1[80],ch2[80]; inti=1,j=1,l1=0,l2=0; if(argc!=3) { printf(\"\\nWrongnumberofarguments.\"); getch(); exit(); } fp1=fopen(argv[1],\"r\"); if(fp1==NULL) { printf(\"\\nunabletoopenthefile%s\",argv[1]); getch(); exit(); } fp2=fopen(argv[2],\"r\"); if(fp2==NULL) { printf(\"\\nunabletoopenthefile%s\",argv[2]); getch(); exit(); } l1=0; l2=0; while(i!=0&&j!=0) { i=fgets(ch1,80,fp1);l1++; j=fgets(ch2,80,fp2);l2++; if(strcmp(ch1,ch2)!=0) { printf(\"\\nContentsofbothFilesarenotEqual\"); printf(\"\\nLineNumber\\tContents\\tFilename\\n\"); printf(\"%d\\t\\t%s\\t\\tFrom%s\",l1,ch1,argv[1]); printf(\"%d\\t\\t%s\\t\\tFrom%s\",l2,ch2,argv[2]); exit(); } } if(i==0&&j==0) printf(\"\\nBothFilesareequal\"); else printf(\"\\nBothfilesarenotequal\"); getch(); }

Q.33 Differentiatebetweenthefollowing: (4) (i) callbyvalueandcallbyreference (ii)do..whileandwhileloops Ans: (i)CallbyvalueandCallbyreference Callbyvaluemeanssendingthevaluesofthearguments-Thevalueofeachofthe actualargumentsin the calling function is copied into corresponding formal argumentsofthecalledfunction.Thechangesmadetotheformalargumentshave noeffectonthevaluesofactualargumentsinthecallingfunction.Thistechnique ofpassing argumentsiscalledcallbyvalueillustrated byswapv(intx,inty) functioninthefollowingexample. Callbyreferencemeanssendingtheaddressesofthearguments-theaddressesof actualargumentsinthecallingfunctionarecopiedintoformalargumentsofthe calledfunction.Usingtheseaddressesweareactuallyworkingonactualargument so changeswillbereflected in the calling function.Thistechniqueofpassing argumentsis called callby reference,illustrated by swapr(int*x,int*y) in followingexample. #include<stdio.h> #include<conio.h> #include<math.h> voidmain(){ inti=10,j=20; clrscr(); printf(\"Thevaluesbeforeswapisi:%d,j:%d\\n\",i,j); swapv(i,j); printf(\"Thevaluesafterswapisi:%d,j:%d\\n\",i,j); printf(\"\\n\"); swapr(&i,&j); printf(\"Thevaluesafterswapisi:%d,j:%d\\n\",i,j); printf(\"\\n\"); getch(); } swapv(intx,inty) {inttemp; temp=x; x=y; y=temp; } swapr(int*x,int*y) { inttemp; temp=*x; *x=*y; *y=temp; } Thevalueofiandjis10and20onlyaftercallingfunctionswapv,thatiscallby value.Howevertheresultofcallingswapr(),callbyreferenceisi=20andj=10 (ii)do-whileandwhileloops whilestatement:Thebasicformatofwhilestatementis while(conditionalexpression) { ...blockofstatementsto execute... }Thewhileloopcontinuestoloopuntiltheconditionalexpressionbecomes false.Oncethisexpressionbecomefalse,thecontrolistransferredoutoftheloop.Onexit, theprogram continueswith thestatementimmediatelyafterthebodyoftheloop.For

example: i=0; while(i<10) { printf(“Helloworld\\n”); i++; } Thisstatementwillprint“Helloworld”10timesinanew lineandcomeoutofthe loopwhen‘i’become10. Dostatement:Thisloopconstructisoftheform: do { ...blockofstatementstoexecute... }while(conditionalexpression); Whileconstructcheckstheconditionalexpressionbeforetheloopisexecuted. Sometimesitisnecessarytoexecutethebodyoftheloopbeforetheconditional expressionisevaluated.Suchsituationsarehandledbydo-whileloopconstruct.On reachingthedostatement,thebodyoftheloopisevaluatedandattheendofthe loop,theconditionalexpressionischeckedfortrueorfalse.Iftrue,itcontinuesto evaluate the bodyagain and when condition become false,the controlis transferredtothestatementimmediatelyafterthewhilestatement. Forexample: do { printf(“Inputacharacter\\n”); ch=getch(); }while(ch=’n’); Thissegmentofprogram readsacharacterfrom thekeyboarduntil‘n’iskeyed in. Q.34 Writeaprogram togenerateatriangleasshownbelow forn=4.Theprogram shouldtaketheinputfrom theuser. A AB A AB C B A A B CD CB A (8) Ans: ACprogram togenerateatriangleforn=4islistedbelow: #include<conio.h> voidmain() { inti,j,k,ch; clrscr(); for(i=3;i>=0;i--) { ch=65; printf(\"\\n\\n\"); for(j=i;j>0;j--) printf(\"\"); for(k=i;k<4;k++) printf(\"%c\",ch++); ch-=2; for(j=i;j<3;j++)

printf(\"%c\",ch--); for(k=i;k>0;k--) printf(\"\"); } getch(); } Q.35 Writeafunctionthatacceptstwostringsstr1andstr2asargumentsandfinds whichofthetwoisalphabeticallygreater(withoutusingthelibraryfunctions).The functionshouldreturn1ifstr1isgreaterthanstr2,0ifstr1isequaltostr2,and-1 isstr1issmallerthanstr2. (8) Ans: Afunctionthataccepttwostringstocheckwhichoneisalphabeticallygreater: voidmain() { chara[10],b[10]; intk; clrscr(); printf(\"enter1ststring\"); gets(a); printf(\"enter2ndstring\"); gets(b); k=comp(a,b); if(k==1) printf(\"%sisgreaterthan%s\",a,b); if(k==-1) printf(\"%sislessthan%s\",a,b); if(k==0) printf(\"%sisequalto%s\",a,b); getch(); } intcomp(char*a,char*b) { inti=0,j=0,k; while(a[i]!='\\0'&&b[j]!='\\0) {if(a[i]<b[j]) return(-1); elseif(a[i]>b[j]) return(1); else i++; j++; } if(i==j) return(0); if(i<j) return(-1); if(i>j) return(1); } Q.36 Consideralinkedlisttostoreapolynomial,thatis,everynodeofthelinkedlisthas coefficient,exponentandpointertothenextnodeinthelist. (i)Defineastructurefornodeofsuchalist.

(ii)Writea function to subtracttwo such polynomials.The function should acceptpointerstothetwopolynomialsasargumentsandreturnthepointerto theresultantpolynomial.Assumethatthepolynomialspassedtothefunction areindecreasingorderontheexponents. (2+8) Ans: (i) Structureforpolynomialnode structpolynode { floatcoeff; intexp; structpolynode*link; }; (ii)Afunctionthatsubtracttwopolynomials: structpolynode*poly_sub(structpolynode*x,structpolynode *y) { structpolynode*z,*temp,*s=NULL; /*ifbothlinkedlistsareempty*/ if(x==NULL&&y==NULL) return; /*traversetilloneofthelistends*/ while(x!=NULL||y!=NULL) { /*createanewnodeifthelistisempty*/ if(s==NULL) { s=malloc(sizeof(structpolynode)); z=s; } /*createnewnodesatintermediatestages*/ else { z->link=malloc(sizeof(structpolynode)); z=z->link; } if(y==NULL&&x!=NULL) { z->coeff=x->coeff; z->exp=x->exp; z->link=NULL; x=x->link; continue; } if(x==NULL&&y!=NULL) { z->coeff=y->coeff; z->exp=y->exp; z->link=NULL; y=y->link; continue; } /*storeaterm ofthelargerdegreepolynomial*/ if(x->exp<y->exp) {


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook