z->coeff=y->coeff; z->exp=y->exp; z->link=NULL; y=y->link;/*gotothenextnode*/ } else { if(x->exp>y->exp) { z->coeff=x->coeff; z->exp=x->exp; z->link=NULL; x=x->link;/*gotothenextnode*/ } else { /*addthecoefficients,whenexponentsareequal*/ if(x->exp==y->exp) { /*assigningtheaddedcoefficient*/ z->coeff=x->coeff-y->coeff; z->exp=x->exp; z->link=NULL; /*gotothenextnode*/ x=x->link; y=y->link; } } }} return(s); } Q.37 Differentiatebetweenthefollowing: (6) (i) compilerandinterpreter (ii)unittestingandintegrationtesting (iii)syntaxerrorsandlogicalerrors Ans: (i)CompilerandInterpreter:Thesearetwotypesoflanguagetranslators. Acompilerconvertsthesourceprogram(user-writtenprogram)intoanobjectcode (machine language by checking theentire program before execution.Ifthe program iserrorfree,objectprogramiscreated and loaded into memoryfor execution.Acompilerproducesanerrorlistoftheprogram inonegoandallhave tobetakencareevenbeforetheexecutionoffirststatementbegin.Ittakesless timeforexecution. Aninterpreterisalso alanguagetranslatorthattranslatesand executes statementsintheprogram onebyone.Itworkononestatementatatimeandif errorfree,executestheinstructionbeforegoingtosecondinstruction.Debugging issimplerininterpreterasitisdoneinstages.Aninterpretertakesmoretimefor executionofaprogram ascomparedtoacompiler. (ii)Unittestingandintegrationtesting: Unittestingfocusesonthesmallestelementofsoftwaredesignviz.themodule. Unittestis conductedon each ofthe modules to uncovererrors within the boundaryofthemodule.Itbecomessimplewhenamoduleisdesignedtoperform onlyonefunction.Unittestingmakesheavyuseofwhite-boxtesting.
Integrationtestingisasystematicapproachforconstructingprogram structure whileconductingteststouncovererrorsassociatedwithinterfacing.Thereare likelytobeinterfacingproblems,suchasdatamismatchbetweenthemodules.In Incrementalintegrationtheprogram isconstructedandtestedinsmallsegments. Wehavetwotypesofintegrationtesting: -Top-DownIntegrationtesting -Bottom-UpIntegrationtesting (iii)Syntaxerrorsandlogicalerrors: Syntaxerrorsalsoknownascompilationerrorsarecausedbyviolationofthe grammarrulesofthelanguage.Thecompilerdetects,isolatetheseerrorsandgive terminatethesourceprogram afterlistingtheerrors. Logicalerrors:Thesearetheerrorsrelatedwiththelogicoftheprogram execution. Theseerrorsarenotdetectedbythecompilerandareprimarilyduetoapoor understandingoftheproblem oralackofclarityofhierarchyofoperators.Such errorscauseincorrectresult. Q.38 Writeafunctiontoreversethelinksinalinkedlistsuchthatthelastnodebecomes thefirstandthefirstbecomesthelastbytraversingthelinkedlistonlyonce. (8) Ans: ACfunctiontoreversethelinkedlist: structnode { intdata; structnode*link; }; voidreverse(structnode**x) { structnode*q,*r,*s; q=*x; r=NULL; /*traversetheentirelinkedlist*/ while(q!=NULL) { s=r; r=q; q=q->link; r->link=s; } *x=r; } Q.39 Defineastructureforanemployeeofanorganizationhavingemployeecode,name, address,phonenumberandnumberofdependents.Assumethat“allEmployees”is anarrayofemployeesinascendingorderontheemployeecode.Writeafunctionto displaythedetailsofanemployeegivenitsemployeecode. (8) Ans: Astructureforanemployeeandafunctiontodisplaythedetailsofan employee: structemployee { intemp_code; charemp_name[30];
charemp_address[50]; charemp_ph_num[10]; intno_of_dep; }allEmployees[100],b; voiddisplay() { intctr=0; fp=fopen(\"employee.c\",\"r\"); rewind(fp); while(fread(&allEmployees,sizeof(allEmployees[i]),1,fp)==1) { ctr++; clrscr(); heading(); printf(\"\\n\\n\\n\\tFollowingarethedetails:-\"); printf(\"\\n\\n\\tRecord#%d\",ctr); printf(\"\\n\\n\\t\\tCode:%d\",allEmployees[i].emp_code); printf(\"\\n\\n\\t\\tName:%s\",allEmployees[i].emp_name); printf(\"\\n\\n\\t\\tAddress:%s\",allEmployees[i].emp_address); printf(\"\\n\\n\\t\\tPhoneNumber:%s\",allEmployees[i].emp_ph_num); printf(\"\\n\\n\\t\\tNumberofDependents :%s\",allEmployees[i].no_of_dep); printf(\"\\n\\n\\n\\n\\t\\tPleasePressEnter...\"); getch(); } } Q.40 Explaintheconceptoftop-downdesignforaprogram. (5) Ans: TopdownDesign: 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 understood and maintained.Top-down programming isa programming style in whichdesignbeginsbyspecifyingcomplexpiecesandthendividingthem into successivelysmallerpieces.Eventually,thecomponentsarespecificenoughtobe codedandtheprogram iswritten.Thetechniqueforwritingaprogram usingtop- downmethodsistowriteamainprocedurethatnamesallthemajorfunctionsit willneed.Later,theprogramming team looksattherequirementsofeachof thosefunctions and the process is repeated.These compartmentalized sub- routineseventually willperform actions so simple they can be easily and conciselycoded.Whenallthevarioussub-routineshavebeencodedtheprogram is done. Q.41 Whatarecompilersandinterpreters?Listtheadvantagesofaninterpreterovera compiler.Underwhichsituationsyouwillprefertouseinterpreterovercompiler. (8) Ans: CompilerandInterpreter:Thesearetwotypesoflanguagetranslators.
Acompilerconvertsthesourceprogram(user-writtenprogram)intoanobject code(machinelanguagebycheckingtheentireprogram beforeexecution.Ifthe program iserrorfree,objectprogramiscreated and loaded into memoryfor execution.Acompilerproducesanerrorlistoftheprogram inonegoandallhave tobetakencareevenbeforetheexecutionoffirststatementbegin.Ittakesless timeforexecution.Aninterpreterisalsoalanguagetranslatorthattranslatesand executesstatementsintheprogram onebyone.Itworkononestatementatatime and iferror free, executes the instruction before going to second instruction.Debugging is simplerin interpreteras itis done in stages.An interpretertakesmoretimeforexecutionofaprogram ascomparedtoacompiler. Q.42 Giveanytwocharacteristicsofagoodprogramminglanguage. (3) Ans: Twocharacteristicsofagoodprogramminglanguageare: 1. Itshouldsupportalargenumberofdatatypes,built-infunctionsandpowerful operators.Insimpleterms,aprogramminglanguageshouldberobust,only thenitcanefficientandfast. 2. Itshouldbeportablemeansthatprogramswrittenforonecomputercanbe runonanotherwithlittleornomodification. Q.43 Writeaprogram inCtodemonstratetheuseofscoperesolutionoperator. (8) Ans: Thescoperesolutionsoperatorisusedtofindthevalueofavariableoutof thescopeofthevariable. Example: inti=10; main(){ inti=5; cout<<::i; cout<<i; } ::ireferstothevaluejustbeforethescope(i.e.10). Q.44 Why‘&’operatorisnotusedwitharraynamesinascanfstatement? (2) Ans: Inscanf()statement,the“addressof”operator(&)eitherontheelementofthe array(e.gmarks[i])oronthevariables(e.g&rate)areused.Indoingso,the addressofthisparticulararrayelementispassedtothescanf()function,rather thenitsvalue;whichiswhatscanf()requires.BUTmanytimestheaddressof zerothelement(alsocalledasbaseaddress)canbepassedbyjustpassingthe nameofthearray. Q.45 WriteaCprogramtoreadasetofnumbersfrom thekeyboardandtosorttogiven arrayofelementsinascendingorderusingafunction.(7) Ans:
ACprogram tosortgivenarrayofelementsinascendingorder: (6) #include<stdio.h> #include<conio.h> voidsort(int*,int); voidmain() { inta[10]; inti,n; clrscr(); printf(\"howmanynumbersuwanttoenterin1starray:\"); scanf(\"%d\",&n); printf(\"enternumbers:\\n\"); for(i=0;i<n;i++) scanf(\"%d\",&a[i]); sort(a,n); for(i=0;i<n;i++) printf(\"%d\",a[i]); getch(); } voidsort(int*a,intm) { inti,j,temp; for(i=0;i<m-1;i++) { for(j=i+1;j<m;j++) { if(a[i]>a[j]) { temp=a[j]; a[j]=a[i]; a[i]=temp; } } } } Q.46 Writearecursivefunctiontocalculatethefactorialofapositiveinteger. Ans: Arecursivefunctiontocalculatethefactorialofagivenpositivenumber: voidmain() { intn,c; clrscr(); printf(\"enterthenumber:\"); scanf(\"%d\",&n); c=fact(n); printf(\"factorialof%d=%d\",n,c); getch(); } fact(intn) { intfactorial; if(n==1||n==0) return(1); else
factorial=n*fact(n-1); return(factorial); } Q.47 Howdoesanenumstatementdifferfrom atypedefstatement? (3) Ans: Typedefstatementallowsuserto define an identifierthatwould representan exiting data type.Theuser-defined data type identifiercan be used furtherto declarevariables.Ithasthefollowingsyntax typedefdatatypeidentifier; wheredatatypereferstoexitingdatatypeandidentifieristhenew namegiven tothisdatatype.Forexample typedefintnos; nosheresymbolizesinttypeandnowitcanbeusedlatertodeclarevariableslike nosnum1,num2,num3; enumstatementisused to declarevariablesthatcan haveoneofthevalues enclosedwithinbracesknownasenumerationconstant.Afterdeclaringthis,we candeclarevariablestobeofthis‘new’type.Ithasthefollowingsyntax enum identifier{value1,value2,value3……,valuen); wherevalue1,value2etcarevaluesoftheidentifier.Forexample enum day{Monday,Tuesday,Wednesday,Thursday,Friday, Saturday} Wecandefinelater enum dayworking_day; working_day=Monday; Thecompiler automatically assigns integer digits beginning with 0 to allenumerationconstants. Q.48 Defineastructure.Howitisdifferentfrom union?WriteaCprogram toillustrate astructure. (8) Ans: Structuresandunion Astructurecontainsanorderedgroupofdataobjects.Unliketheelementsofan array,thedataobjectswithinastructurecanhavevarieddatatypes.Eachdata objectinastructureisamemberorfield.Aunionisanobjectsimilartoastructure exceptthat 1.Inunion,oneblockisusedbyallthememberoftheunionbutincaseofstructure, eachmemberhastheirownmemoryspace.Allofunionmembersstartatthesame locationinmemory.A unionvariablecanrepresentthevalueofonlyoneofits membersatatime. 2.Thesizeoftheunionisequaltothesizeofthelargestmemberoftheunion whereassizeofthestructureisthesum ofthesizeofallmembersofthestructure. Forexample structbook { char name; intpages; floatprice; }; Now ifwedefinestructbookbook1,thenitwillassign1+2+4=7bytesofmemory forbook1. Ifwedefineitasunionlike unionbook
{ charname; intpages; floatprice; }; Thecompilerallocatesapieceofstoragethatislargeenoughtostorethelargest variabletypesinunion.Allthreevariableswillsharethesameaddressand4bytes ofmemoryisallocatedtoit.Thisprogram ofstructurewillreadname,rollnoand marksin6subjectof3students&thendisplaynameandrollofstudentwho scoredmorethan70%marksintotal. #include<stdio.h> #include<conio.h> structstudent { charname[10]; introll_no; intmarks[6]; inttotal; intper; }; voidmain() { structstudentstu[3]; inti,j,req; clrscr(); for(i=0;i<3;i++) { stu[i].total=0; printf(\"enterdatafor%dstudents:\",i+1); printf(\"\\nentername\"); scanf(\"%s\",stu[i].name); printf(\"\\nenterrollno \"); scanf(\"%d\",&stu[i].roll_no); printf(\"\\nentermarksinsubjects\\t\"); for(j=0;j<6;j++) { printf(\"\\nentermarksin%dsubject\\t\",j+1); scanf(\"%d\",&stu[i].marks[j]); stu[i].total=stu[i].total+stu[i].marks[j]; } stu[i].per=stu[i].total/6; printf(\"\\n\"); } for(i=0;i<3;i++) { if(stu[i].per>70) { printf(\"\\nSTUDENT %d\",i+1); printf(\"\\nname:\"); printf(\"%s\",stu[i].name); printf(\"\\nrollno\"); printf(\"%d\",stu[i].roll_no); for(j=0;j<6;j++) { printf(\"\\nmarksin%dsubject\\t\",j+1); printf(\"%d\",stu[i].marks[j]);
} printf(\"\\nTOTAL :%d\",stu[i].total); } } getch(); } Q.49 WriteaCprogram toconcatenatetwostrings. (8) Ans: Aprogram toconcatenatetwostringsisgivenbelow: #include<stdio.h> #include<conio.h> voidmain() { chara[100],b[100]; inti=0,j=0; clrscr(); printf(\"enterthesetoflines\"); gets(a); while(a[i]!='\\0') { while(a[i]!=''&&a[i]!='\\t'&&a[i]!='\\0') { b[j]=a[i]; j++; i++; } while(a[i]==''||a[i]=='\\t') i++; } b[j]='\\0'; printf(\"%s\",b); getch(); } Q.50 Whatisapointer?Howitisdeclared?WriteaCprogram toreverseastringusing pointers. (2+3+4) Ans: Apointerisavariablewhichcontainstheaddressinmemoryofanothervariable. Wecanhaveapointertoanyvariabletype.Theunaryormonadicoperator&gives the “address ofavariable”.The indirectionordereference operator*gives the “contentsofanobjectpointedtobyapointer”. Apointerisdeclaredasfollows: int*ptr; where*ptrisapointerofinttype. Aprogram toreverseastringusingpointerislistedbelow: #include<stdio.h> #include<conio.h> voidmain() { inti,j; char*a; clrscr();
printf(\"enterastring\"); scanf(\"%s\",a); i=0; while(*(a+i)!='\\0') i++; for(j=i-1;j>=0;j--) printf(\"%c\",*(a+j)); getch(); } Q.51 Differentiatebetween pointersand arrays?WriteaC program to displaythe contentsofanarrayusingapointerarithmetic. (2+5) Ans: Pointerandarrays: PointersandarraysareverycloselylinkedinC.Considerthefollowingstatements: inta[10],x; int*ptr;/*ptrisapointervariable*/ ptr=&a[0];/*ptrpointstoaddressofa[0]*/ x=*ptr; /*x=contentsofptr(a[0]inthiscase)*/ Apointerisavariablesowecando ptr=aandptr++; whileanarrayisnotavariablesostatements a=paanda++areillegal. ACprogram todisplaythecontentsofanarrayusingapointerarithmeticis listedbelow: //displaythecontentsofanarrayusingpointer #include<conio.h> voidmain() { int*p,sum,i; staticintx[5]={5,9,6,3,7}; i=0; p=x; sum=0; clrscr(); printf(\"\\nElementValueAddress\\n\\n\"); while(i<5) { printf(\"x[%d] %d %u\\n\",i,*p,p); sum+=*p; i++; *p++; } printf(\"\\nSum =%d\\n\",sum); printf(\"\\n&x[0]=%u\\n\",&x[0]); printf(\"\\np =%u\\n\",p); getch(); } Q.52 Whatisalinkedlist?Listdifferenttypesoflinkedlist.WriteaC program to demonstrateasimplelinearlinkedlist. (2+2+6)
Ans: Linkedlist:Alinkedlistisaselfreferentialstructurewhichcontainamemberfield thatpointtothesamestructuretype.Insimpleterm,alinkedlistiscollectionsof nodesthatconsistsoftwofields,onecontainingtheinformationaboutthatnode, item andsecondcontaintheaddressofnextnode.Suchastructureisrepresentedas follows: structnode { intitem; structnode*next; }; Infopartcanbeanyofthedatatype;addresspartshouldalwaysbethestructure type. Linkedlistsareoffollowingtypes: 1. LinearSinglylinkedlist:Alisttypeinwhicheachnodepointstothenext nodeandthelastnodepointstoNULL. 2. Circularlinkedlist:Listswhichhavenobeginningandnoend.Thelast nodepointsbacktothefirstitem. 3. DoublylinkedlistorTwo-waylinkedlist:Theselistscontaindoublesetof pointers,onepointingtothenextitem andotherpointingtotheprecedingitem. Soonecantraversethelistineitherdirection. 4. Circularlydoublylinkedlist:Itemploysboththeforwardandbackward pointerincircularform. Aprogram todemonstratesimplelinearlinkedlistisgivenbelow: #include<stdio.h> #include<stdlib.h> #defineNULL0 structlinked_list { intnumber; structlinked_list*next; }; typedefstructlinked_listnode; voidmain() { node*head; voidcreate(node*p); intcount(node*p); voidprint(node*p); clrscr(); head=(node*)malloc(sizeof(node)); create(head); printf(\"\\n\"); print(head); printf(\"\\n\"); printf(\"\\nNumberofitems=%d\\n\",count(head)); getch(); } voidcreate(node*list) { printf(\"Inputanumber\\n\"); printf(\"(type-999toend):\");
scanf(\"%d\",&list->number); if(list->number==-999) list->next=NULL; else { list->next=(node*)malloc(sizeof(node)); create(list->next); } return; } voidprint(node*list) { if(list->next!=NULL) { printf(\"%d-->\",list->number); if(list->next->next==NULL) printf(\"%d\",list->next->number); print(list->next); } return; } intcount(node*list) { if(list->next==NULL) return(0); else return(1+count(list->next)); } Q.53 ExplainthedifferenttypesofmemoryallocationsinC. (6) Ans: Differenttypesofmemoryallocationfunctionare: (i)malloc():Itisamemoryallocationfunctionthatallocatesrequestedsizeof bytesandreturnsapointertothefirstbyteoftheallocatedspace.Themalloc functionreturnsapointeroftypevoidsowecanassignittoanytypeofpointer. Ittakesthethefollowingform: ptr=(casttype*)malloc(byte-size); whereptrisapointeroftypecast-type.Forexample,thestatement x=(int *)malloc(10 *sizeof(int))means that a memory spaceequivalentto 10timesthesizeofanintbyteisreservedandthe addressofthefirstbyteofmemoryallocatedisassignedtothepointerxofint type. Themallocfunctioncanalso allocatespaceforcomplexdatatypessuch asstructures.Forexample: ptr=(structstudent*)malloc(sizeof(structstudent));whereptrisapointerof typestructstudent. (ii)calloc():Itisanothermemoryallocationfunctionthatallocatesspaceforan arrayofelements,initializesthem tozeroandthenreturnsapointertothe memory.Thisfunctionisnormallyusedforrequestingmemoryspaceatrun time.Ittakesthefollowingform: ptr=(casttype*)calloc(n,element-size); Thisstatementallocatescontiguousspacefornblocks,eachofsizeelement- sizebytes.
(iii)realloc():reallocisamemoryallocationfunctionthatmodifiesthesizeof previouslyallocatedspace.Sometimeitmayhappenthattheallocatedmemory spaceislargerthanwhatisrequiredoritislessthanwhatisrequired.Inboth cases,wecanchangethememorysizealreadyallocatedwiththehelpofthe reallocfunctionknownasreallocationofmemory.Forexample,iftheoriginal allocationisdonebystatement ptr=malloc(size); thenreallocationisdonebythestatement ptr=realloc(ptr,newsize);whichwillallocateanew memoryspaceof sizenewsizetothepointervariableptrandreturnsapointertothefirstbyteof thenewmemoryblock. Q.54 Explainthefollowingfilefunctions. (i)fgetc() (ii)ftell (iii)fgets() (iv)rewind() (v)fseek (5) Ans: (i)getc():readsacharacterfrom afile.Thisfunctionisusedtoreadacharacter from afilethathasbeenopenedinthereadmode.Forexample,thestatement c=getc(fp2);wouldreadacharacterfrom thefilewhosefilepointerisfp2. (ii)ftell():givesthecurrentpositioninthefilefrom thestart.ftelltakesafile pointerand returnsanumberoftypelong,thatcorrespondstothecurrent position.Forexample:n=ftell(p);wouldgivetherelativeoffsetninbytesofthe currentposition.Thismeansthatnbyteshavealreadybeenread(orwritten). (iii)fgets():To read a line ofcharacters from a file,we use the fgets() libraryfunction.The prototype is char*fgets(char*str,intn,FILE *fp);The argumentstrisapointertoabufferinwhichtheinputistobestored,nisthe maximum numberofcharacterstobeinput,andfpisthepointertotypeFILE thatwasreturnedbyfopen()whenthefilewasopened. (iv)rewind():setsthepositiontothebeginningofthefile.Italsotakesafile pointerandresetthepositiontothestartofthefile.Forexample: rewind(fp); n=ftell(fp);wouldassign0tonbecausefilepointerhasbeensettothestartof thefilebyrewind. (v)fseek():setsthepositiontoadesiredpointinthefile.fseekfunctionisused tomovethefilepositiontoadesiredlocationwithinthefile.Forexample: fseek(fp,m,0);wouldmovethefilepointerto(m+1)thbyteinthefile. Q.55 Writeaprogram thatreadsthefollowinginformationfrom thekeyboard– student_id,studentnameandtotalmarksandwritertoafile.Aftertaking theinformation itcloses the file and displays the information aboutthe studentwhosestudent_idhasbeenenteredbytheuser. (9) Ans: //displayrecordsonthebasisofstudentidentered. #include<stdio.h> structstudent { intstu_id; charstu_name[30]; intmarks; }s[100],b;
voidmenu(); voidcreate(); voiddisplay(); voidsearch(); voidheading(); voiddisp(); inti=0; FILE*fp,*ft; voidmain() { intfirst_ch; clrscr(); heading(); printf(\"\\n\\n\\n\\t\\t\\t\\t MENU\"); printf(\"\\n\\n\\n\\t\\t1.Createanewdatabase.\"); printf(\"\\n\\n\\t\\t2.Continuewiththeexistingdatabase.\"); printf(\"\\n\\n\\t\\t3.Exit.\"); printf(\"\\n\\n\\n\\t\\tEnteryourchoice(1-3):\"); scanf(\"%d\",&first_ch); switch(first_ch) { case1: create(); break; case2: menu(); break; case3: exit(); break; default: printf(\"\\n\\n\\n\\t\\tYouhaveenteredwrongchoice...!!!..Theprogram willexitnow.\"); } getch(); } voidcreate() { intctr=0; charch='y'; fp=fopen(\"student.c\",\"w\"); while(ch=='y') { ctr++; clrscr(); heading(); printf(\"\\n\\n\\n\\n\\tEntertheEmployeeRecords:\\n\"); printf(\"\\n\\n\\t\\tStudentid:\"); fflush(stdin); scanf(\"%d\",&s[i].stu_id); printf(\"\\n\\n\\t\\t Name:\"); fflush(stdin); scanf(\"%s\",&s[i].stu_name); printf(\"\\n\\n\\t\\tTotalMarks:\"); fflush(stdin); scanf(\"%d\",&s[i].marks); fwrite(&s,sizeof(s[i]),1,fp);
printf(\"\\n\\n\\n\\t\\tDoyouwishtoentermorerecords(y/n)?\"); ch=getch(); } printf(\"\\n\\n\\n\\t%dRecordshavebeenwritteninthefile.\",ctr); fclose(fp); menu(); } voidmenu() { charch; clrscr(); heading(); printf(\"\\n\\n\\n\\t\\t\\t MENU:-\"); printf(\"\\n\\n\\t\\t1.ToDISPLAYalltherecords\"); printf(\"\\n\\n\\t\\t2.ToSEARCHarecord\"); printf(\"\\n\\n\\t\\t3.EXIT\"); printf(\"\\n\\n\\n\\t\\tEnteryourchoice(1-3):\"); scanf(\"%d\",&ch); switch(ch) { case1: display(); break; case2: search(); break; case3: exit(); break; default: printf(\"\\n\\n\\tYouhave entered a WRONG CHOICE..!!..Please Re- enteryourchoice\"); menu(); } } voiddisplay() { intctr=0; fp=fopen(\"student.c\",\"r\"); rewind(fp); while(fread(&s,sizeof(s[i]),1,fp)==1) { ctr++; clrscr(); heading(); printf(\"\\n\\n\\n\\tFollowingarethedetails:-\"); printf(\"\\n\\n\\tRecord#%d\",ctr); printf(\"\\n\\n\\t\\tStudentid:%d\",s[i].stu_id); printf(\"\\n\\n\\t\\t Name:%s\",s[i].stu_name); printf(\"\\n\\n\\t\\tTotalMarks:%d\",s[i].marks); printf(\"\\n\\n\\n\\n\\t\\tPleasePressEnter...\"); getch(); } menu(); } voidsearch()
{ intf,flag=0; charch='y'; while(ch=='y') { clrscr(); flag=0; heading(); printf(\"\\n\\n\\n\\tEntertheStudentidtobesearched:\"); fflush(stdin); scanf(\"%d\",&b.stu_id); fp=fopen(\"student.c\",\"r\"); rewind(fp); while(fread(&s,sizeof(s[i]),1,fp)==1) { if(s[i].stu_id==b.stu_id) { clrscr(); flag=1; heading(); printf(\"\\n\\n\\n\\tThedetails of the record having Studentid%dare:-\",b.stu_id); disp(); } } fcloseall(); if(flag==0) printf(\"\\n\\n\\n\\t\\tNoMatchfound!!\"); printf(\"\\n\\n\\n\\tDouwishtosearchformorerecords(y/n)?\"); ch=getch(); } menu(); } voidheading() { printf(\"\\n\\n\\t\\t\\tSTUDENTDATABASEMANAGEMENT\"); printf(\"\\n\\n\\t\\t\\t----------------------------\"); } Q.56 Definemacros. (2) Ans: Amacroisapre-processordirectivewhichisaprogramthatprocessesthesourcecode beforeitpassesthroughthecompiler.Theseareplacedinthesourceprogram before themain.Todefineamacro,#definestatementisused.Thisstatement,alsoknownas macrodefinitiontakesthefollowinggeneralform: #defineidentifierstring Thepre-processorreplaceseveryoccurrenceoftheidentifierinthesourcecodebythe string.The preprocessordirective definition isnotterminated bya semicolon.For example #defineCOUNT 100willreplacealloccurrencesofCOUNT with100inthewhole program beforecompilation. Q.57 WriteaC program thatreadstwo stringsstr1andstr2andfindstheno of
occurrenceofsmallerstringsinlargestring. (8) Ans: #include<conio.h> #include<string.h> voidmain() { charstr1[100],str2[100],a[100],b[100],c[100]; intlen1,len2,l1,l2,k=0,i,j,count=0,n; clrscr(); printf(\"\\nEnterthefirststring:\"); gets(str1); printf(\"\\nEnterthesecondstring:\"); gets(str2); len1=strlen(str1); len2=strlen(str2); if(len1>len2) { strcpy(a,str1); strcpy(b,str2); l1=len1; l2=len2; } elseif(len2>len1) { strcpy(a,str2); strcpy(b,str1); l1=len2; l2=len1; } else printf(\"\\n\\nPleaseenteronestringsmallerthantheother!!!\"); for(i=0;i<l1;i++) { n=i; for(j=1;j<=l2;j++) c[k++]=a[n++]; c[k]='\\0'; if(strcmp(b,c)==0) ++count; k=0; } printf(\"\\nThenumberofoccurencesis:%d\",count); getch(); } Q.58 Explainpathtesting. (6) Ans: PathTesting:Testinginwhichallpathsintheprogram sourcecodearetestedatleast once.Pathtestinghasbeenoneofthefirsttestmethods,andeventhoughitisa typicalwhiteboxtest,itisnowadaysalsousedinblackboxtests.First,acertain paththroughtheprogram ischosen.Possibleinputsandthecorrectresultarewritten
down.Then theprogram isexecuted byhand,and itsresultiscomparedto the predefined.Possiblefaultshavetobewrittendownatonce. Q.59 Distinguishbetweenmalloc()andcalloc(). (2) Ans: Whilemallocallocatesasingleblockofstoragespace,callocallocatesmultipleblock ofstorage,eachofthesamesize,andthensetsallbytestozero.(ExplainedinQ53) Q.60 Whatisacompiler?Whattypeoferrorscanbedetectedbyit?Howdoesitdiffer from aninterpreter? (2+3+3) Ans: ACompilerisaprogramthatacceptsaprogram writteninahighlevellanguageand producesanobjectprogram.Thetypesoferrorsdetectedbyacompilerare: · Syntaxerrors--Thecompilercannotunderstandaprogram becauseitdoesnot followthesyntaxthatistherulesandgrammarofaparticularlanguage.Common syntaxerrorsinclude · missingormisplaced;or}, · missingreturntypeforaprocedure, · Missingorduplicatevariabledeclaration. · Typeerrorsthatinclude · typemismatchonassignment, · typemismatchbetweenactualandformalparameters. Aninterpreterisaprogram thatappearstoexecuteasourceprogram asifitwere machinelanguage. Q.61 Whatisasubroutine?Howdosubroutineshelpinprogram writing? (2+2) Ans: A subroutineisanamed,independentsectionofC codethatperformsaspecifictask andoptionally returns a value to the calling program. Some of the importantcharacteristicsofsubroutinethathelpinprogram writingare: · Asubroutineisnamed,eachhaveauniquename.Byusingthatnameinanother partoftheprogram,onecanexecutethestatementscontainedinthesubroutine. · Asubroutineisindependentthatcanperformitstaskwithoutinterferencefrom or interferingwithotherpartsoftheprogram. · Asubroutineperformsaspecifictask.Ataskisadiscretejobthataprogram must perform aspartofitsoveralloperation,suchassendingalineoftexttoaprinter,sorting anarrayintonumericalorder,orcalculatingacuberoot. · Asubroutinecanreturnavaluetothecallingprogram.Whenaprogram callsa subroutine,then statements itcontains areexecuted.These statements can pass informationbacktothecallingprogram. Q.62 Definetheterm ‘complexityofanalgorithm;andexplainworst-caseandaverage caseanalysisofanalgorithm. (2+4) Ans: Complexityofanalgorithm isthemeasureofanalysisofalgorithm.Analyzingan
algorithm meanspredictingtheresourcesthatthealgorithmrequiressuchasmemory, communicationbandwidth,logicgatesandtime.Mostoftenitiscomputationaltime thatis measured forfinding a more suitablealgorithm.This is known as time complexityofthealgorithm.Therunningtimeofaprogram isdescribedasafunction ofthesizeofitsinput.Onaparticularinput,itistraditionallymeasuredasthenumber ofprimitiveoperationsorstepsexecuted.Worstcaseanalysisofanalgorithm isan upperboundontherunningtimeforanyinput.Knowingthatinadvancegivesusa guaranteethatthealgorithm willnevertakeanylonger.Averagecaseanalysisofan algorithm meansexpectedrunningtimeofanalgorithm onaverageinputdataset.The averagecaseisoftenasbadastheworstcase.Oneproblem withperformingan averagecaseanalysisisthatitisdifficulttodecidewhatconstitutesan“average”input foraparticularproblem.Oftenweassumethatallinputsofagivensizeareequally likely. Q.63 WriteaC program togenerateaseriesofArmstrongnumbers.A numberisan Armstrongnumberifthesum ofthecubeofitsdigitisequaltothenumber. (6) Ans: ACprogram togenerateaseriesofArmstrongnumbersislistedbelow: #include<stdio.h> #include<conio.h> #include<math.h> voidmain() { intn,r,k,sum=0,up; clrscr(); printf(\"enterthelimitofseries\"); scanf(\"%d\",&n); up=n; while(up>1) { k=n; sum=0; while(n>0) { r=n%10; sum=sum+pow(r,3); n=n/10; } if(sum==k) printf(\"%d\\t\",k); up--; n=up; } getch(); } Q.64 WriteaCprogramtogeneratethefollowingseries: (8) Ans: ACprogram togenerateanexponentialseriesisgivenbelow:
main() { intn,i=0,j=1; longintfact=1; clrscr(); printf(\"\\nEnterthelimitfortheseries:->\"); scanf(\"%d\",&n); if(n%2!=0) n-=1; printf(“X+”); for(i=1;i<=n;) { fact=1;j=1; while(j<=i) { fact*=j; j++; } printf(\"\\tX^%d/%ld\\t+\",i,fact); i*=2; } getch(); } Q.65 Whatisbubblesort?Writeaprogram tosortalistofnelementsofanarrayusing bubblesort. (8) Ans: BubbleSort: Thebasicideainbubblesortistoscanthearraytobesortedsequentiallyseveral times.Eachpassputsthelargestelementinitscorrectpositionbycomparingeach elementinthearraywithitssuccessorandinterchangingthetwoelementsiftheyare notinproperorder.Thefirstpassputthelargestelementat(n-1)thpositioninanarray ofnelements,nextpassputsecondlargestelementat(n-2)thpositionandsoon.This wayeachelementslowlybubblesuptoitsproperpositionthatiswhyitiscalledbubble sort.Aprogram sortingarrayelementusingbubblesortisgivenbelow: #include<stdio.h> #include<conio.h> voidmain() { inta[20],i,j,n,c,flag; clrscr(); printf(\"howmanynumbersuwanttoenter:\\n\"); scanf(\"%d\",&n); printf(\"\\nenterthenumbers:\\n\"); for(i=0;i<n;i++) scanf(\"%d\",&a[i]); for(i=0;i<n-1;i++) { for(j=0;j<n-1-i;j++) { if(a[j]>a[j+1]) { c=a[j]; a[j]=a[j+1];
a[j+1]=c; flag=0; } } if(flag) break; else flag=1; } printf(\"sortedelements:\\n\"); for(i=0;i<n;i++) printf(\"%d\\t\",a[i]); printf(\"\\n\"); getch(); } Q.66 Explainthedifferencebetweenafunctiondeclarationandfunctiondefinition. (4) Ans: FunctiondeclarationandFunctiondefinition: Afunctiondeclarationcontainsthenameofthefunction,alistofvariables thatmustbepassedtoit,andthetypeofvariableitreturns,ifany.For exampleinthefollowingprogram inline2,thefunctioncubeisdeclared. Thevariablestobepassedtothefunctionarecalledarguments,andthey areenclosedinparenthesesfollowingthefunction'sname.Inthisexample, thefunction'sargumentislongx.Thekeywordbeforethenameofthe functionindicatesthetypeofvariablethefunctionreturns.Inthiscase,a typelongvariableisreturned.Thefunctionitselfiscalledthefunction definition.Inthefollowingexample,afunctioncubeisdefinedfrom line13 to18.Afunctiondefinitionhasfollowingseveralparts: ·Functionheader:Thefunctionstartsoutwithafunctionheaderonline 13.Thefunctionheaderisatthestartofafunction,anditgivesthe function's name,the function's return type anddescribes its arguments. The function header is identical to the functiondeclarationminusthesemicolon. ·FunctionBody:Thebodyofthefunction,lines14through18,isenclosedinbraces. Thebodycontainsstatementsthatareexecuted wheneverthefunction is called.Localvariablesaredeclaredwithinafunctionbody.Finally,thefunction concludeswithareturnstatementonline17,whichsignalstheendofthe functionanditpassesavaluebacktothecallingprogram. Thefollowingprogram usesafunctiontocalculatethecubeofa number. 1:#include<stdio.h> 2:longcube(longx); 3:longa,result; 4:main() 5:{ 6:printf(\"Enteranintegervalue:\"); 7:scanf(\"%d\",&a); 8:result=cube(a);
9:printf(\"\\nThecubeof%ldis%ld.\\n\",a,result); 10:} 11: 12:/*Function:cube()-Calculatesthecubevalueofavariable*/ 13:longcube(longx) 14:{ 15:longy; 16:y=x*x*x; 17:returny; 18:} Q.67 Whatisapre-processor?Whichpre-processorisusedtodefineamacro? (4) Ans: Apre-processorisaprogram thatprocessesthesourcecodebeforeitpassesthrough thecompiler.Itoperatesunderthecontrolofpreprocessordirective.Theseareplaced inthesourceprogram beforethemain. Todefineamacro,#definestatementisused.Thisstatement,alsoknownasmacro definitiontakesthefollowinggeneralform: #defineidentifierstring Thepre-processorreplaceseveryoccurrenceoftheidentifierinthesourcecodebythe string.The preprocessordirective definition isnotterminated bya semicolon.For example #defineCOUNT100willreplacealloccurrencesofCOUNTwith100inthewhole programbeforecompilation. Q.68 WhatarethedifferentstorageclassesinC? (4) Ans: StorageclassesinC TherearefourstorageclassesinC: a.Automaticstorageclass:Thefeaturesofvariablesareasfollows -Storage:Memory -Defaultinitialvalue:Garbagevalue -Scope:Localtotheblockinwhichdefined -Life:tillthecontrolremainswithintheblockinwhichdefined. b.Registerstorageclass:Thefeaturesofvariablesareasfollows -Storage:CPUregisters -Defaultinitialvalue:Garbagevalue -Scope:Localtotheblockinwhichdefined -Life:tillthecontrolremainswithintheblockinwhichdefined c.Staticstorageclass:Thefeaturesofvariablesareasfollows -Storage:Memory -Defaultinitialvalue:Zero -Scope:Localtotheblockinwhichdefined -Life:valueofvariablepersistsbetweendifferentfunctioncalls. d.Externalstorageclass:Thefeaturesofvariableshereareasfollows -Storage:Memory -Defaultinitialvalue:Zero -Scope:global -Life:Aslongasprogram executiondoesnotcometoanend.
Q.69 Differentiatebetweenrecursionanditeration. (4) Ans: Recursionanditeration: Thefactorialofanumber,writtenasn!,canbecalculatedasfollows: n!=n*(n-1)*(n-2)*(n-3)*...*(2)*1 Thisapproachiscallediteration,thatisstepbystepcalculation. However,wecanalsocalculaten!like: n!=n*(n-1)! Goingonestepfurther,wecancalculate(n-1)!usingthesameprocedure: (n-1)!=(n-1)*(n-2)! Wecancontinuecalculatingrecursivelyuntilthevalueofnis1.This approachiscalledrecursion.Itreferstoasituationinwhichafunction callsitselfeitherdirectlyorindirectly.Indirectrecursionoccurswhenone functioncallsanotherfunctionthatthencallsthefirstfunction. Q.70 Differentiatebetweenpointer(*)andaddress(&)operatorusingexamples. (4) Ans: The indirection operator(*)getsthe valuestored in the memorylocation whose addressisstored inapointervariable.Theaddressof(&)operatorreturnsthe addressofthememorylocationinwhichthevariableisstored.Theoutputofthe followingexampleshowsthedifferencebetween*and&. //differencebetween*and&. #include<conio.h> voidmain() { intk; int*ptr; clrscr(); k=10; ptr=&k; printf(\"\\nValueofkis%d\\n\\n\",k); printf(\"%disstoredataddr%u\\n\",k,&k); printf(\"%disstoredataddr%u\\n\",*ptr,ptr); *ptr=25; printf(\"\\nNowk=%d\\n\",k); getch(); } Output:Valueofkis10 10isstoredataddr65524 10isstoredataddr65524 Nowk=25 Q.71 Writeaprogram tofindthehighestofthreenumbersusingpointertofunction.6) Ans: ACprogram tofindthehighestofthreenumbersusingpointertofunctionislisted below: #include<conio.h> voidmain() {
intx,y,z; clrscr(); printf(\"\\nEnterthreenumbers:\"); scanf(\"%d%d%d\",&x,&y,&z); printf(\"\\n\\nThehighestofthethreenumbersis:\"); highest(&x,&y,&z); getch(); } highest(a,b,c) int*a,*b,*c; { if(*a>*b&&*a>*c) printf(\"%d\",*a); elseif(*b>*a&&*b>*c) printf(\"%d\",*b); else printf(\"%d\",*c); } Q.72 Differentiatebetween i. Staticvariablesandautovariables. (6) ii. Executionerrorandcompilationerror. Ans: (i) Staticvariablesandautovariables: Staticvariables:Thefeaturesareasfollows Declarationplace:-maybedeclaredinternallyorexternally. Declarationsyntax:-weusethekeywordstatictodeclareastaticvariable. Staticintage; Defaultinitialvalue:-Zero Scope:-incaseofinternalstaticvariable,thescopeislocaltothefunctionin whichdefined whilescopeofexternalstaticvariableisto allthefunctions definedintheprogram. Life:-valueofvariablepersistsbetweendifferentfunctioncalls. Automaticvariables:Thefeaturesareasfollows Declaration place:-declared inside a function in which they are to be utilized,that’swhyreferredaslocalorinternalvariables. Declaration syntax:-A variable declared inside a function withoutstorage classspecificationbydefaultisanautomaticvariable.However,wemayuse thekeywordautotodeclareitexplicitly. main() { autointage; } Defaultinitialvalue:-Garbagevalue Scope:-createdwhenthefunctioniscalledanddestroyedonexitfrom the function. Life:-tillthecontrolremainswithintheblockinwhichdefined. (ii)Executionerrorandcompilationerror: Errorssuchasmismatchofdatatypesorarrayoutofbounderrorareknownas executionerrorsorruntimeerrors.Theseerrorsaregenerallygoundetectedby thecompilersoprogramswithrun-timeerrorwillrunbutproduceerroneous results.
Compilationerroralsoknownassyntaxerrorsarecausedbyviolationofthe grammarrulesofthelanguage.Thecompilerdetects,isolatetheseerrorsand terminatethesourceprogram afterlistingtheerrors. Q.73 Explaintheuseofstructureswithpointers. (5) Ans: Callowsapointertoastructurevariable.Infactapointertoastructureissimilar toapointertoanyothervariable.Thepointerpointstothefirstelementofthe structure.Astructurecanhavememberswhichpointstoastructurevariableof thesametype;suchstructuresarecalledself-referentialstructuresandwidely usedindynamicdatastructuresliketrees,linkedlistetc.Aprogram showingthe usageofpointerwithstructurevariableislistedbelow: #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(); } Q.74 Canastructurebeusedwithinastructure?Giveappropriateexamplestosupport your answer. (6) Ans: Yes,astructurecanbeusedwithinastructurecallednestingofstructures.For example,insideastructurerectangle,apoint(x,y)needstoberepresented.Sowe canfirstdeclareastructurepointas: structpoint {intx; inty;
}; Wecan now use this definition in defining points in any ofgeometrical figure.Forexample structrectangle {structpointpt; intdiagonal; } Q.75 Whatarethedifferentmodesinwhichafilecanbeopened? (5) Ans: Differentmodesforopeningafilearetabulatedbelow: Modes Operations “r” Opentextfileforreading “w” Opentextfileforwriting,previouscontent,ifany,discarded “a” Openorcreatefileforwritingattheendofthefile “r+” Opentextfileforupdate “w+” Createoropentextfileforupdate,previouscontentlost,ifany “a+” Openorcreatetextfileforupdate,writingattheend. Q.76 WriteaCprogram toinsertanewnodeataspecifiedpositioninalinklist.(8) Ans: ACprogram toinsertanewnodeataspecifiedpositioninalinkedlistislistedbelow: #include<stdio.h> #include<stdlib.h> #defineNULL0 structlinked_list { intnumber; structlinked_list*next; }; typedefstructlinked_listnode; voidmain() { node*head; node*n; voidcreate(node*p); voidprint(node*p); node*insert(node*p); clrscr(); head=(node*)malloc(sizeof(node)); create(head); printf(\"\\n\"); print(head); printf(\"\\n\"); n=insert(head); printf(\"\\n\"); print(n); getch(); } voidcreate(node*list) {
printf(\"Inputanumber\\n\"); printf(\"(type-999toend):\"); scanf(\"%d\",&list->number); if(list->number==-999) list->next=NULL; else { list->next=(node*)malloc(sizeof(node)); create(list->next); } return; } voidprint(node*list) { if(list->next!=NULL) { printf(\"%d-->\",list->number); if(list->next->next==NULL) printf(\"%d\",list->next->number); print(list->next); } return; } node*insert(node*head) { node*find(node*p,inta); node*new,*tmp; node*n1; intkey; intx,i=0; printf(\"\\nValueofnewitem ?\"); scanf(\"%d\",&x); printf(\"\\nValueofkeyindex?(type-999iflast):\"); scanf(\"%d\",&key); tmp=head; while(1) { if(key==0) { new=(node*)malloc(sizeof(node)); new->number=x; new->next=head; head=new; } elseif(i==key-1) { new=(node*)malloc(sizeof(node)); new->number=x; new->next=tmp->next; tmp->next=new; } i++; tmp=tmp->next; if(tmp==NULL) { printf(\"\\nKeyIndexoutofReach\");
break; } } return(head); } node*find(node*list,intkey) { if(list->next->number==key) return(list); else if(list->next->next==NULL) return(NULL); else find(list->next,key); } Q.77 Distinguishbetweenthefunctionsislower()andtolower(). (2) Ans: islower()andtolower(): islower(c)is a charactertesting function defined in ctype.h headerfile.This functiondeterminesifthepassedargument,inthiscasec,islowercase.Itreturns anonzerovalueiftrueotherwise0.tolower(c)isaconversionfunctiondefinedin ctype.hheaderfilethatconvertargumentctolowercase. Q.78WriteaCprogram thatreadstwostringsandcopiesthesmallerstringintothebigger string. (6) Ans: Aprogram tocopysmallerstringtoabiggerstring: #include<stdio.h> #include<conio.h> voidmain() { charstr1[20],str2[20]; intm,i,flag=0,j; clrscr(); printf(\"enterthe1ststring\"); gets(str1); printf(\"enterthe2ndstring\"); gets(str2); if(strlen(str1)<strlen(str2)) { char*str; str=str2; str2=str1; str1=str; } printf(\"entertheindexafterwhichuwanttoinsert2ndstringin1st:\"); scanf(\"%d\",&m); i=0; while(i<=m) { i++;
} j=0; while(str2[j]!='\\0') { str1[i]=str2[j]; i++; j++; if(str1[i]=='\\0') flag=1; } if(flag==1) str1[i]='\\0'; printf(\"%s\",str1); getch(); } Q.79 Arethefollowingstatementsvalid?Justifyyouranswer (i) k=(char*)&m (ii) m=(float*)&p (4) Ans: Typeofm isnotknown.Ifitisoftypeotherthancharandkisapointertochar typethen statementisvalidotherwiseitisinvalid.Similarly,secondstatementisvalid ifm isapointertofloatandpisoftypeotherthanfloatandpointingtomorethantfour consecutivebytes. Q.80 WhyisCstandardlibraryneeded? (4) Ans: CStandardLibrary: Cwouldhavebeenatoughprogramminglanguageinabsenceofthestandardlibrary. ThestandardlibraryinCincludesheaderfilesandstandardfunctionsinthesefiles. Headerfilesarecollectionofmacros,types,functionsandconstants.Anyprogram thatneedsthose functions has to include these headerfiles.Forexample,the standardlibrary functions, included in “stdlib.h” header file, are used for numberconversions,storage allocation and otherfunctions on the same line. Thesefunctionsarecalledutilityfunctions.Cdoesnothaveanybuilt-ininput/output statementsaspartofitssyntax.AllI/Ooperationsarecarriedoutthroughfunction callssuchasprintfandscanf.Therearemanyfunctionsthathavebecomestandard forI/OoperationsinC,collectivelyknownasstandardI/Olibrary“stdio.h”.Becauseof thisstandardinput-outputheaderfile,standardI/O functionscanbeusedonmany machineswithoutanychange. Q.81 Whatarethefunctionsofthefollowingheaderfiles: (i) ctype.h (ii) string.h (4) Ans: (i) ctype.h:Itisaheaderfilethatcontainscharactertestingandconversionfunctions. Forexampleisalpha(c)returnsaninttypedataanddetermineiftheargumentcis alphabetic.Itreturnsnonzerovalueiftrue;0otherwise. toascii(c ):is a conversion function defined in ctype.h thatconverts value of
argumenttoascii. (ii) string.h:Itisalsoastandardheaderfilethatcontainsstringmanipulationfuncions. For example strcmp(c1,c2) function compares two strings c1 and c2lexicographically.Itreturnsanegativevalueifc1<c2;0ifc1andc2areidentical; andapositivevalueifc1>c2. Q.82Explainpointersandstructuresbygivinganexampleofpointertostructure variable?(5) Ans: Wecanhaveapointerpointingtoastructurejustthesamewayapointerpointingtoan int,suchpointersareknownasstructurepointers.Forexampleconsiderthefollowing example: #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(); } Hereptrisastructurepointernotastructurevariableanddotoperatorrequiresa structurevariableonitsleft.C providesarrow operator“->”torefertostructure elements.“ptr=stu”wouldassigntheaddressofthezerothelementofstutoptr.Its memberscanbeaccessedbystatementlike“ptr->name”.Whenthepointerptris incrementedbyone,itismadetopointtothenextrecord,thatisstu[1]andsoon. Q.83Explainvariousstepsforanalysinganalgorithm. (6) Ans: Thevariousstepsinvolvedinanalysisofanalgorithm are: 1.Foranyalgorithm,thefirststepshouldbetoprovethatitalwaysreturnsthe desiredoutputforalllegalinstancesoftheproblem. 2.Secondsteptoanalyzeanalgorithmistodeterminetheamountofresourcessuch astimeandstoragenecessarytoexecuteit.Usuallytheefficiencyorcomplexityof analgorithm isstatedasafunctionrelatingtheinputlengthtothenumberofsteps (timecomplexity)orstoragelocations(spacecomplexity).Intheoreticalanalysisof
algorithmsitiscommontoestimatetheircomplexityinasymptoticsense,i.e.,to estimatethecomplexityfunctionforreasonablylargelengthofinput.BigOnotation, omeganotation and thetanotation are used forthis purpose.There are many techniquesforsolvingaparticularproblem.Wemustanalyzethesealgorithmsand selecttheonewhichissimpletofollow,takeslessexecutiontimeandproduces requiredresults. Q.84 WhatareTranslators?Explainitsvarioustypes. (3) Ans: A program thattranslatesbetween high-levellanguages is usually called a languagetranslator,sourcetosourcetranslator,orlanguageconverter. Thevarioustypesoftranslatorare: Acompilerconvertsthesourceprogram (user-writtenprogram)intoanobjectcode (machine language bychecking the entire program before execution.Ifthe program iserrorfree,objectprogram iscreated and loaded into memoryfor execution.Acompilerproducesanerrorlistoftheprogram inonegoandallhave tobetakencareevenbeforetheexecutionoffirststatementbegin.Ittakesless timeforexecution. An interpreter is also alanguage translator that translates and executes statementsintheprogram onebyone.Itworkononestatementatatimeandif errorfree,executestheinstructionbeforegoingtosecondinstruction.Debugging issimplerininterpreterasitisdoneinstages.Aninterpretertakesmoretime forexecutionofaprogram ascomparedtoacompiler. Q.85 Designanalgorithm togeneratealltheprimesinthefirstnpositiveintegers. (7) Ans: Thisalgorithm willgenerateallprimenumberslessthann. voidprime() { inti,n,j; printf(\"enteranynumber\"); scanf(\"%d\",&n);/*scanthenumber*/ i=2; while(i<n) {j=2; while(j<=i-1) { if(i%j==0) break; else j++; } if(j==i) printf(\"%d\\n\",i); i++; } } Q.86 ExplainvariousclassesofdatatypesofC (4) Ans: FollowingarethemajorclassesofdatatypesinClanguage:
1.Primarydatatypes:Alsoknownasfundamental/basicdatatypes.AllCcompliers supportfourbasicdatatypesnamely:integer(int),character(char),floating(float), anddoubleprecisionfloatingpoint(double).Thenthereareextendeddatatypes suchaslongint,doubleint. 2.Deriveddatatypes:alsoknownassecondaryoruser-defineddatatypes.These datatypes,derivedfrom basicdatatypes,includearrays,pointer,structure,union, enum etc. Q.87 Whatareescapesequencescharacters?Listanysixofthem. (4) Ans: Thecharacterswhichwhenusedwithoutputfunctionslikeprintf(),putc(),put()etc. helps in formatting the outputare known as Escape sequencecharacter.The followingisalistofsixescapesequences. \\n Newline \\t HorizontalTab \\v VerticalTab \\b Backspace \\r CarriageReturn \\\\ Backslash Q.88 WriteaCprogramtocalculatetheaverageofasetofNnumbers. (8) Ans: ACprogram tocalculatetheaverageofasetofnnumbers: #include<stdio.h> #include<conio.h> voidmain() { inti,a[1000],n,sum; floataverage; clrscr(); printf(\"howmanyelementsyouwanttoenter\"); scanf(\"%d\",&n); printf(\"entervalues:\\n\"); for(i=0;i<n;i++) scanf(\"%d\",&a[i]); sum=0; for(i=0;i<n;i++) { sum=sum+a[i]; } printf(\"\\n%d\",sum); average=(float)sum/n; printf(\"\\n%f\",average); getch(); } Q.89 Comparetheuseofswitchstatementwiththeuseofnestedif-elsestatement. (6) Ans: If-else statement:When there are multiple conditionalstatements thatmayall evaluatetotrue,butwewantonlyoneifstatement'sbodytoexecute.Wecanuse
an\"elseif\"statementfollowinganifstatementanditsbody;thatway,ifthefirst statementistrue,the\"elseif\"willbeignored,butiftheifstatementisfalse,itwill thenchecktheconditionfortheelseifstatement.Iftheifstatementwastruethe elsestatementwillnotbechecked.Itispossibletousenumerouselseifstatements toensurethatonlyoneblockisexecuted. #include<stdio.h> voidmain() { intage; printf(\"Pleaseenteryourage\"); scanf(\"%d\",&age); if(age<100){ printf(\"Youareprettyyoung!\\n\");} elseif(age==100){ printf(\"Youareold\\n\"); } else{ printf(\"Youarereallyold\\n\"); } } Switch casestatements are a substitute forlong ifstatements thatcompare avariabletoseveral\"integral\"values(\"integral\"valuesaresimplyvaluesthatcanbe expressedasaninteger,suchasthevalueofachar).Thevalueofthevariablegiven intoswitchiscomparedtothevaluefollowingeachofthecases,andwhenonevalue matchesthevalueofthevariable,thecomputercontinuesexecutingtheprogram from thatpoint.Theconditionofaswitchstatementisavalue.Thecasesaysthatifit hasthevalueofwhateverisafterthatcasethendowhateverfollowsthecolon. Thebreakisusedtobreakoutofthecasestatements.Breakisakeywordthatbreaks outofthecodeblock,usuallysurroundedbybraces,whichitisin.Inthiscase,break preventstheprogram from fallingthroughandexecutingthecodeinalltheothercase statements. #include<stdio.h> #include<conio.h> voidmain() { intflag; printf(\"Enteranyvalue\\n\"); scanf(\"%d\",&flag); switch(flag){ case1: printf(\"Itishotweather!\\n\"); break; case2: printf(\"Itisastormyweather!\\n\"); break; case3: printf(\"Itisastickyweather!\\n\"); break; default: printf(\"Itisapleasantweather!\\n\"); break; } getch(); }
Q.90 Whatdoyoumeanbyunderflowandoverflowofdata. (2) Ans: Underflowandoverflowofdata: Whenthevalueofthevariableiseithertoolongortoosmallforthedatatypeto hold,theproblem ofdataoverflow orunderflow occurs.Thelargestvaluethata variablecanholddependsonthemachine.Sincefloatingpointvaluesarerounded offtothenumberofsignificantdigitsallowed,anoverflow resultsinthelargest possiblerealvaluewhereasanunderflowresultsinzero.Cdoesnotprovideany warningorindicationofintegeroverflow,itsimplygiveerroneousresult. Q.91 WriteaCprogram tomultiplytwomatrices(maximum sizeofthetwomatricesis 20x20each). (8) Ans: ACprogram tomultiplytwomatrices: #include<stdio.h> #include<conio.h> voidmain() { inta[20][20],b[20][20],c[20][20],i,j,k,m,n,p,q; clrscr(); printf(\"enterno.ofrowsandcolumnfor1stmatrix\\n\"); printf(\"no.ofrows\\n\"); scanf(\"%d\",&m); printf(\"no.ofcolumns\"); scanf(\"%d\",&n); printf(\"\\nenterno.ofrowsandcolumnsfor2ndmatrix\"); printf(\"\\nno.ofrows\"); scanf(\"%d\",&p); printf(\"\\nno.ofcolumns\"); scanf(\"%d\",&q); if(n==p) { printf(\"enterelementsformatrixA\"); for(i=0;i<m;i++) { for(j=0;j<n;j++) scanf(\"%d\",&a[i][j]); } printf(\"enterelementsformatrixB\"); for(i=0;i<p;i++) { for(j=0;j<q;j++) scanf(\"%d\",&b[i][j]); } printf(\"\\nMATRIXA:\\n\"); for(i=0;i<m;i++) { for(j=0;j<n;j++) { printf(\"%d\",a[i][j]);
printf(\"\\t\"); } printf(\"\\n\"); } printf(\"\\nMATRIXB:\\n\"); for(i=0;i<p;i++) { for(j=0;j<q;j++) { printf(\"%d\",b[i][j]); printf(\"\\t\"); } printf(\"\\n\"); } printf(\"\\n\"); printf(\"MULTIPLICATION:\\n\"); for(i=0;i<m;i++) { for(j=0;j<q;j++) { for(k=0;k<p;k++) { c[i][j]=c[i][j]+(a[i][k]*b[k][j]); } printf(\"%d\",c[i][j]); c[i][j]=0; printf(\"\\t\"); } printf(\"\\n\"); } } else printf(\"multiplicationisnotpossible\"); getch(); } Q.92 Explain,inbriefthepurposeofthefollowingstringhandlingfunctions: (i)strcat (ii)strcmp (iii)strcpy Usesuitableexamples (6) Ans: (i)strcat()Functionconcatenatestwostringstogetherandhasthefollowingform: strcat(string1,string2); Whenthisfunctionisexecuted,string2isappendedtostring1byremovingthenull characterattheendofstring1. Cpermitsnestingofstrcatfunctionsasstrcat(strcat(string1,string2),string3); (ii)strcmp()isthestringcomparisonfunctiondefinedinstring.hheaderfile.Ithas thefollowingform:. intstrcmp(constchar*s1,constchar*s2);strcmpwillaccepttwostrings.It willreturnaninteger.Thisintegerwilleitherbe: Negativeifs1islessthans2.Zeroifs1ands2areequal.Positiveifs1isgreater thans2.Strcmpperformsacasesensitivecomparison;ifthestringsarethesameexceptfor adifferenceincase,thenthey'recounteredasbeingdifferent.Strcmp also passesthe addressofthecharacterarraytothefunctiontoallowittobeaccessed.
(iii)strcpy()functionisjustlikeastring-assignmentoperatorwhichtakethe followingform:char*strcpy(char*dest,constchar*src);strcpyisshortforstringcopy, whichmeansitcopiestheentirecontentsofsrcintodest.Thecontentsofdestafterstrcpy willbeexactlythesameassrcsuchthatstrcmp(dest,src)willreturn0.srcmaybe acharacterarrayvariableorastringconstant. Q.93 WriteaCprogram toreadalineoftextcontainingaseriesofwordsfrom the terminal. (7) Ans: #include<stdio.h> #include<conio.h> voidmain() { chartext[100],ch; inti=0; clrscr(); printf(\"Entertext.Press<return>attheend\\n\"); do {ch=getchar(); text[i]=ch; i++; }while(ch!='\\n'); i=i-1; text[i]='\\0'; printf(\"Theenteredtextis\"); printf(\"\\n%s\\n\",text); getch(); } Q.94 Explaintheneedforuser-definedfunctions. (3) Ans: Theneedforuser-definedfunction: 1. A programmermayhaveablockofcodethathehasrepeatedfortytimes throughouttheprogram.Afunctiontoexecutethatcodewouldsaveagreatdealof space,anditwouldalsomaketheprogram morereadable. 2. Itiseasytolocateandisolateafaultyfunction.Havingonlyonecopyofthecode makesiteasiertomakechanges. 3.Anotherreasonforfunctionsistobreakdownacomplexprogram intologicalparts. Forexample,takeamenuprogramthatrunscomplexcodewhenamenuchoiceis selected.Theprogram wouldprobablybestbeservedbymakingfunctionsforeach oftheactualmenuchoices,andthenbreakingdownthecomplextasksintosmaller, more manageabletasks,which could be in theirown functions.In this way,a program canbedesignedthatmakessensewhenread.Andhasastructurethatis easiertounderstandquickly.Theworst programsusuallyonlyhavetherequiredfunction,main,andfillitwithpagesof jumbledcode. 4. Afunctionmaybeusedbymanyotherprograms.Aprogrammercanusealready compiledfunctioninsteadofstartingoverfrom scratch. Q.95 Writeaprogram inCtofindthesum ofthefirst100naturalnumbers (8) Sum=1+2+3+…….100 Ans:
Aprogram tofindthesum offirst100naturalnumbers: #include<stdio.h> #include<conio.h> #include<math.h> voidmain() { inti,sum; clrscr(); sum=0; for(i=1;i<=100;i++) { sum=sum+i; } printf(\"%d\\t\",sum); getch(); } Q.96 ListanysixcommonlyfoundprogrammingerrorsinaCprogram. (6) Ans: SixcommonlyfounderrorsinaCprogram are: 1. Missingormisplaced;or},missingreturntypeforaprocedure,missingor duplicatevariabledeclaration. 2. Typemismatchbetweenactualandformalparameters,typemismatchon assignment. 3. Forgettingtheprecedenceofoperators,declarationoffunctionparameters. 4. Outputerrorsmeanstheprogramrunsbutproducesanincorrectresult.This indicatesanerrorinthemeaningoftheprogram. 5. Exceptionsthatincludedivisionbyzero,nullpointerandoutofmemory. 6. Non-terminationmeanstheprogram doesnotterminateasexpected,but continuesrunning\"forever.\" Q.97 DefineastructureinC,whichstoressubject-wisemarksofastudent.Usinga studentarray,writeaCprogram tocalculatethetotalmarksineachsubjectfor allthestudents. (8) Ans: #include<stdio.h> #include<conio.h> structmarks { intsub1,sub2,sub3; inttotal; }; voidmain() { inti,n; structmarksstudent[20]; structmarkstotal; total.sub1=0; total.sub2=0; total.sub3=0; clrscr(); printf(\"enterno.ofstudents\"); scanf(\"%d\",&n);
for(i=0;i<n;i++) { printf(\"\\nentermarks:\"); scanf(\"%d%d%d\",&student[i].sub1,&student[i].sub2,&student[i].sub3); total.sub1=total.sub1+student[i].sub1; total.sub2=total.sub2+student[i].sub2; total.sub3=total.sub1+student[i].sub3; printf(\"\\n\"); } printf(\"SUBJECT TOTAL\\n\"); printf(\"Sub1 %d\",total.sub1); printf(\"\\n\"); printf(\"Sub2 %d\",total.sub2); printf(\"\\n\"); printf(\"Sub3 %d\",total.sub3); printf(\"\\n\"); getch(); } Q.98 (a)Whatisdynamicmemoryallocation?Explainthevariousmemoryallocation functionwithitstask. (3) (b)Whyalinkedlistiscalledadynamicdatastructure?Whataretheadvantagesof usinglinkedlistoverarrays? (6) (c)Whatisamacro?How isitdifferentfrom aCvariablename?Whatarethe advantagesofusingmacrodefinitionsinaprogram. (6) (d)Whatarethedifferentmodesinwhichafilecanbeopened. (4) Ans: (a)Themechanism ofallocatingrequiredamountofmemoryatruntimeiscalled dynamicallocation ofmemory.Sometimesitisrequired to allocatememoryat runtime.Whenwedeclarearrayinanyprogram,thecompilerallocatesmemoryto holdthearray.Now supposethenumbersofitemsarelargerthanthedefinedsize thenitisnotpossibletoholdalltheelementsandifwedefineanarraylargeenough anddatatobestoredisless,inthatcasetheallocatedmemoryiswastedleadingto aneedfordynamicmemoryallocation.Inthismechanism weuseapointervariable towhichmemoryisallocatedatruntime. Thevariousmemoryallocationfunctionsaredescribedbelow: (i)malloc():Itisamemoryallocationfunctionthatallocatesrequestedsizeofbytes andreturnsapointertothefirstbyteoftheallocatedspace.Themallocfunction returnsapointeroftypevoidsowecanassignittoanytypeofpointer.Ittakesthe thefollowingform: ptr=(casttype*)malloc(byte-size); whereptrisapointeroftypecast-type.Forexample,thestatement x=(int*)malloc(10*sizeof(int))meansthatamemoryspaceequivalent to10timesthesizeofanintbyteisreservedandtheaddressofthefirstbyteof memoryallocatedisassignedtothepointerxofinttype. The malloc function can also allocate space forcomplex data typessuch as structures.Forexample: ptr=(structstudent*)malloc(sizeof(structstudent));whereptrisapointeroftype structstudent. (ii)calloc():Itisanothermemoryallocationfunctionthatallocatesspaceforanarray ofelements,initializesthem tozeroandthenreturnsapointertothememory.This functionisnormallyusedforrequestingmemoryspaceatruntime.Whilemalloc allocatesasingleblockofstoragespace,callocallocatesmultipleblockofstorage,
eachofthesamesize,andthensetsallbytestozero.Ittakesthefollowingform: ptr=(casttype*)calloc(n,element-size); Thisstatementallocatescontiguousspacefornblocks,eachofsizeelement-size bytes. (iii)realloc():realloc is a memory allocation function thatmodifies the size ofpreviously allocated space. Sometime it may happen that the allocated memoryspaceislargerthanwhatisrequiredoritislessthanwhatisrequired. Inbothcases,wecanchangethememorysizealreadyallocatedwiththehelpof therealloc function known as reallocation of memory.For example,if the originalallocationisdonebystatement ptr=malloc(size); thenreallocationisdonebythestatement ptr=realloc(ptr,newsize);whichwillallocateanewmemoryspaceofsizenewsizeto thepointervariableptrandreturnsapointertothefirstbyteofthenewmemoryblock (b)Alinkedlistiscalledadynamicdatastructurebecauseitcanbeusedwithadata collectionthatgrowsandshrinksduringprogram execution.Themajoradvantageof usinglinkedlistoverarraysisinimplementinganydatastructurelikestackorqueue. Thearraysarefixedinsizeandsoalotofmemorygetswastedifwedeclareinprior theestimatedsizeandtheusedspaceisless.Alsoitisnottimeefficienttoperform deletion,insertionandupdatingofinformationinanarrayimplementationbecause ofitsfixedlengthmemorystorage.Alinkedlistallocationstorageresultinefficient useofmemoryandcomputertime.Linkedlistsareusefuloverarraysbecause: Theexactamountofmemoryspacerequiredbyaprogram dependsonthedata beingprocessedandsothisrequirementcannotbefoundinadvance.Linkedlist usesrun-timeallocationofmemoryresultinginnowastageofmemoryspace. Someprogramsrequireextensiveuseofdatamanipulationlikeinsertionofnewdata, deletionandmodificationofolddata.Linkedlistsareselfreferentialstructuresso provideanefficienttimecomplexityfortheseoperations. (c)A macro isapre-processordirectivewhichisaprogram thatprocessesthe sourcecodebeforeitpassesthroughthecompiler.Theseareplacedinthesource program beforethemain.Todefineamacro,# definestatementisused.This statement,alsoknownasmacrodefinitiontakesthefollowinggeneralform: #defineidentifierstring Thepre-processorreplaceseveryoccurrenceoftheidentifierinthesourcecodeby thestring.Thepreprocessordirectivedefinitionisnotterminatedbyasemicolon.For example #defineCOUNT100willreplacealloccurrencesofCOUNTwith100inthewhole program beforecompilation. (d)Differentmodesforopeningafilearetabulatedbelow: Modes Operations “r” Opentextfileforreading “w” Opentextfileforwriting,previouscontent,ifany,discarded “a” Openorcreatefileforwritingattheendofthefile “r+” Opentextfileforupdate “w+” Createoropentextfileforupdate,previouscontentlost,ifany “a+” Openorcreatetextfileforupdate,writingattheend. Q.99 Explainthefollowingdirectives: #pragma #error #elif (6) Ans:
(i)‘#elif’is a preprocessordirective thatprovides alternate testfacility. `#elif'standsfor“elseif”.Like`#else',itgoesinthemiddleofaconditional groupandsubdividesit;itdoesnotrequireamatching`#endif'ofitsown. Like`#if',the`#elif'directiveincludesanexpressiontobetested.Thetext followingthe`#elif'isprocessedonlyiftheoriginal`#if'-conditionfailedand the`#elif'conditionsucceeds. Forexample,supposewehavefollowingsetofstatements: #ifX==1 ... #else/*X!=1*/ #ifX==2 ... #else/*X!=2*/ ... #endif/*X!=2*/ #endif/*X!=1*/ Using`#elif',wecanabbreviatethisasfollows: #ifX==1 ... #elifX==2 ... #else/*X!=2andX!=1*/ ... #endif/*X!=2andX!=1*/ (ii) #pragmaisanimplementationorienteddirectivethatspecifiesvarious instructionstobegiventothecompiler. #pragmaname causescompilertoperform“name” (iii) #errorisapreprocessordirectiveusedtoproducediagnosticmessages duringdebugging. #errormessage causesthecompilertodisplaytheerrormessageandterminate processingonencounteringthisdirective. Q.100 Usingrecursion,writeaCprogram toreverseagivennumber. (6) Ans: #include<stdio.h> #include<conio.h> voidmain() { intn,r; clrscr(); printf(\"enteraninteger\"); scanf(\"%d\",&n); rev(n); getch(); } rev(intn) { if(n>0) { printf(\"%d\",n%10); rev(n/10);
} } Q.101 WriteaC functiontodeleteagivenitem fromasinglelinkedlist.Checkfor duplicateelements. (8) Ans: structnode { intdata; structnode*link; }; voiddelete(structnode**q,intnum ) { structnode*old,*temp; temp=*q; while(temp!=NULL) { if(temp->data==num ) { /*ifnodetobedeletedisthefirstnodeinthelinkedlist*/ if(temp==*q) *q=temp->link; /*deletestheintermediatenodesinthelinkedlist*/ else old->link=temp->link; /*freethememoryoccupiedbythenode*/ free(temp); return; } /*traversethelinkedlisttillthelastnodeisreached*/ else { old=temp;/*oldpointstothepreviousnode*/ temp=temp->link;/*gotothenextnode*/ } } printf(\"\\nElement%dnotfound\",num ); } Q.102 Considerthefollowing: P1isanintegerpointer P2isalongintegerpointer P3isacharactertypepointer TheinitialvalueofP1is2800,P2is1411andP3is1201. WhatisthenewvalueofP1afterP1=P1+1,P2afterP2=P2+1and P3afterP3=P3+1; (4) Ans: TheinitialvalueofP1is2800whichisanintegerpointersonewvalueofP1is2802 afterP1=P1+1 TheinitialvalueofP2is1411whichisalongintegerpointersonew valueofP1is 1415afterP2=P2+1becauselongtakes4bytesofmemory.
TheinitialvalueofP3is1201whichisachartypepointersonewvalueofP3is1202 afterP3=P3+1 Q.103 DifferentiatebetweenWhiteBoxandBlackBoxTesting. (4) Ans: Whiteboxtestingstrategydealswith theinternallogicand structureofthe code.White box testing also known as glass,structural,open box orclear boxtesting,testscodewritten,branches,paths,statementsandinternallogic ofthecodeetc. Inordertoimplementwhiteboxtesting,thetesterhastodealwiththecodeand henceisneededtopossessknowledgeofcodingandlogici.e.internalworkingof thecode.Whiteboxtestalsoneedsthetestertolookintothecodeandfindout whichunit/statement/chunkofthecodeismalfunctioning.Whiteboxtestingis applicableatunit,integrationandsystem levelhoweveritismainlydoneatunit level. BlackboxtestingBlack-boxtestdesigntreatsthesystem asa\"black-box\",soit doesn'texplicitlyuseknowledgeoftheinternalstructure.Ittakesanexternal perspectiveofthetestobjecttoderivetestcases.Thesetestscanbefunctional ornon-functional,thoughusuallyfunctional.Thetestdesignerselectsvalidand invalidinputanddeterminesthecorrectoutput.Thereisnoknowledgeofthetest object'sinternalstructure. This method oftestdesign is applicable to alllevels ofsoftware testing: unit,integration,functionaltesting,systemandacceptance. Q.104 WriteaCprogram usingpointerstocomputethesum ofallelementsstoredin anarray. (8) Ans: voidmain() { inti,*p,s; staticinta[10]={10,20,30,40,50,60,70,80,90,100}; clrscr(); i=0; p=a; s=0; while(i<10) { s=s+*p; i++; p++; } printf(\"sum=%d\",s); getch(); } Q.105 WriteaCprogram tocreateafilecontainsaseriesofintegernumbersandthen readsallnumbersofthisfileandwritealloddnumberstootherfilecalledodd andwriteallevennumberstoafilecalledeven. (8) Ans: #include<stdio.h> #include<conio.h> voidmain()
{ FILE*f1,*f2,*f3; inti,j; printf(\"Enterthedata\\n\"); f1=fopen(\"file1\",\"w\"); for(i=0;i<=10;i++) {scanf(\"%d\",&j); if(j==-1)break; putw(j,f1); } fclose(f1); f1=fopen(\"file1\",\"r\"); f2=fopen(\"od\",\"w\"); f3=fopen(\"ev\",\"w\"); while((j=getw(f1))!=EOF) {if(j%2==0) putw(j,f3); else putw(j,f2); } fclose(f1); fclose(f2); fclose(f3); f2=fopen(\"od\",\"r\"); f3=fopen(\"ev\",\"r\"); printf(\"\\nContentsofoddfile\\n\"); while((j=getw(f2))!=EOF) printf(\"%4d\",j); printf(\"\\nContentsofevenfile\\n\"); while((j=getw(f3))!=EOF) printf(\"%4d\",j); fclose(f2); fclose(f3); getch(); } Q.106 Whatisstructuredprogramming?Explainitsadvantages. (8) Ans: StructuredProgramming:meansthecollectionofprinciplesandpracticesthatare directed toward developing correctprogramswhich are easyto maintain and understand.Astructuredprogram ischaracterizedbyclarityandsimplicityinits logicalflow. TheThreeimportantconstructsuponwhichstructuredprogrammingisbuiltare: · Sequence-Stepsareperformedoneaftertheother. · Selection-Logicisusedtodeterminetheexecutionofasequenceofsteps. Forexample,if-then-elseconstruct. · Iteration-Asetofactionsarerepeateduntilacertainconditionismet.For examplewhileconstruct. The various advantages of structuredprogramming are:1.Complexity of program reduces. 2.Easymaintenance. 3.Simplifiedunderstanding. 4.Reusabilityofcodeincreases.
5.Testinganddebuggingbecomeeasier. Q.107 Whataretheessentialfeaturesofanalgorithm?Writeanalgorithm toobtain H.C.F.oftwogivenpositiveintegers. (8) Ans: Essentialfeaturesofanalgorithm: 1.Input:Thealgorithm shouldtakezeroormoreinput.
2.Output:Thealgorithm shouldproduceoneormoreoutputs. 3.Definiteness:Eachandeverystepofalgorithm shouldbedefinedunambiguously. 4.Effectiveness:Ahumanshouldbeabletocalculatethevaluesinvolvedintheprocedureof thealgorithm usingpaperandpencil. 5.Termination:Analgorithm mustterminateafterafinitenumberofsteps. Writingalgorithmsisanartsothelanguageusedtowritealgorithmsshouldbe simpleand precise.Each and every step ofthe algorithm should be clear andunambiguous and should notconvey more than one meaning to the programmer. AClanguagealgorithm toobtainH.C.F.oftwogivenpositiveintegersislisted below: voidhcf() { inta,b,r,h,k,c; clrscr(); printf(\"entertwonumbers\"); scanf(\"%d%d\",&a,&b); h=a; k=b; while(r!=0) { r=a%b; a=b; b=r; } printf(\"H.C.F.of%dand%d=%d\",h,k,a); } Q.108 Howdoyoucalculatethecomplexityofsortingalgorithms?Findthecomplexity ofInsertionsortandBubbleSort. (8) Ans: Thecomplexityofsortingalgorithmsdependsontheinput:sortingathousand numberstakeslongerthansortingthreenumbers.Thebestnotionofinputsize dependsontheproblem beingstudied.Forsortingalgorithms,themostnatural measureisthenumberofitemsintheinputthatisarraysizen.Westartby associating time “cost”ofeach statementand the numberoftimeseach statementisexecutedassumingthatcommentsarenotexecutablestatements, andsodonottakeanytime. ComplexityofBubblesort:O(n2) ComplexityofInsertionsort:O(n2) Q.109 (a)WriteaCprogram tocompareandcopythestructurevariableswithexample. (8) (b)WriteaCprogram usingpointerstodeterminethelengthofacharacterstring. (8) (c)Comparethe2 constructsArraysofstructuresand Arrayswithinstructure. Explainwiththehelpofexamples. (8) Ans: (a)ACprogram tocompareandcopythestructurevariablesislistedbelow:
#include<stdio.h> #include<conio.h> structstudent { charname[10]; intmarks; }; voidmain() { inti,j; staticstructstudentstu1={\"Simmi\",78}; staticstructstudentstu2={\"Ruci\",90}; staticstructstudentstu3={\"Seema\",95}; clrscr(); stu1=stu3; if((stu1.marks==stu3.marks)) { printf(\"Student1issameasstudent3\\n\"); printf(\"%s\",stu1.name); printf(\"\\t\"); printf(\"%d\",stu3.marks); printf(\"\\n\"); } else printf(\"\\nStudentsaredifferent\\n\"); getch(); } (b)ACprogram todeterminethelengthofacharacterstring: #include<stdio.h> #include<conio.h> #include<process.h> voidmain() {char*a,*ptr; inti; clrscr(); printf(\"enterthestring\"); gets(a); ptr=a; while(*ptr!='\\0') {ptr++; } i=ptr-a; printf(\"length=%d\",i); getch(); } (c)Arrayofstructuresandarrayswithinstructures: Structuresvariablesarejustlikeordinaryvariablessowecancreateanarrayof structures.Howeverarithmetic operations cannotbeperformed on structure variables.Forexample,wecancreateanarrayofstructurestudentasshown below: structstudent { charname[30]; intmarks; }; structstudentlist[4]={{“aaa”,90},{“bbb”,80},{“ccc”,70}};declareandinitializeanarray
of structurestudent. AStructureisaheterogeneouscollectionofvariablesgroupedunderasinglelogical entity.Anarrayisalsoause-defineddatatypeandhencecanbeusedinsidea structurejustlikeanordinaryvariable.Asintheaboveexample,nameisachar arraywithinthestructurestudent. Q.110 Describetheoutputthatwillbegeneratedbythefollowing‘C’program. (4) #include<stdio.h> main() { inti=0,x=0; while(i<20) {if(i%5==0) {x+=i; printf(\"%d\",x); } ++i; } printf(“\\nx=%d”,x); } Ans: TheoutputgeneratedbygivenCprogram is: 051530 x=30 initiallyi=0<20,(i%5==0)istruesox=x+i=0+0=0,iisincrementedto2,againthenext whileloop,howevercondition(i%5==0)isfalsesoiincrementedandsoontilli=5. Ati=5,(i%5==0)istruesox=x+i=0+5=5,iisincrementedto6,againthenextwhile loop,howevercondition(i%5==0)isfalsesoiincrementedandsoontilli=10. Ati=10,(i%5==0)istruesox=x+i=5+10=15,iisincrementedto11,againthenext whileloop,howevercondition(i%5==0)isfalsesoiincrementedandsoontilli=15. Ati=15,(i%5==0)istruesox=x+i=15+15=30,iisincrementedto16,againthenext whileloop,howevercondition(i%5==0)isfalsesoiincrementedandoutofwhile loopati=20. Outerblock,itisprintingthevalueofxwhichis30. Q.111 Writeacompleteprogram tocreateasinglylinkedlist.Writefunctionstodothe followingoperations (i)Countthenumberofnodes (ii)Addanewnodeattheend (iii)Reversethelist. (10) Ans: Acompleteprogram tocreatealinkedlist,countingnumberofnodes,addingnew nodeattheendandreversingthelistisasfollows: #include<stdio.h> #include<conio.h> #include<alloc.h> /*structurecontainingadatapartandlinkpart*/ structnode { intdata;
structnode*link; }; voidappend(structnode**,int); voidreverse(structnode**); voiddisplay(structnode*); intcount(structnode*); voidmain() { structnode*p; intn; p=NULL;/*emptylinkedlist*/ append(&p,14); append(&p,30); append(&p,25); append(&p,42); append(&p,17); clrscr(); display(p); printf(\"\\nNo.ofelementsinthelinkedlist=%d\",count(p)); printf(\"\\nEntertheelementyouwanttoinsert\"); scanf(\"%d\",&n); append(&p,n); display(p); printf(\"\\nNo.ofelementsinthelinkedlist=%d\",count(p)); reverse(&p); printf(\"\\nElementsafterreversingthelinkedlist\\n\"); display(p); } /*addsanodeattheendofalinkedlist*/ voidappend(structnode**q,intnum ) { structnode*temp,*r; if(*q==NULL)/*ifthelistisempty,createfirstnode*/ { temp=malloc(sizeof(structnode)); temp->data=num ; temp->link=NULL; *q=temp; } else { temp=*q; /*gotolastnode*/ while(temp->link!=NULL) temp=temp->link; /*addnodeattheend*/ r=malloc(sizeof(structnode)); r->data=num ; r->link=NULL; temp->link=r; } } voidreverse(structnode**x) { structnode*q,*r,*s; q=*x;
r=NULL; /*traversetheentirelinkedlist*/ while(q!=NULL) { s=r; r=q; q=q->link; r->link=s; } *x=r; } intcount(structnode*list) { if(list->next==NULL) return(0); else return(1+count(list->next)); } /*displaysthecontentsofthelinkedlist*/ voiddisplay(structnode*q) { printf(\"\\n\"); /*traversetheentirelinkedlist*/ while(q!=NULL) { printf(\"%d\",q->data); q=q->link; } } Q.112 Whatisrecursion?Writearecursiveprogram toreverseastring. (8) Ans: Recursionisaspecialcaseoffunctioncallwhereafunctioncallsitself.Theseare very usefulin the situations where solution can be expressedin terms of successivelyapplyingsameoperationtothesubsetsoftheproblem.Forexample, arecursivefunctiontocalculatefactorialofanumbernisgivenbelow: fact(intn) { intfactorial; if(n==1||n==0) return(1); else factorial=n*fact(n-1); return(factorial); } Assumen=4,wecallfact(4) Sincen≠1or0,factorial=n*fact(n-1) Factorial=4*fact(3) (againcallfactfunctionwithn=3) =4*3*fact(2) (againcallfactfunctionwithn=2) =4*3*2*fact(1) (againcallfactfunctionwithn=1) =4*3*2*1 (terminatingcondition) =24 We should always have a terminating condition with a recursivefunction call
otherwisefunctionwillneverreturn. Arecursiveprogram toreverseastringis: #include<stdio.h> #include<conio.h> voidmain() { charstr[100]; clrscr(); printf(\"enterastring\"); gets(str); printf(\"reverseofstringis:\\n\"); rev(str); getch(); } rev(char*string) { if(*string) { rev(string+1); putchar(*string); } } Q.113 Distinguishbetweenthefollowing: (8) (i)Automaticandstaticvariables (ii)Globalandlocalvariables. Ans: (i)AutomaticandStaticvariables: Automaticvariables:Thefeaturesareasfollows Declarationplace:-declaredinsideafunctioninwhichtheyaretobeutilized,that’s whyreferredaslocalorinternalvariables. Declaration syntax:-A variable declared inside a function without storage classspecification bydefaultis an automatic variable.However,we mayuse thekeywordautotodeclareitexplicitly. main() { autointage; } Defaultinitialvalue:-Garbagevalue Scope:-createdwhenthefunctioniscalledanddestroyedonexitfrom thefunction. Life:-tillthecontrolremainswithintheblockinwhichdefined. Staticvariables:Thefeaturesareasfollows Declarationplace:-maybedeclaredinternallyorexternally. Declarationsyntax:-weusethekeywordstatictodeclareastaticvariable. Staticintage; Defaultinitialvalue:-Zero Scope:-incaseofinternalstaticvariable,thescopeislocaltothefunctioninwhich definedwhilescopeofexternalstaticvariableistoallthefunctionsdefinedinthe program. Life:-valueofvariablepersistsbetweendifferentfunctioncalls. (ii)GlobalandLocalVariables Globalvariables:Thefeaturesareasfollows Declaredoutsideofallfunctionsorbeforemain.
Thesecanbeusedinallthefunctionsintheprogram. Itneednotbedeclaredinotherfunctions. Aglobalvariableisalsoknownasanexternalvariable. Localvariables:Thefeaturesareasfollows Declaredinsideafunctionwhereitistobeused. Thesearenotknowntootherfunctionintheprogram. Thesevariablesarevisibleandmeaningfulinsidethefunctionsinwhichtheyare declared. Forexample: #include<stdio.h> intm; voidmain() {inti; ….. ….. Fun1(); } Fun1() {intj; …. ….. } Herem isaglobalvariable,iislocalvariablelocaltomain()andjislocalvariable localtoFun1(). Q.114 Whatwouldbetheoutputoftheprogram givenbelow?(6) typedefstructsoldier{ char*name; char*rank; intserial_number;}SOLDIER; SOLDIERsoldier1,soldier2,soldier3,*ptr; ptr=&soldier3; soldier3.name=“AnandMohanti”; printf(“\\n%s”,(*ptr).name); printf(“\\n%c”,*ptr->name); printf(“\\n%c”,*soldier3.name); printf(“\\n%c”,*(ptr->name+4)); Ans: Outputoftheprogram wouldbe: AnandMohanti A A d ptr is pointing to address of soldier3 so (*ptr).name would printthe soldier3.namethatisAnandMohanti *ptr->namewouldprintfirstcharacterofsoldier3namesoprinted‘A’. Similarly3rdline. ptr->namemeansfirstcharofnamesoptr->name+4pointsto4thlocationfrom beginningsothisstatementwillprintd.
Search
Read the Text Version
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226
- 227
- 228
- 229