part i · web viewq1.write a user defined function dispten(int a[][4],int n,int m) in c++ to find...
TRANSCRIPT
S P E C I A L S T U D YS P E C I A L S T U D Y M O D U L EM O D U L E
COMPUTERSCIENCEXII
Manik Kumar PGT (Comp. Sc.)
K V Sonpur
How to use Study Material: I
twillbemuchbeneficialtothosestudentswhoneedspecialcareandattention.Iamsure,thoroughstudy and practicingsimilar patterns of questions ofthismaterialwillhelpsuchstudentssecure60%andabove.
However it isnot 100%substitutefor Textbook . Minimu
masetoffivequestionswithanswersfromeachquestionsoftheBoardPatternQuestionPaperareincluded,keepinginmindtheneedsandinterestoftargetgroup.
Conceptsineveryunithavebeenexplainedusingnotes/solutionstoquestions/guidelinesinasimplelanguage.
Practiceandpeergroupdiscussiononthisstudymaterialwilldefinitelyimprovetheconfidencelevelofthestudentswhentheysolvethequestions.
Nowyouarewelcometothe...content...
Weightagetodifferenttopics/contentunitsS.No
UNIT VSA1 Mark
SAI2Marks
SA II3Marks
LA4Marks
Total
1 Review ofC++ coveredinClassXI 1(1) 8(4) 3(1) 12(6)2 ObjectOrientedProgramminginC++
2(1) 4(1) 6(2)a)IntroductiontoOOP using C++b)Constructor&Destructor 2(1) 2(1)c)Inheritance 4(1) 4(1)
3 Data Structure &Pointers
2(1)3(1)
4(1)
3(1)a)Address Calculationb)StaticAllocation ofObjects 3(1) 5(2)c)DynamicAllocationofObjects 4(1)d)Infix&Postfix Expressions 2(1) 2(1)
4 DataFileHandlinginC++a) FundamentalsofFileHandlingb) TextFilec) BinaryFiles
1(1)2(1)
3(1)
1(1)2(1)3(1)
5 DatabasesandSQL2(1)
4(1)2(1)a)Database Concepts
b)StructuredQueryLanguage 2(1) 6(2)6 BooleanAlgebra
1(1)2(1)
3(1)
2(1)a)IntroductiontoBooleanAlgebra &Lawsb)SOP&POS 1(1)c)KarnaughMap 3(1)d)BasicLogicGates 2(1) 2(1)
7 Communication&OpenSource Concepts2(2)
4(1)2(2)a)IntroductiontoNetworking
b)Media,Devices,Topologies&Protocols 4(1)c)Security 2(2) 2(2)d)Webservers 1(1) 1(1)e)OpenSourceTerminologies 1(1) 1(1)
TOTAL 9(9) 26(13) 15(5) 20(5) 70(32)
Review of C++covered in Class XI
Questions based on HeaderFilesVery Short AnswerQuestions (1 mark)
Q1.Writethe namesofthe headerfilestowhichthefollowingbelong:
math.hQ2. Nametheheaderfile(s)thatshallbeneededforsuccessfulcompilationofthefollowingC++
code:voidmain(){
charsubject[30];strcpy(subject,”ComputerScience”);puts(subject);
}Ans: string.h
stdio.h
Q3. Nametheheaderfile(s)thatshallbeneededforsuccessfulcompilationofthefollowingC++code:voidmain(){
charname[20];gets(name);cout<<setw(20)<<name;
}Ans: iomanip.h
stdio.h
Q4.Nametheheaderfile(s)thatshallbeneededforsuccessfulcompilationofthefollowingC++code:voidmain(){
}Ans: ctype.h
stdio.h
chara,b;a=getchar();b= toupper(a)cout<<”\nThe uppercasecharacter of“<<a<<”is“<<b;
Note:Marksarenottobedeductedifanyadditionalheaderfileismentioned.Butthese headerfilesmustbewritten.
(i)isdigit()(vi)setw()
(ii)strcmp()(vii)exit()
(iii)fabs()(viii)tolower()
(iv)gets()(ix)ceil()
(v)eof()(x)feof()
(xi)strupr()(xvi)strstr()
(xii)atoi()(xvii)put()
(xiii)setprecision()(xviii)puts()
(xiv)floor()(xix)exp()
(xv)remove()(xx)free()
(xxi)fwrite() (xxii)write() (xxiii) setiosflags() (xxiv)sin() (xxv)abs()
Ans: (i)ctype.h(vi)iomanip.h
(ii)string.h(vii)process.h
(iii)math.h(viii)ctype.h
(iv)stdio.h(ix)math.h
(v)iostream.h(x)stdio.h
(xi)string.h(xvi)string.h
(xii)stdlib.h(xvii)iostream.h
(xiii)iomanip.h(xviii)stdio.h
(xiv)math.h(xix)math.h
(xv)stdio.h(xx)stdlib.h
(xxi)stdio.h (xxii)iostream.h (xxiii)iomanip.h (xxiv)math.h (xxv)stdlib.h/
Concept Questionsbased on C++Review (2 marks)
Q1. Whatisthedifference betweena keywordandanidentifierinC++? Giveexamplesof both.Ans:
Keywordisaspecialwordthathasaspecialmeaningandpurpose.Keywordsarereservedandarefew.Forexample:goto,for,while,if,elseetc.Identifiersaretheuser-definednamegiventoapartofaprogram.Identifiersarenotreserved.Itshouldbethename ofanykeyword.Forexample:name,stud, _myfile,opetc.
Q2.Whatisa referencevariable?Whatisitsusage?Ans:
Areferencevariableisanaliasnameforapreviouslydefinedvariable.Theusageofitisthatthesamedataobjectcanbereferredtobytwonamesandthesenamescanbeusedinterchangeably.
Q3. Writetwoadvantagesofusinginclude compilerdirectives.Ans:(i)The#includecompilerdirectiveletsusincludedesiredheaderfilesinourprogramwhichenables us
workwithalldeclaration/definitions/macrosinsidetheincludedheaderfile(s).(ii) Itsupportsmodularity.
Q4. Differentiate betweenaLogical ErrorandSyntaxError.Alsogivesuitableexamplesofeachin C++.
Ans: LogicalError:Error occurredduetoincorrectlogicappliedbythe programmer.SyntaxError:Erroroccurreddueto notfollowingthe proper grammar/syntaxofthelanguageOR the erroroccurredduetoviolating rules ofthe programminglanguageExample://Programtofindarea andperimeterofrectanglevoidmain(){
intA=10,B=20,AR, P;AR=2*(A*B); //LogicalError–WrongFormulaP=2*(A+B);cout<<A<<P>>endl; //SyntaxError–Useof>>withcout
}
Q5.Whatisthedifference betweenGlobalVariableandLocalVariable?Ans:
#include<iostream.h>floatNUM=900; //NUMisa globalvariablevoidLOCAL(intT){
intTotal=0;
//Totalisalocalvariablefor(intI=0;I<T;I++)Total+=I
;cout<<NUM+Total;}voidmain(){
Global Variable LocalVariable I
tisavariable,whichisdeclaredoutsideallthefunctions
Itisaccessiblethroughoutthepro
Itisavariable,whichisdeclaredwithinafunctionorwithinacompoundstatement
Itisaccessible onl
LOCAL(45); }
Q6.Whatisthedifference betweenObjectOrientedProgramming andProceduralProgramming?Ans:ObjectOrientedProgramming ProceduralProgramming EmphasisonData FollowsBottom-
Upapproachinprogramdesign Data hidingfeature
preventsaccidentalchangeindata Featureslike data
encapsulation
Emphasisondoingthings (functions) FollowsTop-
downapproachinprogramdesign
Presence ofGlobalvariablesincreasechancesofaccidentalchangeindataQ7. DifferentiatebetweenaCallbyValueandCallbyReference,givingsuitableexamplesofeach?
Ans:CallbyValue CallbyReference Th
ecalledfunctioncreatesitsowncopiesofthe original valuessent toit.
Anychangesthataremadeinthefunctionrun,changesinthe
Thecalledfunctionaccessesandworkswiththe originalvalues usingtheirreferences.
Anychangesthatoccur inthefunction run,changesinthe originalvaluesarereflected.
void change(intb){
b=10;}voidmain(){
inta=5;cout<<”\na=“<<a;change(a);cout<<”\na=“<<a;
}Outputwillbe:
voidchange(int&b){
b=10;}voidmain(){
inta=5;cout<<”\na=“<<a;change(a);cout<<”\na=“<<a;
}Outputwillbe:
Q8.Whatisaparameter?Differentiatebetweenanactualandaformalparameterwithanexample?Ans:Parameteristhevariable/
valuepassedtoafunctionorthevariablethatisusedastheincomingvaluesinafunction.Thevariables/valuespassedtoafunctionarecalledactualparameters.Thevariablesthatareusedastheincomingvaluesinafunctionarecalledformalparameters.For Example:
void change(intb) //bistheformalparameter{
b=10;}voidmain(){
inta=5;change(a);
//aistheactualparametercout<<”\na=“<<a;
}
Q9. Enlistanyfourjump statementswith theiruses.Ans:(i)goto: A gotostatementcantransferthe programcontrolanywhereintheprogram.
(ii) break:Abreakstatementenablesaprogramtoterminateoftheloop/block,skipping anycode inbetween.
(iii) continue:Abreakstatementenablesaprogramtoforcethenextiterationtotakeplace,skipping anycode inbetween.
(iv) return:Areturnstatementisusedtoreturnfromafunction.
Q10.How arethefollowing relatedtoone another?(i) arrayandstructure (ii)structure andclass
Ans:(i)Arrayisagroupofitemsofthesamedatatypeswhereasstructurebringstogetheragroupofrelated dataitems ofanydatatypes.
(ii) Structureisactuallyaclass(inC++)declaredwithkeywordstruct.Bydefault,allmembersarepublicinastructure;ontheotherhandallmembersareprivatebydefaultinaclass.
Questions based on ProgramErrors (2marks)Note
:Errorsareexplainedinthesolutions.Whilesolvingsuchtypeofquestion,astudentshouldcarefullygothroughcorrectnessofeachstatementandthelogicofthewholeprogram.Students areadvised topracticevariousquestionstodevelop theskilloffinding theerrors.
Q1. Rewrite thefollowing programafterremoving thesyntactical errors(ifany).Underlineeachcorrection.#include<iostream.h>intfunc(inty=10,int&x){
if(x%y=0)return++x;elsereturny--;}voidmain(){
intp=20, q=23;r= func(p,q);cout>>p>>q>>r;
}Ans: #include<iostream.h>
intfunc(int y , int&x) // violating theruleofDefaultargument{
if(x%y= = 0)return++x;elsereturny--; //==relationaloperator}voidmain(){
intp=20, q=23;intr= func(p,q); //rshouldbedeclaredcout << p << q << r ; //<<operator forcout
}Q2..Rewritethefollowingprogramafterremovingthesyntacticalerrors(ifany).Underlineeachcorrection.
#include<iostream.h>voidmain(){
intX[]={60,50,30,40},Y; count=4;cin>>Y;for(i=count-1;i>=0;i--)switch(i){
case1;
case2:cout<<Y *X;break;case3:cout<<Y+Y;
}}
Ans:#include<iostream.h>voidmain(){
intX[]={60,50,30,40},Y,count=4;/
/multipledeclarationseparatedbycommacin>>Y;for(int i =count-1; i>=0;i--) //ishouldbe declaredswitch(i){
case 1:; /
/caseshouldfollowby:case2:cout<<Y*X[i];break; //LvaluerequiredforXcase3:cout<<Y+ Y;
}}
Q4. Rewritethefollowingprogramafterremovingthesyntacticalerrors(ifany).Underlineeachcorrection.#include<iostream.h>str
uctPixels{intColor,Style;}voidShowPoint(PixelsP){cout<<P.Color,P.Style<<endl;}voidmain(){
PixelsPoint1=(5,3);ShowPoint(Point1);PixelsPoint2=Point1;Color.Point1+=2;ShowPoint(Point2);
}Ans:
#include<iostream.h>structPixels{ intColor,Style;}; //Definition ofstructurePixelsmustbeendedwith;voidShowPoint(PixelsP){ cout<<P.Color<<P.Style<<endl;} // In cascadingofcout,<<tobeusedvoidmain(){
PixelsPoint1={5,3}; //{}tobeusedtoinitialiseofmembersofthe objectShowPoint(Point1);PixelsPoint2=Point1;Point1.Color+=2;
//membertofollowedbytheobjectusing.operatorShowPoint(Point2);
}Question
s based on Finding Outputsusing random() ShortAnswerQuestions(2ma
rks)Note:random(n)generatesthe numbersrandomlyfrom0 ton–1.Forexample:random(20)generates
randomlyfrom0to19.Explanationsaregivenattheendofeachsolution.
Q1. Inthefollowingprogram,ifthevalueofNgivenbytheuseris50,whatmaximumandminimum values the programcouldpossiblydisplay?#include<iostream.h>#include<stdlib.h>voidmain(){
intN,Guessme;randomize();cin>>N;Guessme=random(N)+5;cout<<Guessme<<endl;
}
Ans: Minimum: 5 Maximum:54Explanation:Sincerandom(50)givesanumberrandomlyfrom0to49.Ifitreturns0i.e.minimumforrandom(50),theminimumvalueforGuessmewillbe0+5=5.Ifitreturns49i.e.maximumforrandom(50),themaximumvalueforGuessmewillbe49+5=54.
Q2.Studythefollowingprogramandselect the possibleoutputfrom it:#include<iostream.h>#include<stdlib.h>constintMax=3;voidmain(){
randomize();intNumber;Number=50+random(Max);for(intP=Number; P>=50;P--)
cout<<P<<”#”;cout<<endl;
}(i) 53#52#51#50#(ii) 50#51#52#(iii) 50#51#(iv)51#50#
Ans:51#50#
Q3.Inthefollowingprogram,ifthevalueofNgivenbytheuseris20,whatmaximumandminimum values the programcouldpossiblydisplay?#include<iostream.h>#include<stdlib.h>voidmain(){
intN,Guessnum;randomize();cin>>N;
Explanation:Sincerandom(3)givesanumberrandomlyfrom0to2.So,thevaluesofNumberrangesfrom50(50+0)to52(50+2)andtheNumbershouldbedisplayedindescendingorderaccordingtotheprogramme.53isnotpossible,sothe answeris(iv).
Guessnum=random(N – 10)+10;cout<<Guessnum<<endl;
}Ans: MaximumValue:19 Minimum Value:10
Q4.
Inthefollowingprogram,ifthevalueofGuessenteredbytheuseris65,whatwillbetheexpectedoutput(s) fromthefollowing options(i),(ii),(iii)and(iv)?#include<iostream.h>#include<stdlib.h>voidmain(){
intGuess;randomize();cin>>Guess;for(intI=1;I<=4;I++){
New=Guess+random(I);cout<<(char)New;
}}
(i) ABBC(ii) ACBA(iii) BCDA(iv) CAB
DAns:(i)ABBC
Questions based on Finding Outputs ShortAnswerQuestions(2marks)
Note:Whilesolvingsuchtypeofquestion,astudentshouldcarefullygothroughthelogicofthewholeprogramandconceptsusedinit.Variouspatternsofquestionsaregivenbelow.Students areadvised topracticevariousquestionstodevelop theskilloffinding theoutput.
Explanation:InfirstiterationI=1andrandom(I)gives 0.So,New =65+0,henceoutputisA.InfirstiterationI=1,So,New=65+0,henceoutputisA.InseconditerationI=2andrandom(I)gives0or1.So,New=65or66,henceoutputisAorB.InthirditerationI=3andrandom(I)gives0to2.So,New=65or66or67,henceoutputisAorBorC.InfourthiterationI=4andrandom(I)gives0to3.So,New =65or66or67or68,henceoutputis AorBorCorD.Option(i)satisfiesallthe above only,soitisthe answer.
Q1. Findthe output ofthe
followingprogram:#include<iostream.h>structGame{
charMagic[20];intScore;};voidmain(){
Game M={“Tiger”,500};char*Choice;Choice=M.Magic;Choice[4]=’P’;Choice[2]=’L’;M.Score+=50;cout<<M.Magic<<M.Score<<endl;GameN=M;N.Magic[0]=’A’;N.Magic[3]=’J’;N.Score-=120;cout<<N.Magic<<N.Score<<endl;
}Ans: TiLeP550Q2. Find the output ofthe
followingprogram:#include<iostream.h>voidmain(){
intNumbers[]={2,4,8,10};int*ptr =Numbers;for(intC =0;C<3;C++){
cout<<*ptr<<“@”;ptr++;
}cout<<endl;for(C =0;C<4;C++){
(*ptr)*=2;--ptr;
}for(C =0;C<4;C++)
cout<<Numbers[C]<< “#”;cout<<endl;
}Ans : 2@4@8@
4#8#16#20#
Q3. Find the output ofthe followingprogram:
#include<iostream.h>voidfun(intp, int*q){
p= *(q)+= 2;}voidmain(){
intx,b=5, a[2]={10,20};for(x =1;x <3; x++)
{fun(a[x –1],&b);
cout<<“\n”<<a[x -1]<<”:“<<b;}
}
Ans: 10:720:9
Q4.Find the outputofthe followingprogram:#include <iostream.h>voidmain(){
longNUM=98534210;intf=0,s=0;do{
intrem= NUM %10;if(rem%2== 0)
f+=rem;else
s += rem;NUM /=10;
}while(NUM >0);cout<<“\n”<<f<<”–“<<s<<“= ”<<f– s;
}
Ans : 14 – 18= –4
Q5. Find the output ofthe followingprogram:
#include<iostream.h>inta=10;voidmain(){
voiddemo(int&,int, int*);inta=20,b=5;demo(::a,a,&b);cout<<”\n”<<::a<<”*”<<a<<”*”<<b;
}void demo(int&x,inty,int*z){
a=a+x; y=y*a;*z=a+y;cout<<”\n”<<x<<”*”<<y<<”*”<<*z;
}Ans: 20*400*420
20*20*420Q6.Find the outputofthe followingprogram:#include <iostream.h>#include<ctype.h>voidmain(){
char*name= "ThEbEStmeNwIN";for(inti=0;name[i]!='\0' ;i++){
if(islower(name[i]) )name[i]= toupper(name[i]);
elseif
(isupper(name[i]))if(i%2== 0)
name[i]––;else
name[i]= tolower(name[i–1]);}cout<<name;
Questions based on Finding Outputs Short Answer Questions (3 marks)
Q1. Findthe outputofthe followingprogram:#include<iostream.h>#include<string.h>structKEY{
charword[10];intcount;
};
voidchangekeyword(KEYsomekey);voidmain(){
KEYaKEY;strcpy(aKEY.word,“#define”);aKEY.count=10;cout<<aKEY.word<<“\t”<<aKEY.count<< “\n”;changekeyword(aKEY);cout<<aKEY.word<<“\t”<<aKEY.count<< “\n”;
}voidchangekeyword(KEYsomekey){
strcpy(somekey.word,“const”);somekey.count+= 1;cout<<somekey.word<<“\t”<<somekey.count<<“\n”;
}
Ans : #define 10#const11#define 10
Q2. Findthe outputofthefollowingprogram:#include<iostream.h>intmodify(inttemp=2){
if(temp %3== 0)temp =temp +1;
elsetemp =temp +3;
returntemp;}void doupdation(intm,int&n){
staticinti;i++;m=n+i;if(n>10)
n=modify();else
n=modify(n);cout<<m<<"; "<<n<<endl;
}voidmain(){
intx =8,y=20;doupdation(x,y);cout<<x<<";"<<y<<endl;doupdation(y,x);cout<<x<<";"<<y<<endl;doupdation(y,x);cout<<x<<";"<<y<<endl;
}Ans: 21;5
8;510;11
Q3. Find the output of thefollowingprogram:
#include <iostream.h>voidchang (int&x,inty){
inttemp;temp=x;x=y;y=temp;cout<<”\n”<<x<<” :“<<y;
}voidmain(){
inta=10,b;b=a++ +++a +++a +a+++2;cout<<”\n”<<a<<” :“<<b;chang(a,b);cout<<”\n”<<a++ <<” :”<<++b;
}
Ans : 14:5050:14
11;514;55;5
Q4.Givethe outputofthe followingprogram:#include<iostream.h>voidmain(){
inta,*b,**c,***d;a=12,b=&a,c=&b,d=&c;***d*=5;cout<<”\n”<<a<<”,”<<a+*b;(**c)+= 10;cout<<”\n”<<**c +***d;(***d)+=10;cout<<”\n”<<a+*b;
}Ans: 60, 120
140160
Q5. Givethe outputofthe followingprogram:#include<iostream.h>#include<string.h>#include<ctype.h>voidfunnystr(char*s,int n=2){
inti=n;while(i< strlen(s)){
}i=0;
s[i]='-';i=i+n;
while(s[i]!='\0'){
if(s[i]> 'A'&&s[i]<'P')s[i]=tolower(s[i]);
elseif(s[i]>'a'&&s[i]<'p'){
if(i%3 == 0)s[i]=tolower(s[i-1]);
} i++;}
}
elses[i]=tolower(s[i]);
voidmain(){
charstr[]="MiCroSoFT";funnystr(str,3);cout<<str;
}
Ans : mic–oS–fT
Introduction to OOP using C++ Objec
t Oriented Programming ConceptsShortAnswerQuestions
Q1. Defineobject.Ans.Objectisanidentifiableentitywithsome characteristicsandbehaviour.
Q2. Defineclass.Ans.A classisgroupofobjectsthatsharecommonproperties andrelationships.
Q3.Definedataabstraction.Ans.Abstractionreferstothe actofrepresentingessentialfeatureswithoutincludingthebackground details
orexplanations.
Q4.Whatis inheritance?Ans.Inheritancei
sthecapabilitiesofoneclassofthingstoinheritcapabilitiesorpropertiesfromanotherclass.
Q5.Definemodularity.Ans
.Modularityisthepropertyofasystemthathasbeendecomposedintoasetofcohesiveandlooselycoupledmodules.
Q6.Defineencapsulation.Ans.Thewrappingupofdataandoperations/
functions(thatoperateonthedata)intoasingleunit(calledclass )isknownasencapsulation .
Q7.Whatispolymorphism?Ans.Polymorphism isthe abilityforamessageordatatobeprocessedin morethanoneform.
Q8.HowpolymorphismisimplementedinC++?Ans.PolymorphismisimplementedinC++throughoverloadedfunctions,overloadedoperatorsandvirtual
functions.
Q9.HowinheritanceisimplementedinC++?Ans.InheritanceisimplementedinC++byspecifyingthebaseclassfromwhichthederivedclassofthe base
classisdefined.
Q10.Whatisdata hiding?HowitisimplementedinC++?Ans.Dat
ahidingisapropertywherebytheinternaldatastructureofanobjectishiddenfromtherestoftheprogram.DatahidingisimplementedinC++byprivateandprotectedmembersofclass.
Q11.How data abstraction canbeimplemented inC++?Ans.Dataabstractioncan beimplemented inC++byusing publicmembersofclass.
Q12.Whatisprogrammingparadigm?Ans.A programmingparadigmdefinesthe methodology ofdesigningandimplementingprogramsusing
the keyfeaturesandbuildingblocksofa programminglanguage.
Q13.Whatisproceduralprogrammingparadigm?Ans.Inproceduralprogrammingparadigm,dataissharedamongallthefunctions.Itsemphasisisondoing
thingsratherthanusing the data.
SOMEMPORTANTQUESTIONSTOREFRESHTHECONCEPT
Q14.Whatarethe advantagesofOOP?Ans:TheadvantagesofOOPareReusabilityofcode,Easeof
comprehension,easeoffabricationandmaintenance,easeofredesignandextension.Q15.Whatdoyouunderstandbyfunctionaloverloading?GiveanexampleillustratingitsuseinaC++
program.Ans:Afunctionnamehavingseveraldefinitionsthataredifferentiableby
thenumberortypesoftheirargumentsisknownasfunctionaloverloading.Forexample:floatvolume(floata){returna*a*a;}floatvolume(floata,floatb){returna*a*b;}floatvolume(floata,floatb,floatc){returna*b*c;}
CLASSES AND OBJECTS
Q1. Write fourattributesassociatedwithdeclarationofclasses.An
s.TheattributesassociatedwithdeclarationofclassesareDataMembers,MemberFunctions,ProgramaccesslevelsandClassTagname.
Q2. Definedatamembers andmemberfunctions.Ans.Datamembers areexactlylikethevariablesina structure.TheyarenormallymadeMemberfunction
isfunction definedwithina classthatactson thedatamembersinthe class.Theyarenormallymade public.
Q3. Writethe scoperules of members ofa class.Ans.Scope rules of membersofa classare:-
Private Thesemembers canbe accessed onlybythememberfunctions&friendfunctionsoftheclass.ItcannotbeinProtected Thesemembers canbe accessed onlybythememberfunctions&friendfunctionsoftheclass.ItcanbeinheriPublic Thesemembers canbe directlyaccessedbyanyfunction.
Q4. How manytypesoffunctions are usedinaclass?Ans.1.Accessorfunction2.Mutatorfunctions3.Managerfunctions
Q5. Whenwillyoumakeafunctioninline?Ans.Afunctionismadeinlinewhenitisverysmallanddoesnotreturnanyvalue.Alsoitdoesnot
containanyloopand staticvariables.Q6. Whatisscope resolutionoperator?Ans
.Thisoperator(::)isusedinsituationswhereaglobalvariableexistswiththesamenameasalocalvariable.Thisisalsousedwhenthememberfunctionsaredeclaredoutsidetheclassdefinition;thefunctionnameisprecededbytheclassnameandthebinaryscoperesolutionoperator(::).
Q7. Definestatic datamembers.Ans
.Staticdatamembersareinitializedtozerowhenthefirstobjectofitsclassiscreated.Nootherinitializationispermitted.Onlyonecopyofthatmemberiscreatedfortheentireclassandissharedbyallthe objectsforthatclass.
Q8. Howismemoryallocated toaclass anditsobjects?Ans.Whena classisdefined,memoryisallocatedforitsmemberfunctionsandtheyare stored
inthememory.When objectiscreated,separate memoryspaceisallocatedforitsdatamembers.Allobjects workwiththesamecopyof
memberfunctionsharedbyall.
BOARDPATTERNQUESTIONS:LongAnswer Questions (4marks)
Q1.Definea classemployeewiththefollowingspecifications;Privat
emembersofclassemployee:empno integerename 20charactersbasic,hra,da floatnetpay floatcalculate() Afunctiontocalculate basic+hra+dawithfloatreturn type
Publicmemberfunctionsofclassemployee:havedata() functiontoacceptvaluesforempno,sname,basic,hra,daandinvokecalculate() tocalculatenetpaydispdata() functiontodisplayallthedata members on thescreen .
Ans.classemployee{
intempno;charename[20];floatbasic,da,hra;floatnetpay;floatcalculate(){
return (basic+da+hra);}
public:voidhavedata(){
cout<<”Enteremployeeno”;cin>> empno;cout<<”\nEnter name“;cin>>ename;cout<<”\nEnter basicsalary”;cin>> basic;cout<<”\nEnter DA“;cin>>da;cout<<“\nEnterHRA“;cin>>hra;netpay= calculate();
}voiddispdata(){
cout<<“\nEmployeenois“<<empno<< endl;cout<<“\nNameis“<< ename << endl;cout<<“\nBasic Salaryis”<< basic << endl;cout<<“\nDAis“<<endl ;cout<<“\nHRA is“<<hra<<endl;cout<<“\nNetpayis“<<netpay<<endl;
}};
Q2. Definea classStudentforthefollowingspecifications:
PrivatemembersoftheStudentare:roll_nointegername arrayofcharactersofsize 20
class _starrayofcharactersofsize8marks arrayof integers ofsize 5percentagefloatcalculatethatcalculatesthe percentagemarks
Publicmembersofthe Studentare:readmarksreadsmarkandinvoke the calculate functiondisplaymarks prints thedata.
Ans.classStudent{
introll_no;charname[20];charclass_st[8];intmarks[5];floatpercentage;voidcalculate();public:
voidreadmarks();voiddisplaymarks();
};voidStudent::calculate(){
floattotal=0;for(intI=0; I<5; I+
+)total+=marks[I];percentage =total/5;
}voidStudent::readmarks(){
cout<<“\nEnter5marks:“;for(intI=0; I<5; I++)
cin>>marks[I];calculate();
}voidStudent::displaymarks(){
cout<<“\nThe5marksare:“;for(intI=0;I<5; I++)
cout<<marks[I]<< endl;cout<<“\nPercentage=“<<percentage << endl;
}Q3. Definea classDONORwiththefollowingspecifications :
Private:Donornumber integerName 20charactersBloodgroup 2characters
Public:Input() AfunctiontoacceptalltheinformationOutput() A functiontodisplayalltheinformationCheckgroup() Afunctionwith
char*returntoreturnBloodGroupDefineboththenumberfunctionswiththeirgiven description.
Ans.class DONOR{ intd_no;
charname[20];charb_grp[2];
public:voidinput(){
cout<<“\nEnterthe detailsasdonorno,nameandbloodgroup:“;cin>>d_no; gets (name );gets(b_grp);
}voidoutput( ){ cout<<“\nThedetailsare“;
cout<<“\nName :“<<name<<“\nDonorNo:<<d_no;cout<<“\nBloodGroup:“<< b_grp;
}char*checkgroup (){ return( b_grp);}
};Q4. Defineaclass TESTinC++ with
followingdescription:Private Members TestCodeoftypeinteger Descriptionoftypestring NoCandidateoftypeinteger CenterReqd(number ofcentersrequired)oftypeinteger AmemberfunctionCALCNTR()tocalculate
andreturnthenumberofcentersas(NoCandidates/100+1)Public Members
• A functionSCHEDULE()toallow usertoentervaluesforTestCode,Description,NoCandidate&callfunctionCALCNTR()tocalculatethenumberofCentres
• A functionDISPTEST()toallow usertoview thecontentofallthe data membersAns:class TEST{
public:
};
intTestCode;charDescription[20];intNoCandidate,CenterReqd;voidCALCNTR();
voidSCHEDULE();voidDISPTEST();
void TEST::CALCNTR(){
CenterReqd=NoCandidate/100+1;}voidTEST::SCHEDULE(){
cout<<”TestCode :”;cin>>TestCode;cout<<”Description :”;gets(Description);cout<<”Number :”;cin>>NoCandidate;CALCNTR();
}void TEST::DISPTEST(){
cout<<”TestCode
:”<<TestCode<<endl;cout<<”Description :”<<Description<<endl;cout<<”Number :”<<NoCandidate<<endl;;cout<<”Centres :”<<CenterReqd<<endl;;
}
SOMEMPORTANTQUESTIONSTOREFRESHTHECONCEPTCONSTRUCTORANDDESTRUCTOR
Q1.Whatisconstructor?Ans.Amemberfunctionwiththesamenameasitsclassiscalledconstructoranditisusedtoinitialize the
objectsofthatclass typewithalegalinitialvalue.Q2.Whatisdestructor?Ans
.Adestructorisamemberfunctionhavingsamenameasitsclassbutprecededby~signanditdeinitialisesanobjectbefore itgoesoutofscope.
Q3.Whataredifferenttypes ofconstructors?Ans
.ThedifferenttypesofconstructorsareDefaultconstructor,ParameterizedconstructorandCopyconstructor.
Q4. Whatis defaultconstructor?Ans.Aconstructorthatacceptsnoparameteriscalledthedefaultconstructor.Q5. Whatisparameterizedconstructor?Ans.Aconstructorthatacceptsparametersforitsinvocationisknownasparameterizedconstructor.Q6. Whatiscopyconstructor?Ans.Acopyconstructorisaconstructorthatdefinesandinitializesanobjectwithanotherobject.Ittakes
theformclassname(classname).Foracopyconstructortheremustbeadefaultconstructororaparameterizedconstructor.
BOARDPATTERNQUESTIONS-Short AnswerQuestions (2 marks)
Note: Twooptionswith thefollowing patternaregenerallyaskedinthe BoardExam.Variousoptionalquestionsaregivenbelow.
Q7.Answerthefollowing questionsaftergoing throughthefollowingclass:class Seminar{
public:
};
intTime;
Seminar(); //Function 1voidLecture() //Function 2{cout<<”Lecturesinthe seminaron”<<end1;}Seminar(int); //Function 3Seminar(Seminar&abc); //Function 4~Seminar() //Function 5{ cout<<”Voteofthanks”<<end1;
(i) InObjectOrientedProgramming,whatisFunction5referredasandwhendoesitgetinvoked/called?
Ans:Function5isreferredasdestructoranditisinvokedassoonasthescopeoftheobjectgetsover.(ii) InObjectOriente
dProgramming,whichconceptisillustratedbyFunction1,Function3andFunction4 alltogether?Ans: ConstructorOverloading (Polymorphism)
(iii) Whichcategoryofconstructor-Function1belongsto?WriteanexampleillustratingthecallsforFunction1.
Ans:DefaultConstructor.Exampletoinvokefunction1 SeminarS;(iv) Whichcategoryofconstructor-Function3belongsto?
WriteanexampleillustratingthecallsforFunction3.Ans: ParameterisedConstructor.Example toinvokefunction3 SeminarA(8);(v) Whichcategoryofconstructor-Function4belongsto?
WriteanexampleillustratingthecallsforFunction4.Ans:CopyConstructor.Exampletoinvoke function4 SeminarS2(S);Or
SeminarS2=S;(vi) Write an exampleillustrating thecallsforFunction3explicitly.Ans: SeminarA= Seminar(8);(vii) Write an exampleillustrating thecallsforFunction4explicitly.Ans: SeminarS2= Seminar(S);(viii) Write thecomplete definitionforFunction1 toinitializeTime as30.Ans: Seminar::Seminar()
{Time=30;}(ix) Writethe complete definitionforFunction3 toinitializeTimewith Mytime
asparametertotheFunction3.Ans: Seminar::Seminar(intMytime)
{Time= Mytime;}(x) Writethe complete definitionforFunction4.Ans: Seminar::Seminar(Seminar&abc)
{Time=abc.Time;}Q8.Answerthefollowing questionsaftergoing throughthefollowingclass:class
Complex{
public:
};
int x;inty;
Complex(); //Function 1voiddisp() //Function 2{cout<<”The Complexnumberis:“<<x<<” +“<<y<<”i”<<end1;}Complex(int,int); //Function 3Complex(Complex&abc); //Function 4
(i) Whichcategoryofconstructor-Function1belongsto?WriteanexampleillustratingthecallsforFunction1.
Ans:DefaultConstructor.Exampletoinvokefunction1 ComplexC;(ii) Whichcategoryofconstructor-Function3belongsto?
WriteanexampleillustratingthecallsforFunction3.Ans:Parameterised Constructor.Exampletoinvoke function3 Complex C(6,8);(iii) Whichcategoryofconstructor-Function4belongsto?
WriteanexampleillustratingthecallsforFunction4.Ans:CopyConstructor.Exampletoinvoke function4 Complex C2(C);Or
Complex C2=C;(iv) Write anexampleillustrating thecallsforFunction3explicitly.Ans: ComplexC =Complex(6,8);(v) Write anexampleillustrating thecallsforFunction4explicitly.Ans: ComplexC2=Complex(C);(vi) Write the complete definitionforFunction1 toinitializex as 10andyas 20.Ans: Complex::Complex()
SOMEMPORTANTQUESTIONSTOREFRESHTHECONCEPT
{x =10;y=20;}(vii) Write the complete definitionforFunction3 toinitializethedatamembers
withpandqasparametersto the Function3.Ans: Complex::Complex(intp,intq)
{x =p;y=q;}(viii) Write the complete definitionforFunction4.Ans: Complex::Complex(Complex&abc)
{x =abc.x; y=abc.y;
}
Inheritance
Q1. Write the reasonsbehind theintroductionof inheritanceinOOP.Ans.ThemajorreasonsbehindtheintroductionofinheritanceinOOPare:
(i)Itensurestheclosenesswiththerealworldmodels,(ii)ideaofreusability,(iii)transitivenatureofinheritance.
Q2.Whatarethedifferentforms of inheritance?Ans.Thedifferentformsofinheritanceare(i)SingleInheritance,(ii)MultipleInheritance,(iii)Hierarchical
Inheritance,(iv)Multilevel Inheritance,(v)HybridInheritance.Q3
.Howdoestheaccessofinheritedmembersdependupontheiraccessspecifiersandthevisibilitymodesofthe baseclass?
Ans.Accessspecifier
Visibilitymodepublicinheritance protectedinh
eritanceprivate inheritance
publicmemberin base class publicinderivedclass protectedinderivedclass
privateinderivedclass
protectedmemberinbaseclass
protectedinderivedclass
protectedinderivedclass
privateinderivedclass
privatememberinbaseclass
hiddeninderived class hiddeninderivedclass
hiddeninderivedclass
Q4. Write thedifferentways ofaccessibilityof base classmembers.Ans.
AccessSpecifier Accessiblefromown class
Accessiblefromderivedclass (Inheritable)
Accessiblefromobjectsoutsideclasspublic Yes Yes Yes
protected Yes Yes Noprivate Yes No No
Q5.Howisthe size ofaderivedclassobjectcalculated?Ans.Thesizeofaderivedclassobjectisequaltothesumofsizesofdatamembersinbaseclassandthe
derivedclass.Q6
.Inwhatorderareclassconstructorsandclassdestructorscalledwhenaderivedclassobjectiscreatedordestroyed?
Ans.Whentheobjectofaderivedclassiscreated,firstlytheconstructorofthebaseclassisinvokedandthen,the constructorofthe derivedclassisinvoked.Onthe otherhand,whenthe objectofa derivedclassis destroyed,firstlythedestructorofthederivedclassis invokedandthen,the destructorofthebaseclassisinvoked.
Note: Observethefollowing questionsandtheir solutions.Theabove concepts are implemented.Practice ofsuchquestionswilldefinitelyclearyourdoubtsandimproveyourconfidencelevel.Discussionwithyourfriends anddistinguishthe varietiesofthese questions.
BOARDPATTERNQUESTIONSLongAnswerQuestions(4Marks)
Q1.Answerthe questions(i)to(iv) basedonthefollowing:
classbus:privateheavyvehicleclassvehicle{
protected:in
twheels;intpa
ssenger;
classheavyvehicle: protectedvehicle{
intdiesel_petrol;protected:
intload;
{
public:cha
rmake[20];voidfetchdata(
);voiddisplaydata();
public:voidinputdata();voidoutputdata();
};
public: };voidreaddata(int,int);voidwritedata();
};
i) Write themember(s)thatcanbeaccessedfromtheobjectofbus.ii) Write the data member(s)thatcanbeaccessedfromthe functiondisplaydata().iii) How manybytes are requiredbyanobjectofbusandheavyvehicle classesrespectively?iv) Is thememberfunctionoutputdata( )accessible tothe objectsofthe classheavyvehicle?
Ans : (i)fetchdata(),displaydata() (ii)make,load,passanger(iii)forthe objectof bus –28bytes,forthe objectofheavyvehicle–8bytes (iv)No
Q2.Answerthe questions(i)to(iv) basedonthefollowing:classlivingbeing{
charspecification[20];intaverageage;
public:voidread();voidshow();
};
classape:privatelivingbeing{
intno_of_organs;intno_of_bones;
protected:intiq_level;
public:voidreadape();voidshowape();
classhuman:publicape{
charrace[20];charhabitation[30];
public:voidreadhuman();voidshowhuman();
};
};
(i) Write thememberswhichcanbeaccessedfromthememberfunctionsofclasshuman.(ii) Write themembers,whichcanbeaccessedbyanobjectofclass human.(iii) Whatisthe size ofan object(inbytes)ofclasshuman?(iv) Write theclass(es)whichobjectscanaccessread()declaredinlivingbeingclass.
Ans : (i)race,habitation,iq_level,readhuman(),showhuman(),readape(),showape()(ii) readhuman(),showhuman(),readape(), showape()(iii) 78bytes (iv)livingbeing
Q3.Answerthe questions(i)to(iv) basedonthefollowing:classparent{
charname[20];protected:
intson;public:
voidinputdata();voidoutputdata();
};
classfather: protectedparent{
intdaughter;protected:
intbaby;public:
voidreaddata();voidwritedata();
};
classmother:publicfather{
intchild;public:
voidfetchdata();voiddispdata();
};
(i)In caseoftheclassfather,whatis thebaseclassoffatherandwhatis the derivedclassof father?(ii) Write thedatamember(s)thatcanbeaccessedfromfunctiondispdata().(iii) Write thememberfunction(s),whichcanbeaccessedbyanobjectofmotherclass.(iv) Isthememberfunction outputdata()accessible to the objectsoffatherclass?
Ans : (i)base classof father–parent,derivedclass offather–mother
(ii) child,baby,son(iii) fetchdata(),dispdata(), readdata(),writedata() (iv)No
Data Structure & Pointers Address Calculation
ShortAnswerQuestions(3marks)FormulaeofRowMajor&ColumnMajorareusedinthe givenquestions.Kindlygothroughit.Q1.Anarrayx[30]
[10]isstoredinthememorywitheachelementrequiring4bytesofstorage.Ifthebaseaddressofxis4500,findoutmemorylocationsofx[12][8]andx[2][4],ifthecontentisstoredalongtherow.
Ans:Given, W=4, N =30, M =10, Base(x)RowMajorFormula:
=4500
Loc(x[12][8])=Base(x)+W*(M*I+J) Loc(x[2][4]) =Base(x)+W*(M*I+J)=4500+4*(10 *12+8)=4500+4*128=4500+512=5012
=4500+4*(10*2+4)=4500+4*24=4500+96=4596
Q2.AnarrayP[20][30]isstoredinthememoryalongthecolumnwitheachoftheelementoccupying4bytes,findouttheBaseAddressofthearray,ifanelementP[2][20]isstoredatthe memorylocation5000.
Ans:Given,W=4,N=20,M=30, Loc(P[2][20])=5000ColumnMajorFormula:
Loc(P[I][J])=Base(P)+W*(N*J+I)Loc(P[2][20])=Base(P)+4*(20*20+2)Base(P)=5000– 4*(400+2)
=5000–1608=3392
Q3.AnarrayARR[5][25]isstoredinthememorywitheachelementoccupying4bytesofspace.AssumingthebaseaddressofARRtobe1000,computetheaddressofARR[5][7],whenthearrayisstoredas :(i)Row wise (ii) Columnwise.
Ans:(i) Rowwise:Given, W=4, N=5,M
=25,Base(ARR)=1000RowMajorFormula:
Loc(ARR[5][7])=Base(ARR)+W*(M*I+J)=1000+4*(25*5+7)=1000+4*132=1000+528=1528
(ii) Columnwise :Given, W=4, N=5,M
=25,Base(ARR)=1000ColumnMajorFormula:
Loc(ARR[5][7])=Base(ARR)+W*(N*J+I)=1000+4*(5*7+5)=1000+4*40=1000+160=1160
Static Allocation ofObjects ShortAnswerQuestions(2marks)Note
:Practicethewaytowritethefunctiondefinitionwherearrayanditssizearepassedasarguments.Practicewiththeconceptsofaccessingtheelementsoftheone/twodimensionalarray.Applythesuitablelogictosolvethe givenproblemandwrite the codingof it.
Q1. WriteafunctioninC++ tofindsumofrowsfromatwodimensionalarray.Ans:voidMatAdd(intA[][],intN,intM){
for(intR=0;R<N;R++){
intSumR=0;for(intC=0;C<M;C++)
SumR+=A[C][R];cout<<SumR<<endl;
}}
Q2. WriteafunctioninC++tofindthesumofbothleftandrightdiagonalelementsfromatwodimensionalarray(matrix).
Ans: voidDiagSum(intA[][ ], intN){
intSumD1=0,SumD2=0;for(intI=0;I<N;I++){
SumD1+=A[I][I];SumD2+=A[N-I-1][I];
}cout<<”SumofDiagonal1:”<<SumD1<<endl;cout<<”SumofDiagonal2:”<<SumD2<<endl;
}Q3.WriteafunctioninC+
+whichacceptsanintegerarrayanditssizeasargumentsandreplaceselementshavingevenvalueswithitshalfandelementshavingoddvalueswithtwiceitsvalue.eg:
ifthearraycontains: 3,4,5,16,9thenthefunctionshouldberearrangedas6,2,10,8, 18Ans:
voidcalc(intx[], intm){
for(inti=0;i<m;++i){
if(x[i]%2==0)x[i]=x[i]/2;
else
}}
x[i]=x[i]*2;
Q4.WriteauserdefinedfunctioninC++whichintakes onedimensionalarrayandsizeof arrayasargumentanddisplaytheelementswhichareprime.If1Darrayis 10, 2,3, 4,5, 16,17,23Thenprime numbersinabove arrayare:2,3,
5,17,23Ans:voidprimedisp(intx[],intm){
intnf;for(inti=0;i<m;++i){
nf=0;for(intj=1;j<=x[i];j++)
if(x[i]%j== 0)nf++;
if(nf== 2)cout<<”\n”<<x[i];
}}
Q5.WriteafunctioninC++whichacceptsanintegerarrayanditssizeasarguments/parametersand exchanges the valuesatalternate locations.example:ifthearrayis8,10,1,3,17,90,13,60thenrearrange thearrayas 10,8,3,1,90,17,60,13Ans:
voidexchange(intx[], intm){
inty;for(inti=0;i<m;i=i+2){
if(m-i== 1) //ifm(no.ofelement)isoddlastelementi=m;//shouldnotalterits position.
else{
}}
}
`
y=x[i];x[i]=x[i+1];x[i+1]=y;
Short Answer Questions (3 marks) Q1.Write a user defined function DispTen(int A[][4],int N,int M) In c++ to find and display all the numbers, which are divisible by 10. For example if the content of array is:12 20 132 10 30The output should be20 10 30
Ans: void DispTen(int A[ ][4], int N, int M){int i, j ;for(i=0 ; i<N ; i++){for(j=0 ; i<M ; j++){if(A[i][j]%10= =0)cout<<A[i][j]<<” “ ;} } }
Q2Write a function ALTERNATE (int A[ ] [3], int N, int M) in C++ to display all alternate elements from two-dimensional array A (staring from A [0] [0]). For example:If the array is containing:
23 54 7637 19 2862 13 19The output will be23 76 19 62 19Ans:void ALTERNATE (int A [] [3], int N, int M)
{int T=0;for (int I=0 ; I<N; I++)for (int J=0 ; J<M ; J++){if (T%2= =0)cout<<A[I] [J]<<" ";T++ ;}}
Q3. Write a DSUMO function in C++ to find sum of Diagonal Elements from aNxN Matrix. (Assuming that the N is a odd number)Ans.
void DSUM (int A[] [100], int N){int SUMR =0, SUML=0;for (int i=0; i<N; i++){SUMR = SUMR + A[i] [i] ;SUML = SUML + A[i] [N-1-i] ;}cout<< "Sum of Right Diagonal Elements = "<<SUMR<<end1;cout<< "Sum of Left Diagonal Elements = "<<SUML<<end1;}
Q5.Define a function SWAPCOL( ) in C++ to swap (interchange) the first column elements with the last column elements, for a two dimensional integer array passed as the argument of the function.
Example: If the two dimensional array contains2 1 4 91 3 7 75 8 6 37 2 1 2After swapping of the content of 1st column and last column, it should be:9 1 4 27 3 7 13 8 6 52 2 1 7
Ans:void SWAPCOL(int A[ ][100], int M, int N){int Temp, I;for (I=0;I<M;I++){Temp = A[I][0];A[I][0] = A[I][N-1];A[I][N-1] = Temp;}}
Q6.WriteafunctioninC++whichacceptsanintegerarrayanditssizeasargumentsandassignthe elementsinto atwodimensionalarrayofintegersinthefollowingformatIfthearrayis1,2,3,4,5,6 ifthearrayis1,2,3Theresultant2Darrayis Theresultant2D arrayis123456 123012345 012001234 001000123000012000001
Ans://Logic:Conditionforputtingthevalueisthe position (i<=j) of2DarrayotherwiseputzerovoidChange2Darray(intx[],intsize){
for(i=0;i<size;i++){
intk=0;for(intj=0;j<size;j++){
if(i<=j){
}else
y[i][j]=x[k];k++;
y[i][j]=0;}
}for(i=0;i<size;i++){
cout<<”\n”;for(intj=0;j<size;j++)
cout<<y[i][j]<<"";}
}Q7.WriteafunctioninC+
+whichacceptsanintegerarrayofdoubledimensionalwithitssizeasargumentsanddisplaysthetotalnumbersofodd,evenandprimenumbersinthearray.Example : ifthefollowingintegerarraywillbepassed tothefunction,i.e.
Thenthe outputshouldbe: Thetotaloddnumbers are:13Thetotaloddnumbers are:12Thetotaloddnumbers are:10
Ans: voidnumcheck(intarr[][ ],intm,intn){
inti,j, oddt=0, event=0,primet=0,nf,k;for(i=0;i<m;i++){
for(j=0;j<n;j++){
if(arr[i][j]%2==0)event++;
else
nf=0;oddt++;
for(k=1; k<=arr[i][j]; k++){
if(arr[i][j]%k==0)nf++;
}if(nf==2)
primet++;}
}cout<<”\nThetotaloddnumbers are:“<<oddt;cout<<”\nThetotalevennumbersare:“<<event;cout<<”\nThetotalprimenumbers are:“<<primet;
}
6 4 13 19 57 3 8 11 519 12 23 4 621 29 18 9 1028 5 12 2 6
Dynamic Allocation of Objects LongAnswerQuestions (4marks )Note
:InsertionatthebeginningofLinkedList(PushoperationinStack),InsertionattheendofLinkedList(InsertioninaQueue),DeletionfromthebeginningofLinkedList(PopoperationinStackaswellasDeletionofnodeinaQueue)areinthesyllabus.So,onlythelogicofthesethreefunctionsshouldbepracticed.Thelogicandthewaytosolvethesefunctionsaregivenbelow.Practicethem.
1. Write a function QDELETE( ) in c++ to perform delete operation on a Linked Queue, which contains passenger no and passenger name. Consider the following definition of node in the codestruct node{long int Pno ;char Pname[20];node *Link ;}
Ans. class Queue{NODE *Front, *Rear;public:Queue ( ) {Front = NULL; Rear = NULL; }void QueAdd ( );void QueDel ( );void QueDis ( );~Queue();} ;void Queue: :QueDel ( ){if (Front!=NULL){NODE *Temp=Front;cout<<Front->Pno<< " " ;cout<<Front->Pname<< "Deleted";Front=Front->Link;delete Temp;if (Front==NULL) Rear=NULL;}elsecout<<"Underflow ! Queue is empty. .";}Infix& PostfixExpressions Short Answer Questions (2 marks)
Q1. Evaluatethefollowingpostfixnotationofexpression:25 8 3 – / 6 * 10 +Ans:
Operator Scanned StackContent25 258 25,83 25,8,3- 25,5/ 56 5,6* 3010 30,10+ 40
So, theansweris40.
(Infix to Postfix) Q2.ConvertA+(B*C–(D/E))*Fintopostfixformshowingstackstatusaftereverystep.Ans:
StepNo. SymbolScanned Stack Expression1 A ( A2 + (+ A3 ( (+( A4 B (+( AB5 * (+(* AB6 C (+(* ABC7 – (+(- ABC *8 ( (+(-( ABC *9 D (+(-( ABC *D10 / (+(-(/ ABC *D11 E (+(-( ABC *DE12 ) (+( ABC *DE/–13 ) ( ABC *DE/– +14 * (* ABC *DE/– +15 F (* ABC *DE/– +F16 ) ABC *DE/– +F*
So, thepostfixform is: ABC *DE/–+F*Q3.ConvertNOTAOR NOTB ANDNOTCintopostfixform.Ans:
StepNo. SymbolScanned Stack Expression1 (2 NOT (NOT3 A (NOT A4 OR (OR ANOT5 NOT (ORNOT ANOT6 B (ORNOT ANOTB7 AND (ORAND ANOTBNOT8 NOT (ORANDNOT ANOTBNOT9 C (ORAND ANOTBNOTC NOT10 ) ANOTBNOTC NOTANDOR
So, thepostfixform is: ANOTBNOTC NOTAND OR
Q4. Evaluate the following POSTFIX notation. Show status of Stack after every step of evaluation (i.e. after each operator): True, False, NOT, AND, False, True, OR, AND
Ans. Element Scanned Stack StatusTrue TrueFalse True, FalseNOT True, TrueAND TrueFalse True, FalseTrue True, False, TrueOR True, TrueAND TrueFinal Answer: True
SOMEMPORTANTPOINTSTOREFRESHTHECONCEPT
DATA FILEHANDLING
1.TypeofLink StreamClass Example DeclarationFile-to-Memory ifstream ifstreamfin;Memory-to-File ofstream ofstreamfout;File-to-Memory/Memory-to-File fstream fstreamfinout;
2. Syntaxofopen()-<streamtype>.open(<data file>,<filemodes>);Example:-
fin.open(“MARK.DAT”,ios::in |ios::binary);fout.open(“MARK.DAT”,ios::out|ios::app|ios::binary);
3. Differentfilemodesare : ios::in,ios::out,ios::ate,ios::app,ios::trunc,ios::binary,ios::nocreate,ios::noreplace.
4. Syntaxofread()-<streamtype>.read((char*)&buffer,sizeof(buffer));Example : fin.read((char *)&stud, sizeof(stud)); //studisanobject/class
5. Syntaxofwrite()-<streamtype>.write((char*)&buffer,sizeof(buffer));Example : fout.write((char*)&stud,sizeof(stud));//studisanobject/class
6. DetectingEOF:Example :-fin.eof()7. Commonforms offilepointerfunctions:
(a) seekg()–<istreamobject>.seekg(long,seek_dir);Example :-fin.seekg(30,ios::beg);
(b) seekp()–<ostreamobject>.seekp(long,seek_dir);Example :-fout.seekp(–1*sizeof(stud),ios::cur);
(c) tellg()/tellp()returns thepositioninbytesofget_pointer/put_pointer.
(d) Differentdefinitionsofseek_dirareios::beg(referstobeginningofthe file),ios::cur(referstocurrentpositioninthefile),ios::end(refers toendofthefile).
8. Closingafile:stream_object.close();Example :fin.close();Very Short AnswerQuestions (1 mark) Q1. ObservetheprogramsegmentgivenbelowcarefullyandfilltheblanksmarkedasStatement1and
Statement2 usingseekg()/seekp()functionsforperforming therequired task.
#include<fstream.h>classItem{
intIno;charItem[20];public://Functionto search anddisplaythe contentofa particularrecordvoidSearch(int);//Functionto modifythecontentofaparticularrecordnumbervoidModify(int);
};voidItem::Search(intRecNo){
fstreamFile;File.open(“STOCK.DAT”,ios::binary|ios::in);
//Statement1File.read((char*)this,sizeof(Item));cout<<Ino<<”==>”<<Item<<endl;File.close();
}voidItem::Modify(intRecNo){
fstreamFile;File.open(“STOCK.DAT”,ios::binary|ios::in|ios::out);cout>>Ino;cin.getline(Item,20);
//Statement2File.write((char*)this,sizeof(Item));File.close();
}Ans : Statement1 – File.seekg((RecNo–1)*sizeof(Item),ios::beg);Statement2–
File.seekp((RecNo–1)* sizeof(Item),ios::beg);
Q2.ObservetheprogramsegmentgivenbelowcarefullyandfilltheblanksmarkedasStatement1andStatement2usingseekg()andtellg()functionsforperformingtherequired task.#include <fstream.h>class Employee{intEno;charEname[20];pub
lic://Functionto countthetotalnumber ofrecordsintCountrec();};intItem::Countrec(){
fstreamFile;File.open(“EMP.DAT”,ios::binary|ios::in);
//Statement1
intBytes = //Statement2
intCount=Bytes/sizeof(Item);File.close();returnCount;
}Ans: Statement1–
File.seekg(0,ios::end);Statement2–File.tellg();
Q3.Afilenamedas“STUDENT.DAT”containsthestudentrecords,i.e.objectsofclassstudent.AssumingthatthefileisjustopenedthroughtheobjectFILEoffstreamclass,intherequiredfilemode,writethecommandtopositiontheputpointertopointtothebeginningofthesecondrecordfromthelastrecord.
Ans :FILE.seekp(–2* sizeof(student),ios::end);
Q4. A filenamedas“EMPLOYEE.DAT”contains the studentrecords,i.e.objectsofclassemployee.Assumingthat thefileisjustopenedthroughtheobjectFILEof fstreamclass,intherequiredFilemode,writethecommand topositionthegetpointertopoint toeighthrecordfromthebeginning.
Ans :File.seekg(8,ios::beg);
Short AnswerQuestions ( 2 marks) Q1. WriteafunctioninC++ tocountthenumberofalphabetspresentinatextfile“DATA.TXT”.Ans:
void count( ){
ifstreamfile(“DATA.TXT”);charch;inttotal=0;while(file.get(ch)){
if(isalpha(ch))total++;
}cout<<”\nTheTotalnoofalphabetsare”<<total;file.close();
}
Q2. Write afunctioninC++ tocount thenumberof vowelspresentina textfile“STORY.TXT”.
Ans: void vowelcount(){
ifstreamfile(“STORY.TXT”);int n=0;while(file.get(ch)){
if(ch==’a’||ch==’A’||ch==’e’||ch==’E’||ch==’i’||ch==’I’||ch==’o’||ch==’O’||ch==’u’||ch==’U’)
n++ ;}cout<<”\nTotalno. ofvowelsare”<<n;file.close();}
Q3. Write afunctioninC++ tocount thenumberofwords ina textfileNOTES.TXT.Ans:void wordcount( ){
ifstreamf1(“NOTES.TXT”);charch;inttot=0;f1.seekg(0);while(f1.get(ch)){
if(ch==’ ‘||ch==’.’||ch==’?’)tot++;}cout<<”\ntotalno. ofwordsare“<<tot;f1.close();
}Q4. Write a functioninC++ tocount thenumberof lines presentina text file“STORY.TXT”.Ans: void CountLine()
{ifstreamFIL(“STORY.TXT”);intLINES=0;charSTR[80];while(FIL.getline(STR,80)
)LINES++;cout<<”No.ofLines:”<<LINES<<endl;FIL.close();
}
Q5. Write a function CountYouMe( ) in c++ which reads the contents of a text file story.txt and counts the words You and Me (not case senitive)For example, if the file containsYou are my best friend.You and me make a good team.The function should display the output asCount for you: 2Count for me: 1Ans: void COUNTYouMe ( )
{ifstream Fil ("story.txt") ;char STR [10] ;int countyou = 0 ;int countme = 0;while (!Fil.eof ( )){Fil>>STR;if (strcmpi (STR, "Me") = =0 )countme++ ;
if(strcmpi (STR, "You") = =0)countyou++;}cout<<"Count for You : "<<countyou<<end1;cout<<"Count for Me : "<<countme<<end1;Fil.close( ) ; //Ignore
}Q6. Write a function in C++ to read the content of a text file "DELHI.TXT' and display all those lines on screen, which are either starting with 'D' or starting with 'M'.Ans. void DispDorM()
{if stream File("DELHI.TXT");char Str[80];while(File.getline(Str,80)){if(Str[0]='D' || Str[0]='M')cout«Str«endl;}File.close(); //Ignore}
Short Answer Questions (3 marks)
Q1.WriteafunctioninC++toread&displaythedetailsofallthememberswhosemembershiptypeis‘L’or‘M’fromabinaryfile“CLUB.DAT”.AssumethebinaryfilecontainsobjectofclassCLUB.class CLUB{
intmno;charmname[20];chartype;
public:voidregister ();voiddis();charwhattype(){ return type;}
};
Ans: voidshow(){
ifstream file;CLUBc1;chars;file.open(“CLUB.DAT”,ios::in|ios::binary);while(file.read((char*)&c1,sizeof(c1))){
s = c1.whattype();if((s==’L’)|| (s==’M’))
c1.dis();}File.close();
}
Q2. GivenabinaryfilePHONE.DATcontainingrecordsofthefollowingstructuretype.class Phonlist{
public:
charadd;charName[20];chararea[5];
voidregister();voidshow();intcheck(charac[]){
returnstrcmp(area,ac)}
};Q3. Write afunctionTRANSFER()inC++,thatwould copyallrecordswhicharehavingarea as”DEL”fromPHONE.DATto PHONBACK.DAT.
Ans: void transfer(){
ifstreamFin;OfstreamFout;Phonlistph;Fin.open(“PHONE.DAT”,ios::in|ios::binary);Fout.open(“PHONBACK.DAT”,ios::out |ios::binary);while(Fin.read((char*)&ph,sizeof(ph))){ if(ph.check(“DEL”)== 0)
Fout.write((char*)&ph,sizeof(ph));}Fin.close();Fout.close();
}
Q4.WriteafunctioninC++tomodifythenameofastudentwhoserollnumberisenteredduringtheexecutionoftheprogram.Searchtheacceptedrollnumberfromabinaryfile“STUDENT.DAT”andmodify thename,assumingthebinaryfileiscontainingtheobjectsofthefollowing class.class STUD{
public:
intRno;charName[20];
intsrno(){returnRno;}voidEnter(){gets(Name);}voidDisplay(){cout<<Rno<<Name<<endl;}};
Ans: void{
Modifyname()fstreamFile;File.open(“STUDENT.DAT”,ios::binary|ios::in|ios::out);STUDs;intmrno;cout<<”\nEntertheroll numbertomodify:“;
if(s.srno(){cout<<”nModifythes.Enter();File.seekp(sizeof(s),ios::cur);File.write((char&s,e.close() ; }
Databases andSQL ShortAnswerQuestions Q1.Whatisadatabasesystem?Whatarethe advantagesprovidedbyadatabase system?Ans:
Adatabaseisacollectionofinterrelateddataandadatabasesystemisbasicallyacomputerbasedrecordkeepingsystem.Theadvantagesprovidedbyadatabasesystemare(i)reduceddataredundancy(ii)Controlleddatainconsistency(iii)Shareddata(iv)Standardizeddata(i) Secureddata(vi)Integrateddata.
Q2.Whatarethe variouslevels ofdatabase abstractioninadatabasesystem?Ans:Th
evariouslevelsofdatabaseabstractioninadatabasesystemare(i)Internal(Physical)Level(ii)ConceptualLevel(iii)External(View)Level.
Q3.WhatisDataIndependence?WhatarethelevelsofDataIndependence?Ans:DataIndependencei
stheabilitytomodifyaschemedefinitioninonelevelwithoutaffectingaschemedefinitioninthenexthigherlevel.ThetwolevelsofDataIndependenceare(i)PhysicalDataIndependence(ii)LogicalDataIndependence.
Q4.Whatisa view? How isituseful?Ans:
Aviewisavirtualtablethatdoesnotreallyexistinitsownrightbutisinsteadderivedfromoneormoreunderlyingbasetable(s).Itprovidesanexcellentwaytogivepeopleaccesstosome butnotalloftheinformationina table.
Q5.Whatisrelation?Define therelationaldatamodel?Ans:
Arelationisatablehavingatomicvalues,uniquerowsandunorderedrowsandcolumns.Therelationaldatamodelrepresentsdataandrelationshipsamongdatabyacollectionoftablesknownasrelation,eachofwhichhas anumber ofcolumnswith uniquenames.
Q6.Define:(i)Tuple(ii)Attribute (iii)Degree(iv)Cardinality.Ans:
(i)Tuple–Therowsoftables(relations)arereferredastuples.(ii) Attribute – Thecolumns oftables(relations)arereferredasattributes.
(iii) Degree–The numberofattributesina relation(table)iscalleddegree ofa relation.(iv) Cardinality–Thenumber oftuplesina
relation(table)iscalledcardinalityofarelation.Q7.WhatdoyouunderstandbyPrimaryKey&CandidateKeys?Ans:Anattributeorsetattributeswhichareusedtoidentify
atupleuniquelyisknownasPrimaryKey.Ifatablehasmorethanonesuchattributeswhichidentifyatupleuniquely thanallsuchattributesareknownasCandidate Keys.
Q8.Definealternatekey.Whatdoyouunderstandbyforeign key?Ans:Acandidatekeythatisnottheprimarykeyiscalledanalternatekey.Anon-
keyattribute,whosevaluesarederivedfromtheprimarykeyofsomeothertable,isknownasforeignkeyin its currenttable.
Q9.WhatisData DefinitionLanguage? Giveexamplesofsome DDLcommands.Ans:Th
eSQLDataDefinitionLanguageprovidescommandsfordefiningrelationschemas,deletingrelations,creatingindexesandmodifyingrelationschemas.TheexamplesofsomeDDLcommandsareCREATETABLE,ALTERTABLE,DROPTABLE,DROPVIEWcommandsetc.
Q10.WhatisData ManipulationLanguage? Giveexamplesofsome DMLcommands.Ans
:TheSQLDataManipulationLanguageincludesaquerylanguagetoinsert,deleteandmodifytuplesinthedatabase.TheexamplesofsomeDMLcommandsareSELECT,INSERT,DELETE,UPDATE commands etc.
Q11.WhatisSQL?Write the variousprocessingcapabilitiesofSQL.Ans:SQ
Lisalanguagethatenablesyoutocreateandoperateonrelationaldatabases.ThevariousprocessingcapabilitiesofSQLaredatadefinitionlanguage,datamanipulationlanguage,view definition,authorization,integrityandtransaction control.
SYNTAXof some SQLCOMMANDS : 1. SELEC
TcolumnlistFROM<tablename>WHERE<condition>GROUPBY<columnname(s)>HAVING<searchcondition>ORDER BY column name;
2. INSERTINTO<table name>[<columnlist>]VALUES(<value>,<value>,...);3. DELETE FROM<table name>[WHERE<predicate>];4. UPDATE<tablename>SET<columnname>=<newvalue>[WHERE<predicate>];5. CREAT
ETABLE<tablename>(<columnname><datatype>[(size)]<columnconstraint>,<columnname><datatype>[(size)]<columnconstraint>,...<tableconstraint> (<columnname>[<columnname>...])...);
6. CREATEVIEW<viewname>[(<columnname>,<columnname>,...)]AS<SELECTcommand>;
7. ALTERTABLE<tablename>ADD/MODIFY<columnname><datatype><size>;8. DROPTABLE<table name>;9. DROPVIEW<viewname>;
LongAnswer Questions
Q1.ConsiderthefollowingtablesACTIVITYandCOACH.Write SQLcommandsforthestatements(i)to(iv)andgive outputs forSQLqueries(v)to(viii).
Table:ACTIVITYACode ActivityName ParticipantsN
umPrizeMoney ScheduleDate
1001 Relay100x4 16 10000 23-Jan-20041002 Highjump 10 12000 12-Dec-20031003 ShotPut 12 8000 14-Feb-20041005 LongJump 12 9000 01-Jan-20041008 DiscussThrow 10 15000 19-Mar-2004
Table:COACHPCode Name ACode1 AhmadHussain 10012 Ravinder 10083 Janila 10014 Naaz 1003
(i) TodisplaythenameofallactivitieswiththeirAcodesindescendingorder.(ii) Todispla
ysumofPrizeMoneyforeachoftheNumberofparticipantsgroupings(asshownincolumnParticipantsNum10,12,16).
(iii) Todisplaythecoach’snameandACodesinascendingorderofACodefromthetableCOACH.
(iv)Todisplaythe contentofthe GAMEStablewhose ScheduleDateearlierthan01/01/2004inascendingorderofParticipantNum.
(v) SELECTCOUNT(DISTINCT ParticipantsNum)FROM ACTIVITY;(vi) SELECTMAX(ScheduleDate),MIN(ScheduleDate)FROM ACTIVITY;(vii) SELECTSUM(PrizeMoney)FROMACTIVITY;(viii) SELECTDISTINCTParticipantNumFROMCOACH;
Ans:(i) SELECTActivityName,ACode FROMACTIVITYORDERBYAcode DESC;(ii) SELECT SUM(PrizeMoney),ParticipantsNum FROM ACTIVITY GROUP
BYParticipantsNum;(iii) SELECTName,ACodeFROM COACHORDER BY ACode;(iv) SELECT*FROMACTIVITYWHEREScheduleDate<’01-Jan-
2004’ORDERBYParticipantsNum;(v) 3(vi)19-Mar-2004 12-Dec-2003(vii) 54000(viii) 1
6 10 12
Q2. Considerthe followingtablesGAMESandPLAYER.WriteSQLcommandsforthestatements(i)to(iv)andgive outputs forSQLqueries(v)to(viii).
Table:GAMESGCode GameName Number PrizeMoney ScheduleDate101 CaromBoard 2 5000 23-Jan-2004102 Badminton 2 12000 12-Dec-2003103 Table Tennis 4 8000 14-Feb-2004105 Chess 2 9000 01-Jan-2004108 LawnTennis 4 25000 19-Mar-2004
Table:PLAYERPCode Name Gcode1 NabiAhmad 101
2 RaviSahai 1083 Jatin 1014 Nazneen 103
(i) TodisplaythenameofallGames withtheirGcodes.(ii) Todisplaydetailsofthosegames whicharehavingPrizeMoneymorethan7000.(iii)Todisplaythe contentofthe GAMEStableinascendingorderofScheduleDate.(iv) TodisplaysumofPrizeMoneyforeachoftheNumber ofparticipation
groupings(asshownincolumnNumber2or4).(v) SELECTCOUNT(DISTINCT Number)FROMGAMES;(vi) SELECTMAX(ScheduleDate),MIN(ScheduleDate)FROM GAMES;(vii) SELECTSUM(PrizeMoney)FROMGAMES;(viii) SELECTDISTINCTGcodeFROM PLAYER;
Ans:(i) SELECTGameName,Gcode FROM GAMES;(ii) SELECT* FROMGAMESWHEREPrizeMoney>7000;(iii) SELECT*FROMGAMESORDERBY ScheduleDate;(iv) SELECTSUM(PrizeMoney),NumberFROMGAMESGROUPBYNumber;(v) 2(vi)19-Mar-2004 12-Dec-2003(vii) 59000(viii) 1
01 103 108
Q3.ConsiderthefollowingtablesHOSPITAL.GiveoutputsforSQLqueries (i)to(iv)andwriteSQLcommandsfor the statements(v)to(viii).
No Name Age Department Dateofadmin Charge Sex1 Arpit 62 Surgery 21/01/06 300 M2 Zayana 18 ENT 12/12/05 250 F3 Kareem 68 Orthopedic 19/02/06 450 M4 Abhilash 26 Surgery 24/11/06 300 M5 Dhanya 24 ENT 20/10/06 350 F6 Siju 23 Cardiology 10/10/06 800 M7 Ankita 16 ENT 13/04/06 100 F8 Divya 20 Cardiology 10/11/06 500 F9 Nidhin 25 Orthopedic 12/05/06 700 M10 Hari 28 Surgery 19/03/06 450 M
(i) SelectSUM(Charge)fromHOSPITALwhere Sex=’F’;(ii) SelectCOUNT(DISTINCTDepartment) fromHOSPITAL;(iii) SelectSUM(Charge)fromHOSPITALgroup byDepartment;(iv) SelectNamefromHOSPITALwhereSex=’F’ANDAge>20;(v) To showallinformationaboutthepatients whosenamesarehavingfourcharactersonly.(vi) Toreduce Rs 200fromthe charge of femalepatientswhoareinCardiologydepartment.(vii) Toinsertanew rowinthe above tablewith
thefollowingdata:11,‘Rakesh’,45,‘ENT’,{08/08/08},1200,‘M’
(viii) Toremovetherows fromtheabovetable where ageofthepatient>60.
Ans:(i) 1200(ii)4(iii)1050
70011501300
(iv) Dhanya(v) SELECT *FROMHOSPITALWHERENAMELIKE“____”;(vi) UPDATEHOSPITALSETCHARGE=CHARGE–
200WHERE(DEPARTMENT=‘CARDIOLOGY’ ANDSEX=‘F’);(vii) INSERTINTO HOSPITALVALUES(11,‘Rakesh’,45,‘ENT’,{08/08/08},1200,‘M’);(viii) DELETEFROMHOSPITALWHEREAGE>60;
Q4.Considerthefollowingtables BOOKS.WriteSQLcommandsforthe statements(i)to(iv)andgiveoutputs forSQLqueries(v)to(viii).
Table :BOOKSB_Id Book_Name Author_Name Publisher Price Type QuantityC01 FastCook Lata Kapoor EPB 355 Cookery 5F01 TheTears WilliamHopkins First 650 Fiction 20T01 MyC++ Brain&Brooke FPB 350 Text 10T02 C++ Brain A.W.Rossaine TDH 350 Text 15F02 Thuderbolts Anna Roberts First 750 Fiction 50
i). TolistthenamesfrombooksofTexttype.ii). Todisplaythenamesandpricefrombooks inascendingorderoftheirprice.iii).
ToincreasethepriceofallbooksofEPB publishers by50.iv). Todisplaythe Book_Name,QuantityandPriceforallC++ books.v).
Selectmax(price)frombooks;vi). Selectcount(DISTINCTPublishers)frombooks wherePrice >=400;vii). SelectBook_Name,Author_Namefrombooks where Publishers =‘First’;viii). Selectmin(Price)frombooks wheretype=‘Text’;
Ans: (i)SELECTBook_Name FROMBOOKSWHEREType=‘Text’;(ii) SELECTBook_Name,Price FROMBOOKSORDERBY Price;(iii) UPDATEBOOKSSETPrice=Price +50WHEREPublisher=‘EPB’;(iv) SELEC
TBook_Name,Quantity,PriceFROMBOOKSWHEREBook_NameLIKE‘%C++%’;(v)750(vi) 2(vii) TheTears
WilliamHopkinsThuderboltsAnna Roberts
(viii) 350
Q5.ConsiderthetablesITEMS&COMPANY.WriteSQLcommandsforthe statements(i)to(iv)and give theoutputsforSQLqueries(v)to(viii).
Table:ITEMSID PNAME PRICE MDATE QTYT001 Soap 12.00 11/03/2007 200T002 Paste 39.50 23/12/2006 55
T003 Deodorant 125.00 12/06/2007 46T004 HairOil 28.75 25/09/2007 325T005 ColdCream 66.00 09/10/2007 144T006 ToothBrush 25.00 17/02/2006 455
Table: COMPANYID COMP CityT001 HLL MumbaiT008 Colgate DelhiT003 HLL MumbaiT004 Paras HaryanaT009 Ponds NoidaT006 Wipro Ahmedabad
i). TodisplayPNAME,PRICE* QTYonlyforthecityMumbai.ii).
Todisplayproductname,companyname&priceforthoseitemswhichIDsareequaltotheIDsofcompany.
iii). Todeletetheitems producedbefore 2007.iv). Toincreasethequantityby20forsoapandpaste.v). SELECTCOUNT(*)FROMITEMS WHEREITEMS.ID=COMPANY.ID;
vi). SELECTPNAMEFROMITEMSWHEREPRICE=SELECTMIN(PRICE)FROMITEMS;vii). SELECTCOUNT(*)FROM COMPANYWHERECOMPLIKE“P____”;
viii). SELECTPNAMEFROMITEMSWHEREQTY<100;
Ans:(i)SELECTPNAME,QTY*PRICEFROMITEMSWHEREITEMS.ID=COMPANY.IDANDCOMPANY.City=’Mumbai’;
(ii) SELECTPNAME,COMP,PRICEFROMITEMS,COMPANYWHEREITEMS.ID= COMPANY.ID
(iii) DELETEFROMITEMSWHEREMDATE<{01/01/2007};(iv) UPDAT
EITEMSSETQTY=QTY+20WHEREPNAME=‘Soap’ORPNAME=‘Paste’;(v) 4(vi) Soap(vii) 2(viii) Paste
Deodorant
Boolean Algebra Introductio
n to BooleanAlgebra & Laws BooleanAlgebraRules1 0+X=X Propertiesof02 0. X =0
3 1+X=1 Propertiesof14 1. X =X5 X+X=X IdempotenceLaw6 X.X=X7 (X)=X InvolutionLaw8 X+X=1 ComplementarityLaw
9 X.X=010 X+Y=Y+X CommutativeLaw11 X.Y=Y. X12 X+(Y+Z)=(X+Y)+Z AssociativeLaw13 X(YZ)=(XY)Z14 X (Y+Z)=XY +XZ Distributive Law15 X+YZ=(X+Y)(X+Z)16 X+ XY=X Absorption Law17 X. (X+Y)=X18 X+XY=X+Y ThirdDistributive Law19 (X+Y)=X.Y DeMorgan’sTheorem20 (X.Y)=X+Y
Short Answer Questions (2 marks)
Q1.Stateand verifyDemorgan'sLaws algebraically.Ans: Demorgan'sLawsare :(i)(X+Y)'= X'.Y' (i)
(X.Y)'=X'+Y'Verification(X+Y)'.(X+Y)= X'.Y'.(X+Y)0=X'.Y'.X+X'.Y'.Y0=X'.X.Y'+ X'.00=0.Y'+00=0+00=0L.H.S= R.H.S
(X.Y)'+(X.Y)=(X'+Y')+ (X.Y)1=(X'+Y'+X).(X'+Y'+ Y)1=(X'+X+Y'). (X'+1)1= (1+Y'). 11=1.11=1L.H.S= R.H.S
Q2.StateandalgebraicallyverifyAbsorptionLaws.Ans: AbsorptionLawsare:(i)X+X.Y =X (ii)X.
(X+Y)=XVerification:L.H.S=X+X.Y
=X.1+X.Y= X.(1 + Y)=X.1=X=R.H.S
L.H.S=X.(X+Y)=X.X+X.Y=X+ X.Y= X.(1 + Y)=X.1=X=R.H.S
Q3.StateDistributive Laws.Writethedualof:X+XY=X+YAns:Distributivelaws are:(i)X.(Y+Z)=X.Y +X.Z (ii)X+Y.Z=(X+Y).
(X+Z)ThedualformofX+XY=X+YisX. (X+Y)=X.YQ4.StateanyoneformofAssociativelaw andverifyitusing truthtable.Ans: Associativelawstatesthat: (i)X+ (Y +Z)= (X+Y)+Z (ii)X.
(Y.Z)=(X.Y).ZVerificationofX + (Y+Z)=(X+Y)+Z using truthtableX Y Z Y+Z X+Y X+(Y+Z) (X +Y)+Z0 0 0 0 0 0 00 0 1 1 0 1 10 1 0 1 1 1 10 1 1 1 1 1 11 0 0 0 1 1 11 0 1 1 1 1 11 1 0 1 1 1 11 1 1 1 1 1 1
Q5.Statetheprincipleofdualityinbooleanalgebra andgivethedualofthefollowing:X.Y.Z+X.Y.Z+X.Y.Z
Ans: Principleofdualitystatesthatfromeveryboolean relation,anotherbooleanrelationcanbederivedby: (i)changingeachOR(+)signtoanAND(.) sign
(ii) changingeachAND (.)sign toanOR(+) sign(iii) replacing each1 by0andeach0 by1.
Thedual formofX.Y.Z+X.Y.Z+X.Y.Zis(X+Y+Z) . (X+Y+Z).(X+Y+Z)
Q6.Explainabouttautologyandfallacy.Ans:Ifresultofanylogical statementorexpressionis always TRUEor1,itiscalledtautology.
Ifresultofanylogical statementorexpressionis alwaysFALSEor0,itiscalledfallacy.Forexample,1+X=1isatautologyand 0.X=0 is afallacy.
SOP & POSVery Short AnswerQuestions (1 Mark)
Q1.Writethe POSformofaBooleanfunctionF,whichis represented inatruthtable asfollows:U V W F0 0 0 10 0 1 00 1 0 10 1 1 01 0 0 11 0 1 01 1 0 11 1 1 1Note:
InPOS,consideronly thecasesthosecontaining0inFcolumn.Forthesamerows,writesumofthelogicalvariables(Ex.Ui.e.0inUcolumn,U'i.e.1forUcolumn).Thenwritetheproductformofallsuchsumof logicalterms.Ans:F(U,V,W)=(U+V+ W').(U+V'+W').(U'+V+W')
Q2.Writethe SOPformofaBooleanfunctionG,whichis represented inatruthtable asfollows:X Y Z G0 0 0 00 0 1 10 1 0 10 1 1 01 0 0 01 0 1 11 1 0 11 1 1 0Note:
InSOP,consideronly thecasesthosecontaining1inGcolumn.Forthesamerows,writeproductofthelogicalvariables(Ex.X'i.e.0inXcolumn,Xi.e.1forXcolumn).Thenwritethesumformofall suchproductoflogicalterms.Ans: G(X,Y,Z)=(X'.Y'. Z)+( X'.Y.Z')+(X.Y'. Z)+(X.Y. Z')
Q3.Convert thefollowingfunctionintocanonicalSOPform.F(A, B,C,D)= (1,4,6, 8,11, 13)
Ans:F(A,B,C,D)=A'B'C'D+A'B C'D'+A'BC D'+AB'C'D' +AB'C D+ABC'D(Note:Here1 =0001 A'B'C'D ,4=0100 A'BC'D',13 =1101 ABC'D ...)
Q4.Convert thefollowingfunctionintocanonicalSOPform.F(A, B,C,D)= (0, 3,7, 9, 10, 14)
Ans:F(A,B,C,D)=(A+B+C+D).(A+B+C'+D').(A+B'+C'+D').(A'+B+C+D').(A'+B+C'+D).(A'+B'+C'+D)
1
14 5
15
11412
11
CDAB
A'B'
C'D'1
C'D CD1
CD'1
032
A'B 1176
AB 1 113
AB' 1 1 18910
1 3 2
0
4
0 0 07
12 13
015 14
08
9
C+DA+BC+D C+D' C'+D' C'+D
A+B 00
A+B'5 6
A'+B'
01110
(Note :Here0=0000 A+B+C+D ,3 =0011 A+B+C'+D',10= 1010 A'+B+C'+D...)Q5.Convert thefollowingfunctiontoitsequivalentSOPshorthandnotation.
F(A, B,C,D)= (0, 3,7, 9, 10, 14)Ans: TheequivalentSOPshorthandnotationof F( A,B,C,D)
= (0,3,7,9,10,14)isF(A,B,C,D)= (1,2,4,5,6,8,11,12,13,15)Q6.Convert thefollowingfunctiontoitsequivalentPOSshorthandnotation.
F(A, B,C,D)= (1,4,6, 8,11, 13)Ans: The equivalentPOSshorthandnotationof F( A,B, C,D) = (1,4,6,8,11,13)
isF(A,B,C,D)= (0,2,3,5,7,9,10,12,14,15)Karnaug
h Map Short Answer Questions (3 marks)
Q1.ReducethefollowingBooleanExpressionusingK-Map:F( A, B,C,D) = (0,2,3,4,6,7,8,9,10,12, 13, 14)
Ans:
Thereare1octet, 2quadsaftereliminatingthe redundantgroups.Octet(m0,m2,m4,m6,m8,m10,m12,m14)reduces toD'Quad(m2,m3,m6,m7) reduces toA'CQuad (m8,m9,m12,m13) reduces
toAC 'Hence,F(A,B,C, D)=D'+A'C +AC'Q2.ReducethefollowingBooleanExpressionusingK-
Map:F(A, B, C,D)= ( 0,3,5,6,7,8,11,15)Ans:
A'+B
Thereare1quadand 3pairs aftereliminatingtheredundantgroups.Quad (M3,M7,M11,M15) reduces toC'+ D'Pair(M5, M7) reduces toA+B '+D'Pair(M6, M7) reduces toA+B '+C'Pair(M0, M8) reduces toB+C +D
Hence,F(A,B,C, D)=(C'+D').(A+B '+D').(A+B '+C').(B+C +D)
C’D’ C’D CD CD’A’B’ 1
01
1 3 2
A’B 1 1 17 64
AB12
114
AB’8 9 11
110
5
113 15
Q3.ReducethefollowingBooleanExpressionusingK-Map:F( A,B,C,D) = ( 2,3,4,5,10,11,13,14, 15)
Ans:CD
AB C'D' C'D CD CD'
A'B
'A'B
1 10 1 3 2
1 14 5 7 6
AB
AB'
112 13
1 115 14
1 18 9 11 10
Thereare2quadsand 2pairsaftereliminatingtheredundantgroups.Quad 1(m2,m3,m10,m11) reduces toB'CQuad 2 (m10,m11,m14,m15)reducestoACPair1(m4,m5)
reduces toA'BC 'Pair1(m13,m15) reduces toABD
Hence,F(A,B,C, D)=B'C+AC +A'BC'+ABD
Q4.ReducethefollowingBooleanExpressionusing K-Map:F(A,B,C,D)= (0,1,4,5,7,10,13,15)Ans:Thereare2quadsandone blockaftereliminatingtheredundantgroups.
Quad 1(m0,m1,m4,m5) reduces toA'C 'Quad 2(m0,m2, m4,m6) reduces toBDm10=AB'C D'Hence,F(A,B,C, D)=A'C '+B D+AB 'C D'
Page 54/70
Basic LogicGates Note: Agateissimplyanelectronic circuitwhichoperateson oneor moresignalstoproduce
anoutputsignal. The three basiclogicgates areNOT gate,ORgate, ANDgate.NORgate,NAND gate,XORgate,XNORgatecanbederivedfromthesethree basicgates.NORandNAND gates arecalleduniversalgates because anycombinationalcircuitispossible usingNORorNAND gates.Practicedifferentquestionsbasedonlogicgates.
Short Answer Questions (2 marks) Q1.WritetheequivalentBooleanExpressionforthefollowingLogic Circuit.
P
Q
Ans: F(P, Q)=(P’+Q). (P+Q’)Q2.WritetheequivalentBooleanExpressionforthefollowingLogic Circuit.
U
V
Ans: F(U,V)=U’.V+U.V’
Q3.DrawtheLogic CircuitDiagramforthefollowing BooleanExpression:F=(A.C)+( A.B)+(B.C)
Ans:A
B
FC
Communication &OpenSource Concepts Very Short AnswerQuestions
Q1.Whatisa network?Ans : A
networkisinterconnectedcollectionofautonomouscomputersthatcanshareandexchangeinformation.
Q2.Mention the advantages of networking.Ans : The advantagesofnetworkingareResourcesharing,Reliability,Reducedcost,Fastcommunication.
Q3.Defineserver.Mention thetypesofservers.Ans:
Acomputerthatfacilitatesthesharingofdata,software,andhardwareresourcesonthenetworkistermedasserver.The twotypesofserversare non-dedicated&dedicatedservers.
Q4.WhatisNIU? What does theMAC address refer to?Ans:ANetworkInterfaceUnitis an interpreter that helps establish communication between the server
and workstations.TheMAC address refers to the physical address assigned by NIC manufacturer.
Q5.Whatarethedifferenttypesofswitchingtechniques?Ans:Th
edifferenttypesofswitchingtechniquesarecircuitswitching,Messageswitchingandpacketswitching.Q6.Whatisacommunication channel?Give examplesofguidedmedia&unguidedmedia.Ans
:Communicationchannelmeanstheconnectingcablesthatlinkvariousworkstations.TheexamplesofguidedmediaareTwisted-paircables,Coaxialcables,Fibre-opticscables.Theexamplesofunguidedmediaaremicrowave,radiowave,satellite,infraredwave etc.
Q7.Define the term Bandwidth.Giv any one unit of Bandwidth.Ans:Bandwidth is referred to the volume of information per unit of time that a transmission
medium(like an Internet connection)can handle.OR
Theamountofdatathatcanbetransmittedinafixedamountoftimeisknownasbandwidth.Fordigitaldevices,thebandwidthisusuallyexpressedinbitspersecond(bps)orbytespersecond.Foranalogdevices,the bandwidthisexpressedincyclespersecond,orHertz(Hz).
Q8.Expand:HTTP,FTP, TCP/IP,SLIP, PPP, NCP,GSM,TDMA,CDMA,WLL,PSTN.Ans: HTTP:HypertextTransferProtocol, FTP:FileTransferProtocolTCP/IP:TransmissionControlProtocol/InternetProtocol
SLIP:SerialLineInternetProtocol, PPP: Point toPointProtocolNCP:NetworkControlProtocol,
GSM:GlobalSystemforMobileTDMA:Time DivisionMultipleAccess, CDMA: CodeDivisionMultiple AccessWLL:WirelessLocalLoop PSTN: PublicSwitchedTelephone Network
Q9.Whatarethedifferenttypesof networks?Ans: Thedifferenttypesofnetworks are :
(a) LocalAreaNetwork (LAN): This computernetworkisconfinedtoalocalisedarea suchasanoffice oracampus.
(b) MetropolitanAreaNetwork(MAN):Thisisthenetworkthatlinkscomputerfacilitieswithinacity.
(c) WideAreaNetwork(WAN):Thisnetworkspreadsoverlargedistanceslikeacrosscountries orevencontinents.
Q10.Whatdoyoumeanbynetworktopology?Whatarethemostpopulartopologies?Ans
:Topologyreferstothewayinwhichtheworkstationsattachedtothenetworkareinterconnected.ThemostpopulartopologiesareBusTopology,RingTopology,StarTopology,TreeTopology.
Q11.Whatarethe advantagesofE-mail?Ans:TheadvantagesofE-
mailareLowcost,Speed,Wastereduction,Easeofuse,Recordmaintenance,Patience.Q12.What is WWW? What are the WWW attributes?Ans:The WorldWideWeb(WWW) is a set of protocols that allow you to access any document on
the NET through an aming system based on URLs. The various WWW attributes are:User-friendly,Multimedia documents,Hypertext and Hyperlinks,Interactive,Frames.
Q13.Whatiswebbrowser? Giveanytwoexamples ofwebbrowsers.Ans:AwebbrowserisaWWWclientthatnavigatesthroughtheWWWanddisplayswebpages.
ExamplesofwebbrowsersareInternetExplorer,Netscape NavigatorandMosaic.Q14.Definetheterms:Website,Webpage,Homepage,Webportal.Ans: Website :Alocationon anetserveriscalleda website.
Webpage:AdocumentthatusesHypertextTransferProtocoliscalleda Webpage.Homepage :Thetop-levelwebpage ofawebsiteiscalledHome page.Webportal:The websitewhichhostsotherwebsitesiscalledWebportal.
Q15.WhendoyoupreferXMLoverHTMLandwhy?Ans:Th
efirstbenefitofXMListhatbecauseyouarewritingyourownmarkuplanguage,youarenotrestrictedtoalimitedsetoftagsdefinedbyproprietaryvendors.Ratherthanwaitingforstandardsbodiestoadopttagsetenhancements(aprocesswhichcantakequitesometime),orforbrowsercompaniestoadopteachother'sstandards,withXML,youcancreateyourownsetoftags atyourownpace.
Q16.Compareauthorisationwithauthentication.Ans
:Authorisationdetermineswhethertheserviceproviderhasgrantedaccesstothewebservicetotherequestor.Authorisationisperformedbyaskingtheuseralegalloginid.Authenticationensuresthateachentityinvolvedinusingawebserviceiswhatactuallyclaimstobe.Itistermedaspasswordprotectionastheauthoriseduserisaskedtoprovideavalid password.
Q17.WhatisFirewall?Howfirewallprotectsournetwork?Ans:Th
esystemdesignedtopreventunauthorisedaccesstoorfromaprivatenetworkiscalledfirewall.Itisadeviceorsetofdevicesconfiguredtopermit,deny,encrypt,decrypt,orproxyall(inandout)computertrafficbetweendifferentsecurity domainsbaseduponasetofrulesandothercriteria.
Q18.Whatarecookies?Ans:Cookies ar messages that a Webserver transmits to a Webbrowser so that the Webserver can
keep track of the user’s activity on a specificWebsite.Q19.How is a cracker different from a hacker? If someone hashacked yourWebsite,to whom
you lodge the Complain?Ans:Acracker is a malicious programmer who breaks into securesystem where as a hacker is more
interested in gaining know ledge about computersystems.If someonehashackedourWebsite thecomplainthas to be lodged with thePolice unde rITAct.
Q20.WhatisCyberlaw?Ans:Cyberlaw is a generic term,which refers to all the legal and regulatory aspects of Internet and
the WorldWideWeb.Q21.Expand:(i)FLOSS (ii)FSF (iii)OSI
(iv)W3CAns:(i)FLOSS= Free Libre andOpenSource Software
(ii) FSF= Free SoftwareFoundation (iii)OSI=OpenSource Initiative(iv)W3C =WorldWideWebConsortium
Q22.Whatisa computervirus? Write thebasic types ofviruses.Ans
:Computervirusisamaliciousprogramthatrequiresahostandisdesignedtomakeasystemsick.BroadlythreetypesofvirusesareFileinfectors,BootSectorVirusesandMacroviruses.
Q23.Definethe terms :Trojan Horses,Worm,Spam.Ans:TrojanHorses:Itiscodehiddeninaprogramsuchasagameorspreadsheetthatlookssafetorunbuthas
hiddensideeffects.
Worm:Awormisa programdesignedtoreplicate.Spam:Itrefers to electronic junk mail or junk news group posting.
Q24. What is cloud computing? Write any two features of it.Ans. The practice of using a network of remote servers hosted on the Internet to store, manage, and process data, rather than a local server or a personal computerFeatures : 1. On demand self service 2. Broad network access
3. Resource pooling 4. Rapid elasticity 5. Measured service 6. Non dependence on local hardware
BlockDBlock A
BlockB
BlockC Block
DBlock
B
BlockA
BlockA
BlockB
Q1.KnowledgeSupplementOrganisationhassetupitsnewcentreatMangaloreforitsofficeandwebbasedactivities.Ithas4blocksofbuildingsasshown inthe diagram below:
BlockC
Centre to centredistancesbetweenvarious blocks NumberofComputersBlackAtoBlockB 50mBlockBtoBlock C 150mBlock C toBlock D 25mBlockAtoBlock D 170mBlockBtoBlock D 125mBlockAtoBlock C 9
BlackA 25BlockB 50Block C 125BlockD 10
(a) Suggestacablelayout ofconnectionsbetweentheblocks.(b) Suggestthemostsuitableplace(i.e.block)tohousetheserverofthisorganisationwithasuitablereason.(c) Suggesttheplacementofthefollowing devices with justification
(i) Repeater (ii) Hub/Switch(d) Th
eorganizationisplanningtolinkitsfrontofficesituatedinthecityinahillyregionwherecableconnectionisnotfeasible,suggestaneconomicwaytoconnectitwithreasonablyhighspeed?
Ans :(a)
OR
BlockC
BlockD
Layout2Sincethe distancebetween BlockAand BlockBisquiteshort
(b) Themostsuitableplace/blocktohousetheserverofthisorganisationwouldbeBlockC,asthisblockcontains themaximumnumberof computers, thus decreasing thecablingcostformostofthecomputersaswellasincreasingtheefficiencyofthemaximumcomputersinthe network.
(c) (i)ForLayout1,sincethecablingdistancebetweenBlocksAandC,andthatbetweenBandCarequitelarge,soarepeatereach,wouldideallybeneededalongtheirpathtoavoidlossofsignalsduring thecourseofdataflow intheseroutes.
Forlayout2,sincethedistancebetweenBlocksAandCislargesoarepeaterwouldideallybeplacedinbetweenthis path(ii)Ahub/switcheachwouldbeneededinalltheblocks,tointerconnectthegroupofcablesfromthedifferentcomputersineachblock.
(d) Themosteconomicwaytoconnectitwithareasonablehighspeedwouldbetouseradiowavetransmission,a
Layout1
stheyareeasytoinstall,cantravellongdistances,andpenetratebuildingseasily,sotheyarewidely usedforcommunication,bothindoorsandoutdoors.Radiowavesalsohavetheadvantageofbeingomnidirectional,whichistheycantravelinallthedirectionsfromthesource,sothatthetransmitterandreceiverdonot havetobecarefullyalignedphysically