Anda di halaman 1dari 62

SUBJECT: C++ (PGDCA/MSC-1) Section A [QUESTIONS 1 TO 42] 2 Marks Questions [PAGE 1 TO 6]

1/62

Q1 !"at are #o$$ents% Ans Comments are pieces of source code discarded from the code by the compiler. They dont change anything in the execution of the program. Their purpose is to allow the programmer to insert notes or descriptions embedded within the source code. Hence they help in documentation of the code. C++ supports two ways to insert comments: // Line comment
/ bloc! comment /

Q2 Ans

!"at is a &re&rocessor 'irecti(e% !"at is its ro)e in #**% Or !"+ s+$,o)ic state$ents are use'% "reprocessor directi#es are orders that we include within the code of our programs that are not instructions for the program itself but for the preprocessor. The preprocessor is executed automatically by the compiler when we compile a program in C++ and is in charge of ma!ing the first #erifications and digestions of the program$s code. .i//erentiate ,et0een constants an' (aria,)es %ariables are the named memory location in computer memory and #ary their #alue at run time. &ut constants remain the same and cannot change their #alue at run time. .i//erentiate ,et0een 1 an' 1 1 o&erators '( operator is one of the assignment operator) used to assign the #alue to a #ariable. '( ( *perator is one of the relational operator+ used to chec! the relation between two #ariables. !rite a s"ort note on t+&e castin3 Type casting is used to con#ert the data type from lower data type to higher data type and con#erse for temporary period so that calculations can be performed with both the data types. ,xample #oid main-. / int a(0+ float b+ cout112#alue of a 311a+ b(-float.a+ cout112#alue of b 3)b+ 4 !"at are ke+ 0or's% 4o0 t"ese are 'i//erent /ro$ i'enti/iers% The ke+0or's are the reser#ed words. The !eywords are identifiers but cannot be user defined. 5t is mandatory that all the !eywords should be in lower case letters. 6or example for) while) do) if) continue) brea! etc. There are 78 !eywords in C and 9: in C++. I'enti/ier can be defined as name of #ariable and some other program elements using the combination of following characters. ;lphabet: a to <) ; to = >umerals: ? to @ Anderscore: B

QAns Q4 Ans

Q2 Ans

Q6 Ans

SUBJECT: C++ (PGDCA/MSC-1)


Q5 Ans

2/62

.i//erentiate ,et0een co$&i)er an' inter&reter% A)so 3i(e t"e na$e o/ t"e (arious co$&i)ers o/ # an' #** Compiler and interpreter both are used to con#ert the highCle#el language program into the obDect source code. Eifferences are: Inter&reter6 C 5nterprets the program line by line. 5t is slow #o$&i)er6 7 Compiles the whole program at a time. 5t is fast. ;lso) interpreter can be more easily designed than compilers. >ame of the C and C++ compilers: &orland C) ;>F5 C) Turbo C. 4o0 # is 'i//erent /ro$ 9#**:% C++ is the superset of C. C is structured programming language where as C++ is obDect oriented programming language. Gany of the features a#ailable in C++ were not there in C. Eata is encapsulated in classes in C++) but not in C. 5nheritance is done in C++) and not in C Eata abstraction is a #ery important concept included in C++. &y the means of the data hiding we can protect the data. 6unctions cannot be o#erloaded in C) where as it is possible in C++. .e/ine arra+ 4o0 0i)) +ou 'ec)are an' store (a)ues in an arra+% ;rrays are subscripted #ariables. They are used to gi#e a common name to different memory locations of same data type. 5n an array) group of elements can share the same name. Fyntax to declare array is: C storgeclass datatype arrayname Hsi<eI+ ,xample int aH0I+ !"at is Proce'ure oriente' &ro3ra$$in3% Asing procedural programming we are able to combine returning seJuence of statements into one single place. Kith the use of procedures) programs can be written in more structured and error free manner. ; program can be #iewed as seJuence of procedure calls. The main program is responsible to pass data to indi#idual calls) data is processed by the procedures and the result in presented. Gain "rogram

Q8 Ans Q; Ans

Q1< Ans

"rocedure L "rocedure 8 Q11 Ans

"rocedure n

!"at is Neste' i/ state$ent% Khen we combine se#eral if statements) it is referred to as nested if statement. The control is mo#ed to next if statement only if the first condition is true and after performing the first statement the next if condition is chec!ed and if this condition is also true) then the second statement is performed. 5n case the first condition is false) the control s!ips the following statement of both if conditions and mo#es to the else part) if specified. Fyntax if-conditionL./ statement L if -condition 8./ statement 8 4 4 else /

SUBJECT: C++ (PGDCA/MSC-1)


statements 4 Q12 Ans

3/62

!"at 'o +ou $ean ,+ Mani&u)ators% These are special stream functions used to change the certain characteristics of input and output. These are used to format input and output streams. The header file used for them is 1iomanip.hM. Fome manipulators are: endl) hex) dec) oct) setw) setfill) setprecision) setiosflags etc. !"at is Pointer or In'irection o&erator% The pointer is used for indirect reference of a #ariable. 5t holds address of the #ariable) where it has been stored in memory. 6or pointer operator is used. Thats why it is also called as indirection operator. 5ts ad#antage is that it allows the user to access memory locations and is also used in call by reference in functions. !"at are t"e 'esira,)e c"aracteristics o/ a 9#**: &ro3ra$% ; C++ program must contain a class according to the concept of **"F. The data members should be declared as pri#ate or protected to ensure that there is e#en no accidental access to the data members of class. The methods should be declared as public. The definition of class consists of the following steps: i. Eefinition of class ii. The internal representation of data structures and storage iii. The internal implementation of the interface. i#. The external operations for accessing and manipulation the instance of the class. !"+ are /unctions create' in 9#**:% !"at is t"e 'i//erence ,et0een )i,rar+ /unctions an' user7'e/ine' /unctions% =unctions6 C ; function is a selfCcontained program segment that carries out some specific) wellCdefined tas!. ; function is also !nown as sub program that can be executed in the program. The functions are used to ma!e the program modular. 6unction basically are classified in two categories >i,rar+ /unctions6 7 These are needed in e#ery program. They are stored in the library files !nown as header files. Commonly used functions are printf-. and scanf-.. 5t is to be included at the beginning of the program using header file. ,xamples of library files: stdio.h) iostream.h etc. User 'e/ine' /unctions6 7 These functions are defined by the users according to their reJuirements. ,xample: functions to calculate factorial) prime number etc. .i//erentiate ,et0een &assin3 ar3u$ents ,+ re/erence an' ,+ (a)ue #a)) ,+ re/erence 5n C++) you can declare a function parameter to be a pointer. 6or example: #oid order -int ) int .+ 5t is used to declare the order function. ;ddresses of arguments are passed when function is called. order -intNp) intNJ.+ 5t is used to change the #alues of p and J in calling en#ironment. #a)) ,+ (a)ue ;rgumentCpassing mechanism where #ariables are passed as arguments to a function copying their #alues to corresponding function parameters without changing them in the calling en#ironment. .e/ine an' e?&)ain t"e /o))o0in36 @aA A,straction @,A Po)+$or&"is$

Q1Ans

Q14 Ans

Q12 Ans

Q16 Ans

Q15

SUBJECT: C++ (PGDCA/MSC-1)


Ans

4/62

A,straction6 5n **" data abstraction is defined as a collection of data and methods -functions.. 5n a class we define the data members as well as the functions) which can access and use these data members. Po)+$or&"is$6 5n **") polymorphism is defined as how to carry out different processing steps by a function ha#ing the same name. "olymorphism allows you to create definitions for operators and functions and at runCtime depending on the context a particular definition will be used. !"at is a structure% !"at is t"e 'i//erence ,et0een a structure an' a union% Ftructure constitutes a super data type) which represents se#eral different data types in a single unit. 5t is a collection of dissimilar data type. Ftructure can be initiali<ed if it is static or global. ; structure #ariable contains each of the named members) and its si<e is large enough to hold all the members. ; union contains one of the named members at a gi#en time and is large enough to hold the largest member. !"at is t"e &rece'ence o/ o&erators% "recedence is as follows Arit"$etic o&erators / O + C Gultiplication Ei#ision Godulus ;ddition Fubtraction

Q18 Ans

Q1; Ans

Be)ationa) o&erators 1 1( M M( (( Q( Less than Less than or eJual to Preater than Preater than or eJual to ,Jual to >ot eJual to

>o3ica) o&erators Q NN RR Q2< Ans Logical >ot Logical ;nd Logical *r

4o0 'o +ou 'ec)are a sin3)e an' a t0o 'i$ensiona) arra+% .ec)aration6 L dimension storageclass datatype arraynameHsi<eI+ ,xample static int aHL?I+ 8 dimension storageclass datatype arraynameHdimensionLIHdimension8I+ ,xample static char chH0IH0I+ Initia)iCation L dimension storageclass datatype arraynameHsi<eI ( /elementL) element8)S.) element n4+

SUBJECT: C++ (PGDCA/MSC-1)

5/62

,xample static int aHL?I ( /L)8)0)9)T)@?)C7)9)0)U4+ 8 dimension storageclass datatype arraynameHdimensionLIHdimension8I ( /elementL) element8S.) element n4+ ,xample static int chH8IH8I ( / /8)74) /9)L4 4+ Q21 Ans !"at is t+&e con(ersion% Type con#ersion is to con#ert the set of declared type of a #ariable to other reJuired type. Con#ersion can be di#ided in two ways. C Con#erting by assignment C Asing cast operator !"at 'o +ou $ean ,+ &re&rocessor% "reprocessor is generally used to include library files and also to define macros. &uilt in functions are the functions defined in the library files. These functions can be used in the program without need to define them in your program as they are defined in library files. ,.g. gets-.) puts- .) getch- . etc. !"at s&ecia) o&erators are use' in #**% Ans Two special operators introduced in C++) which are different than C are 5nsertion operator-11. ,xtraction operator-MM. cout is used to display an obDect onto the standard de#ice-monitor.. 5t uses the insertion operator. The syntax is : cout11#ariableL11#ariable8S cin is used to enter #alues from standard de#ice -!eyboard. in #ariables. The syntax is: cinMM#ariableLMM#ariable8S !"at are t"e a'(anta3es o/ usin3 i'enti/ier 0it" )on3 na$es% C++ allows using long names for identifiers. 5ts ad#antages are: 1 Long name describe identifier clearly. 2 Veadability and understandability of identifier is increased by using long names Is casca'in3 o/ in&ut an' out&ut o&erators &ossi,)e% I/ +es e?&)ain "o0% The multiple uses of insertion or extraction operators in one statement is called cascading. Cascading is possible in C++ 6or example Cascading of input using cin: cinMMaMMbMMc+ Cascading of output using cout: cout11a11b11c+ Gi(e so$e c"aracteristics o/ atoi@A /unction% Fome characteristics of atoi are: L. 5t con#erts string to integer. 8 5t is a utility function. 7 5t is defined in stdlib.h.

Q22 Ans

Q2-

Q24 Ans

Q22 Ans

Q26 Ans

SUBJECT: C++ (PGDCA/MSC-1)


Q25 Ans

6/62

4o0 'oes &ointer 0ork 0it" t0o7'i$ensiona) arra+% 5n twoCdimensional array) pointers contain address of first element i.e. is address of <ero th row and <eroth column assigned to pointer 5f we increment pointer) pointer will be incremented to next data in twoCdimensional arrays that is eJual to #alue. i.e. #alueH?IHLI because twoC dimensional array store data by row order. ,xample ptr(N#alueH?IH?I+ !"at is $eant ,+ 'ata "i'in3% Eata hiding pro#ides facility of exposing information as much is needed by the user. Eata hiding is implemented using abstraction and encapsulation. 5t can be implemented by using three accessCspecifiers: "ri#ate "ublic "rotected 5t is also called as data abstraction. !"at is enca&su)ation% 5t is a method to implement abstraction by wrapping up data and associated functions into a single unit. The single unit is called a class .The data will not be accessible to outer world. *nly member functions of class can access data. These functions pro#ide interface between obDect data and program. !"at is o,Dect oriente' &ro3ra$$in3% !"at is t"e 'i//erence ,et0een an o,Dect an' a c)ass% *bDect oriented programming treat data as a critical element in program de#elopment and does not flow freely around the system. 5t ties data more closely to functions that operate on it in a data structure called Class. *bDects are instances of Class. Class is a template from which obDects ta!e their shape. ; Class can ha#e more than one obDect. Collection of number of entities is called as obDects. Class is also defined as collection of data members and member functions. #once&ts o/ OOP are6 *bDects Classes Eata abstraction and ,ncapsulation 5nheritance "olymorphism Eynamic &inding Gessage "assing

Q28 Ans

Q2; Ans

Q-< Ans

Q-1 Ans

State t0o ru)es /or na$in3 i'enti/iers L. *nly alphabetic characters) digits and underscores are permitted 8. 5t should not begin with numeric data. 7. 6or using multiple word #ariables) underscore is used) as space is not allowed. 9. Eeclared !eywords cannot be used as #ariable names. #an a con'itiona) o&erator re&)ace an i/ state$ent a)0a+s% Wes. &y putting the conditional operator within parenthesis we can write as many conditions. E?a$&)e6 -aMb NNa Mc.Xcout11a: --bMc.Xcout11b:cout11c.+

Q-2 Ans

SUBJECT: C++ (PGDCA/MSC-1)


Q-Ans 4o0 0i)) +ou c)assi/+ o&erators in #**% O&erators in #** can ,e c)assi/ie' on t"e /o))o0in3 ,asis6 L. ;rithmetic operators 8. Velational operators 7. Comparison operators 9. &it wise operators 0. Anary operators U. Fpecial *perators li!e new) delete) scope resolution etc.

7/62

Q-4 Ans

!"at is t"e 'i//erence ,et0een E,F an' 9,:% 'b is in single Juotes so it is a character whereas 2b3 is in double Juotes) it is treated as string 'b would ta!e L byte whereas 2b3 would ta!e 8 bytes in memory as 2b3 also contains a null #alue. Ftrings are always terminated with a null character. !"at is a re/erence (aria,)e% 5t is new type of #ariable pro#ided by C++. 5t pro#ides facility of alias name or alternati#e name. 6or example: 5f we ma!e #ariable sum as reference #ariable to total) then sum and total can be interchangeably used to represent that #ariable. S+nta?6 Eatatype N referenceCname(#ariable name E?a$&)e6 float total(L??+ float Nsum(total+ .i//erentiate ,et0een a structure an' an arra+ Ftructure and array both are user defined data types. &ut structure is collection of dissimilar data type whereas array is collection of similar data type. Ftructures are records of userC defined data whereas arrays are subscripted #ariables. !"at are t"e (arious c"aracteristics o/ o,Dect oriente' )an3ua3es% *bDect oriented programming languages ha#e different characteristics from traditional procedural languages #"aracteristics o/ o,Dect oriente' )an3ua3es *bDects Classes Eata ;bstraction ,ncapsulation 5nheritance "olymorphism Eynamic &inding Gessage passing

Q-2 Ans

Q-6 Ans

Q-5 Ans

Q-8 Ans Q-; Ans

!"at is &ointer to a constant% int const ptr8(Nm+ here ptr8 is declared as pointer to constant. 5t can point to any #ariable of correct type) but the contents of what it points to cannot be changed. !"at are t"e (arious out&ut state$ents use' in #**% E?&)ain 0it" e?a$&)es cout6 5t can display data of any type. 5t can print integer) float) character) double type. 5t is a member of the iostream class. E?a$&)e6 cout11a11b+ &ut6 5t is used to display a line of text) character by character. 5t is a member of the ostream class E?a$&)e6 cout.put-ch.+

SUBJECT: C++ (PGDCA/MSC-1)


0rite6 The write-. function displays an entire line and has he following form. E?a$&)e6 cout.write-stringL) L?.+ Q4< Ans

8/62

4o0 can 0e a))ocate an' 'ea))ocate $e$or+ to an arra+% Gemory can be allocated to an array by using new operator and can be deallocated using delete operator. 5nt ptr(new intH8?I+ will allocate memory for 8? integers. EeleteHI ptr+ will deallocate memory . 4o0 'oes #** "e)& to &ro'uce /)e?i,)e an' e?tensi,)e so/t0are% Asing C++ we can create software that can represent real life entities. The systems design using C++ has open interfaces. 5t pro#ides facility of inheritance using which class can be extended by !eeping its pre#ious form as it is and adding new features to it. C++ is flexible because it industriali<es software de#elopment. #an 0e &ass entire structure as ar3u$ent to /unction% Wes entire structure can be passed as argument to a function and can also be returned. 6or example struct student / char name H8?I + int age) fee+ 4+ struct student functionL -struct student s. / CCCCCCCCCC CCCCCCCCCC 4

Q41 Ans

Q42 Ans

SUBJECT: C++ (PGDCA/MSC-1) Section A [QUESTIONS 1 TO -6]


Q1 Ans

9/62

2 Marks Questions [PAGE 5 TO 21]

!"at are t"e 'i//erent 'ata t+&es a(ai)a,)e in 9#**:% Khile programming) we store the #ariables in our computer$s memory. 6or it) the compiler needs to !now the datatype of the #ariable) so that it could allocate memory to the #ariables. Garious 'ata t+&es are6 1 #"aracter 'ata t+&e: any character belonging to the ;FC55 character set is considered as a character data type whose maximum si<e is : bits long. The 'char !eyword is used to represent character data type in C++. Character constants are always represented within single Juotes. ;n array of characters is called a string. 2 Inte3er 'ata: the !eyword 'int stands for the integer data type in C++ and its si<e is either LU or 78 bits. ; LUCbit integer falls in the range of C8L0 to 8L0 CL) while 78 bit integers fall in the range of C87L to 87L C L. %arious integer data types are: aA S"ort inte3er 'ata t+&e6 >ormally the short int is used to declare the short integer data type in C++. 5ts maximum si<e is LU bits long. 5t falls in the range between C78TU: to 78TUT. Khen we write int in our program) it is considered as short int. ,A >on3 inte3er 'ata t+&e: The long int stands for the long integer data type used in C++. 5ts si<e is 78 bits. 5t may fall in the range of C8L9T9:7U9: to 8L9T9:7U9T. - =)oatin3 &oint 'ata t+&e6 The numbers which are stored in the form of floating point representation are !nown as floating point numbers. They can be declared as 'float in C++ whose maximum si<e is a rational number approximately between C7.9,C7: to 7.9,+7: 4 .ou,)e 'ata t+&e6 'double is a !eyword that is used to represent double precision floating point numbers in C++. The si<e of double data type #aries from CL.T,C7?: to L.T+7?: 2 Goi'6 #oid is a special data type used in C++. Ases of #oid are: To specify the return type of a function when it is not returning any #alue. To indicate an empty argument list to a function. 5t is also used in context of pointers ,xample: #oid functionL-#oid.+ #oid p+ OB In "o0 $an+ 0a+s can 0e re&resent an inte3er% Inte3er 'ata: the !eyword 'int stands for the integer data type in C++ and its si<e is either LU or 78 bits. ; LUCbit integer falls in the range of C8 L0 to 8L0 CL) while 78 bit integers fall in the range of C87L to 87L C L. %arious integer data types are: aA S"ort inte3er 'ata t+&e6 >ormally the short int is used to declare the short integer data type in C++. 5ts maximum si<e is LU bits long. 5t falls in the range between C78TU: to 78TUT. Khen we write int in our program) it is considered as short int. ,A >on3 inte3er 'ata t+&e: The long int stands for the long integer data type used in C++. 5ts si<e is 78 bits. 5t may fall in the range of C8L9T9:7U9: to 8L9T9:7U9T.

Q2

!"at are &re &rocessors% !rite a &ro3ra$ to 'e/ine a $acro 0it" &ara$eters usin3 H'e/ine &re7&rocessor

SUBJECT: C++ (PGDCA/MSC-1)


Ans

10/62

"reprocessor is a directi#e that modifies the C++ source program according to conditions gi#en by users. To instruct the compiler that we are using a library defined function we specify the header file containing the prototype for the function related to their input or output. These header file are included into your source code using 2Y3 symbol and !nown as preprocessors directi#es. They ma!e the compiler to include the contents of specified file. Asing preprocessor we can also specify the macros. They commonly useable preprocessors are Yinclude and Ydefine. T"e &re&rocessor carries out t"e /o))o0in3 actions6 Veplacement of identifiers by some #alues. Conditional execution of parts of the source file. 5nclusion of other file. Venumbering of source file and renaming of the source file itself. Pro3ra$ 0it" 'e/inition o/ $acro 0it" &ara$eter6 Ydefine FZA;V, -x. x x Yinclude 1iostream.hM #oid main- . / int a(FZA;V, -0.+ int b(FZA;V,-U.+ cout11 a11b+ 4 !"at 'o +ou $ean ,+ $ani&u)ators% E?&)ain so$e in,ui)t IIO $ani&u)ators Ganipulator functions are special stream functions that change certain characteristics of the input and output. They change the format flags and #alues for a stream. They facilitate formatting the input and output streams. The input and output manipulators can be used in the program by including the file 1iomanip.hM. ,ndl. The endl is an output manipulator. 5t generate carriage return or line feed. Fetbase- .. 5t is used to con#ert the base of numeric #alue into another base. Eec [ decimal base -base(L?. Hex C hexadecimal base -base(LU. *ct [ octal base -base (:. Fetw - . The setw- . stands for set width. 5t is used to specify the minimum number of character positions on the output field a #ariable will consume. Fetfill- . The setfill- . manipulator function is used to specify a different character to fill the unused field width of the #alue. !"at are t"e 'i//erent contro) structure a(ai)a,)e in 9#**:% E?&)ain 0it" e?a$&)e Control statements are used to ma!e decision. These statements are reJuired to ta!e an action according to the condition. The #arious control statements are as under: C L. if statement 8. if [ else statement 7. nested if L. i/ state$ent :C ,xecutes the statements if condition is true. S+nta?6 7 if -condition. / statements+ 4 8. i/e)se state$ent6 7 ,xecutes the bloc! of statements if condition is true. *therwise execute else bloc!. if -condition. / statements+ 4 else

QAns

Q4 Ans

SUBJECT: C++ (PGDCA/MSC-1)


/

11/62

statements+ 4 7. Neste' i/ 67 ,xecutes one bloc! out of number of bloc!s of statements which specify the condition other wise executes else bloc! statements. if -condition. / statements+ 4 else if-condition. / statement+ 4 else / statements+ 4 #ase state$ents 67 These statements are used to ma!e decision from the number of choices. 5n 2C++3 case control instruction is the switch statement. S0itc" state$ent 6C switch statement pro#ide better alternati#e for series of if [else statements) because any part of the code can be executed on the #alue of an expression. S+nta?6 7 switch-expression. / case #alue: statementL+ case #alue: statement8: default: statements 4 Eefault statement is used as optional. Jranc"in3 state$ents: These statements transfer the control to another part of the program. There are three types of branching statement. -a. Continue statement -b. &rea! statement -c. Poto statement i. continue :C The continue statement ta!es the control at the beginning of the loop and remaining statements s!ipped and control mo#e to the last stub. ii. ,reak :C The brea! statement is used to terminate the loop or a seJuence of statement in a switch statement. ; brea! statement enforces immediate termination of program. iii. 3oto 67 The goto statement is used to alter the normal seJuence of program execution by transferring the control to some of the defined le#el in the program. S+nta? goto label+ label : statements+ Iterations state$entsI>oo& state$ents6 C Loops are used execute a set of statements repeatedly until desired condition is meet. There are different types of loops in C++ L. while 8. do while 7. for !"i)e )oo&6 7

SUBJECT: C++ (PGDCA/MSC-1)

12/62

This statement is used to execute the loop till the condition true. while -expression or condition. / statements 4 .o 0"i)e6 7 Ftatements will execute when the condition is true but in this loop the statements will execute first then condition chec!ed. do / statements 4while -expression.+ =or )oo&6 7 5n the for loop the initiali<ation ) condition and increment or decrement can be done at one place. for -initial #alue+ expression+ increment/decrement. / statements + 4 Q2 !rite a &ro3ra$ to ca)cu)ate t"e su$ o/ a)) o'' nu$,ers ,et0een 1 an' 1<<< Ans Yinclude1iostream.hM Yinclude1conio.hM #oid main- . / int i+ long int sum(?+ for-i(L+i1(L???+i+(8. sum+(i+ cout113Fum of odd numbers between L and L??? is : 211sum+ getch- .+ 4 Q6 !rite a &ro3ra$ to in&ut a 0or' .is&)a+ on screen E4e))oF as $an+ ti$es asK t"e nu$,er o/ a:s &resent in t"e 0or' Ans Yinclude1iostream.hM #oid main- . / char strH8?I+ int !+ cout113,nter a string3+ cinMMstr+ !(?+ while-strH!I Q(\?. / if-strH!I((a. cout11endl113hello3+ !+++ 4 4

Q5 Ans

!"+ 'o 0e use /unctions an' 0"at are its a'(anta3es% 6unctions are used to di#ide a program in sub parts. There are different ad#antages of using functions: 1 E//icienc+ o/ $aintenance o/ co'e The code written as the body of functions that ma!es the tas! simpler. Feparating the code into modular functions ma!es the program easier to design. 2 Ease o/ un'erstan'in3 The use of functions ma!es the program understand easily as each operation is placed in different function. ;nd it can be written or chec!ed immediately. E)i$ination o/ re'un'anc+ o/ co'e Asing this we dont ha#e any need to rewrite the code again and again to perform the same type of tas!. 4 Beusa,i)it+ o/ co'e

SUBJECT: C++ (PGDCA/MSC-1)

13/62

6unctions once defined can be used any number of times Dust by calling them by their name. Q8 Ans 4o0 &ara$eters can ,e &asse' to a /unction E?&)ain% To ma!e the communication between the calling and called functions) parameters can be passed to the functions. 6ormal parameters are passed to the userCdefined function. The communication can be one way or two way. 5f the function defined does not return any thing then it is oneCway communication. 5f the function returns some thing then it is twoCway communication. ,xample: int sJuare - int a. / statements+ CCCCCCCCC return + 4 Here sJuare is the userCdefined function getting one parameter of type int. The function is also returning a #alue of type int. Q; Ans !"at are stora3e c)asses% E?&)ain t"eir t+&es The storage class specifier refers to how widely it is !nown among a set of functions in a program. Ftorage class pro#ides information about its #isibility) lifetime and location. >ormally a #ariable can be declared as belonging to any one of the following groups: L. ;utomatic #ariable 8. Vegister #ariable 7. Ftatic #ariable 9. ,xternal #ariable Auto$atic (aria,)e6 These are also called local or internal #ariables. They are declared inside a function. They are referred to as automatic because their memory space is automatically allocated as the function is entered and released as soon as it lea#es. 5n other words) automatic #ariables are gi#en only temporary memory space. Their scope is within the function in which they are declared. Be3ister (aria,)e6 The only difference between automatic and register #ariables is that of their memory location. The register #ariables are stored in the C"A registers. Thus the time ta!en to access the register #ariables is much less than the memory #ariables. &ut only limited #ariables can be declared with register storage class. 5f there are not sufficient registers to hold these #ariables then they will be stored in memory) hence will be treated as automatic #ariables. Static (aria,)es6 Ftatic #ariables are defined within a function and they ha#e the same scope rules as that of automatic #ariables but in the case of static #ariables) the contents of the #ariables will be retained throughout the program. E?terna) (aria,)e: %ariables) which are declared outside the main) are called external #ariables. These #ariables will ha#e the same data type in main and other functions. The life of these #ariables is in whole program. 5t can be accessed in each and e#ery function of the program. !"at is recursion% !"+ recursion is use'% !rite a &ro3ra$ to ca)cu)ate su$ o/ /irst /i(e nu$,ers usin3 recursion ; function) which calls itself directly or indirectly again and again) is !nown as the recursi#e function. Vecursi#e functions are #ery useful while constructing the data structures li!e trees. The recursi#e function will be in#o!ed by itself as long as the gi#en condition is satisfied. Pro3ra$ to ca)cu)ate t"e su$ o/ /irst /i(e nu$,ers6 int sum-int x. / if -x((L.

Q1< Ans

SUBJECT: C++ (PGDCA/MSC-1)


return L+ else return - x+ sum-xCL..+ 4 #oid main- . / cout11 sum-0.+ getch- .+ 4 Q11 #reate a /unction to /in' 0"et"er t"e c"aracter is in u&&ercase or )o0ercase Ans Yinclude1stdio.hM Yinclude1conio.hM #oid letter-char.+ #oid main-. / char c+ clrscr-.+ cout113enter any letter3+ cinMMc+ letter-c.+ getch-.+ 4 #oid letter-char c. / if--cM$a$.NN-c1$<$.. cout11]letter is in lower case]+ else cout11]letter is in upper case]+ 4

14/62

Q12 !AP to &ass arra+ as &ara$eter in t"e /unction an' to /in' t"e 3reatest nu$,er /ro$ t"e )ist o/ arra+ Ans int greatest -int aH I ) int n . / int D ) max + max ( aH?I+ for - D(L+ D1n+D++. / if -max 1aHDI. max( aHDI+ 4 return max+ 4 #oid main - . / int a H 0? I) n ) D + cout113,nter the range3+ cinMM n+ for -D(?+D1n+ D++. / cout113,nter the array element 2+ cinMM aHDI+ 4 cout113The greatest element in array is3+ greatest- a) n.+ 4

Q1Ans

!AP to &ass a structure in t"e /unction as &ara$eter an' return t"e structure /ro$ t"e /unction struct complex / float real+ float imag+ 4+ complex add -complex a) complex b. / complex c+ c.real(a.real+b.real+ c.imag(a.imag+b.imag+ return c+ 4 #oid main- . / complex a)b)c+ cout113,nter the first complex number3+

SUBJECT: C++ (PGDCA/MSC-1)

15/62

Q14 Ans

cinMMa.realMMa.imag+ cout113,nter the second real number3+ cinMMb.realMMb.imag+ c(add-a)b.+ cout11endl113;ddition of two complex numbers3+ cout11c.real113 i 311c.imag+ 4 !"at is an arra+% !rite a &ro3ra$ to sort an arra+ in ascen'in3 or'er ;n array is collection of elements of homogeneous data type. ;ll the elements in array are referred with common name. ;n index or subscript is used to access the element in the array. Pro3ra$ to sort an arra+6 Yinclude1iostream.hM Yinclude1conio.hM #oid main- . / nt aHL?I) i) D) temp + for-i(?+i1L?+i++. / out113,nter the array element3+ cinMMaHiI+ 4 for-i(?+i1@+i++. / for-D(i+L+D1L?+D++. / if -aHiIMaHDI. / temp(aHiI+ aHiI(aHDI+ aHDI(temp+ 4 4 4 for-i(?+i1L?+i++. / cout11aHiI+ 4 4 Q12 !AP to 'is&)a+ t"e $atri? o/ t0o ,+ t0o Ans Yinclude1stdio.hM Yinclude1conio.hM #oid main-. / int aH8IH8I(//L)84)/8)744)i)D+ clrscr-.+ for-i(?+i18+i++. / for-D(?+D18+D++. / cout11],nter element for311 i+L113 row311D+L113 column3+ cinMMHiIHDI+ Q16 !AP to &er/or$ t"e $u)ti&)ication o/ t0o $atrices Ans Yinclude1iostream.hM Yinclude1conio.hM #oid main- . / int aH7IH7I) b H7I H7I) c H7I H7I) i) D) !+ cout113,nter the first array3+ for -i(?+i17+i++. for-D(?+D17+D++. cinMMaHiIHDI+ cout113,nter the second array3+ for -i(?+i17+i++. for-D(?+D17+D++. cinMMbHiIHDI+

SUBJECT: C++ (PGDCA/MSC-1)


4 4 for-i(?+i18+i++. / for-D(?+D18+D++. / cout11aHiIHDI.+ 4 cout11endl+ 4 getch-.+ 4 for-i(?+i17+i++. / for-D(?+D17+D++. / cHiIHDI(?+ for-!(?+!17+!++. cHiIHDI + ( aHiIH!I bH!IHDI+ 4 4 for-i(?+i17+i++. / cout11endl+ for-D(?+D17+D++. / cout113\t311cHiIHDI+ 4 4 getch- .+ 4

16/62

Q15 Ans

!"at is &ointer% !AP to 'is&)a+ t"e (a)ues o/ sin3)e 'i$ensiona) arra+ usin3 &ointer Pointer6 "ointer is an indirection operator) which refers to any other #ariable. "ointers are #ariables) which store the address of another #ariable. That #ariable may be a scalar -including another pointer.) or an aggregate -array or structure.. The pointer to obDect may be part of a larger obDect) such as a field of a structure or an element in an array. Pro3ra$ to s"o0 t"e e)e$ents o/ an arra+7usin3 &ointer6 Yinclude1iostream.hM Yinclude1conio.hM Ydefine G;^ L?? #oid show- int a) int n. / int D+ for-D(?+D1n+D++. cout11endl11 -a+D.+ 4 #oid main- . / int arrHG;^I) n) !+ cout113,nter the no. of elements to be entered in array3+ cinMM n+ cout113,nter the array3+ for-!(?+!1n+!++. / cout113,nter the array element3+ cinMMarrH!I+ 4 show-arr) n.+ getch- .+ 4 !"at is t"e 'i//erence ,et0een arra+ o/ &ointers an' &ointers to an arra+% ; pointer to an array contains the address of the first element. 5n a oneCdimensional array) the first element is NH?I. 5n twoCdimensional array) it is N#alueH?IH?I.

Q18 Ans

SUBJECT: C++ (PGDCA/MSC-1)

17/62

The address of the <eroth row and the <eroth column of the twoCdimensional array #alue is assigned to the pointer #ariable #alue. 6or example: int aH I H I+ int ptr+ ptr(NaH?IH?I+ // or ptr( a+ Arra+ o/ &ointers6 The pointer may also declared li!e any other data type. The declaration of an integer pointer array of si<e L? is int ptrHL?I+ Khere ptr is an array of pointers. 5t can hold the addresses of #arious arrays. Q1; Ans !"at is t"e 'i//erence ,et0een ca)) ,+ (a)ue an' ca)) ,+ re/erence% !AP to s0a& t"e (a)ue o/ t0o &ara$eters usin3 &ointers "ass by reference passes a pointer to the #alue. This allows the caller to modify the #ariable directly. "ass by #alue gi#es a copy of the #alue to the caller. This allows the caller to modify the #alue without modifying the #ariable. -5n other words) the caller simply cannot modify the #ariable) since it lac!s a reference to it.. Pro3ra$ to s0a& t0o nu$,ers usin3 &ointers6 Yinclude1iostream.hM Yinclude1conio.hM #oid swap- int x) y. / int temp+ temp( x+ x( y+ y(temp+ 4 #oid main- . / int first) second+ cout113,nter the first number3+ cinMMfirst+ cout113enter the second number3+ cinMMsecond+ swap-Nfirst) N second.+ // call by reference cout113;fter swapping #alues are :3+ cout1136irst : 211first+ cout113Fecond: 211second+ getch- .+ 4 Q2< !rite a /unction t"at 0i)) roun' /)oatin37&oint nu$,er to an in'icator 'eci$a) &)ace Ans Yinclude1manip.hM #oid main-. / float a(0)b(7)c d+ c(a/b+ cout113enter d3+ cinMMd+ cout11setprecision-d.11c+ Q21 !rite a c** &ro3ra$ to co$&ute t"e siCe o/ union Ans union stu / int a)b+ 4+ #oid main-. / union stu J+ int D+ D(si<eof-J.+

SUBJECT: C++ (PGDCA/MSC-1)


4 4 Q22 Ans cout11D+

18/62

!"at is a "ea'er /i)e% !"at is t"e &ur&ose o/ usin3 t"ese /i)es% ; file with extension .h is called header file. 5t is a library) which contains the definition of #arious functions. These functions assist the programmer to prepare the program in an efficient manner. These standard libraries come along with the complier as a utility software .The term include is used to include a certain library in your program. ;s these libraries contain se#eral inbuilt functions) we don$t need to redeclare these functions oursel#es. we can include a library and use its functions by Dust calling them with their appropriate parameter. Most # ** co$&)iers su&&ort t"e /o))o0in3 stan'ar' )i,rar+ /aci)ities6 L. *perations on characters 8. *perations on strings. 8. Gathematical operation 9. Ftorage allocation procedures 0. 5nput /*utput operations Q2- Usin3 &ointer 0rite a &ro3ra$ to a'' t0o $atri?es [IN ELAM] Ans Yinclude1iostream.hM Yinclude1conio.hM #oid main- . / int aH7IH7I) b H7I H7I) c H7I H7I) i) D) !+ int pLH7I) p8H7I) p7H7I+ cout113,nter the first array3+ for -i(?+i17+i++. for-D(?+D17+D++. cinMMaHiIHDI+ cout113,nter the second array3+ for -i(?+i17+i++. for-D(?+D17+D++. cinMMbHiIHDI+ pL(NaH?IH?I+ p8(NbH?IH?I+ p7(NcH?IH?I+ for-i(?+i17+i++. / for-D(?+D17+D++. / p7HiIHDI ( pLHiIHDI + p8HiIHDI+ 4 4 for-i(?+i17+i++. / cout11endl+ for-D(?+D17+D++. / cout113\t311cHiIHDI+ 4 4 getch- .+ 4 Q24 Pro3ra$ to con(ert 'eci$a) into "e?a'eci$a) Ans Y include 1iostram.hM Y include 1conio.hM Yinclude 1string.hM #oid main -. / long int n) m+ char resH8?I+ int r)i+ for -i (o+ i18?+c++. res HiI (\++ // to initiali<e string i(?+ cont11$ counter the number + cin MM n+ m(n+ while -m M?. / r( mOLU+ if -r1(a. / resHiI ( r +$?$ / resHiI( r+$?$+ 4 else / switch -a. / case L?: resHiI ($a$+ brea!+ case LL: resHiI ($b$ + brea!+ case L8+ resHiI ($c$ brea!+ caseL7: res HiI ($d$ brea! case L9: resHiI ($e$ brea! case L0: resHiI ($f$ brea! 4 4 i++i m/LU+ 4

SUBJECT: C++ (PGDCA/MSC-1)

19/62

straw -res.+ cout 11$ Hexadecimal eJui#alent of ]11n11 is 11 res+ getch -.+ 4 Q22 !AP to sort an arra+ usin3 &ointer Q26 !rite a &ro3ra$ to count nu$,er o/ (o0e)sK consonantsK ,)ank s&aces an' 0or's in a )ine o/ te?t Ans Yinclude1iostream.hM Yinclude1stdio.hM Yinclude1conio.hM #oid main-. / int cons(?) #ow(?) bsp(?) w(L) 5(?+ chat strH0?I+ cout113,nter a string3+ gets-str.+ while-strH5I Q(\?. / if--strH5IM(a NN strH5I1(<. RR-strH5IM(; NN strH5I1(=.. / if--strH5I ((a RR strH5I((e RR strH5I((i RR strH5I((o RR strH5I((u.RR-strH5I ((; RR strH5I((, RR strH5I((5 RR strH5I((* RR strH5I((A.. / #ow+++ 4 else cons+++ 4 4 else if- strH5I(( '. / bp+++ w+++ 4 5+++ 4 cout113>umber of #owels are311#ow+ cout11endl113>umber of consonants are311cons+ cout11endl113>umber of blan! spaces are 211bsp+ cout11endl113>umber of words are311w+ getch-.+ 4

Ans Y include1iostream.hM Yinclude1conio.hM Ydefine G;^ L?? #oid sort- int a) int n. / int i) temp) D+ for- i(n+iM?+iCC. / for- D(?+D1i+D++. / if -aHDIMaHD+LI. / temp( aHDI+ aHDI( aHD+LI+ aHD+LI(temp+ 4 4 4 4 #oid main- . / int arrHG;^I) n ) index+ cout113,nter the si<e of array3+ cinMMn+ for-index(?+index1n+index++. / cout113,nter the array elements3+ cinMMarrHindexI+ 4 sort- NarrH?I)n.+ // function called and reference to the array is passed cout113Forted array is 2+ for-index(?+index1n+index++. cout11endl11arrHindexI+ getch- .+ 4

Q25 Ans

E?&)ain I= State$ent in 'etai) SIMP>E I=

SUBJECT: C++ (PGDCA/MSC-1)


if -condition. / statements 4 i/ e)se if -Condition. / statement : 4 else / statements : 4 I/ )a''er if -Condition. / if -condition. / statements 4 else / statements 4 4 else / statements 4 Q28 Ans

20/62

!"at is re3ister stora3e c)ass% The #ariable) which reJuires to be processed more then other can be set as register storage class. 6or example the #ariable used as index #ariable in for loop may be set register storage class. e.g. #oid main-. / int aHL?I+ register int i+ for -i(? + i1L?+ i++. / cout 11 ,nter array element+ cin MM aHiI+ 4 for -i(?+ + i1L?+ i++. cout 11 end l11 aHiI+ 4 Q2; Pro3ra$ to a'' a)) o'' noMs ,et0een 1<71<<< Ans Q-< Pro3ra$ to $aintain stu'ent recor' usin3 structure Ans

SUBJECT: C++ (PGDCA/MSC-1)


#oid main -. / long int s(?) i+ for -i (LL + i1L??? i +(8. s+( i+ cont 11 ] sum is 11 s+ float ;#erage -int n. / int i) a+ float s(?+ for -i (o 11 ( n+ i ++. / cout 11 ,nter the number cin MM a+ s( s+a+ 4 s( s/n+ 4 s(s/n+ 4 #oid main -. / int n+ float a#g cout 11 ,nter the #alue of n+ cin MM n+ ;#g ( ;#erage -n.+ cout 11 ;#erage is 11 a#g + 4 Q-1 Pro3ra$ to &rint strin3 in re(erse or'er Ans Yinclude1string.hM #oid main-. / char nH8?I)nLH8?I+ int c(?)i+ clrscr-.+ cout11]enter string]+ gets-n.+ for-i(?+nHiIQ(>ALL+i++. / c+++ 4 for-c(cCL)i(?+cM(?+cCC)i++. / nLHiI(nHcI+ 4 nLHiI($\?$+ char p+ i(?+ while-nLHiIQ($\?$. / struct student / char name H8?I : int age + char sex + 4+ #oid showdata -student .:// "rototype #oid main -. / student s+ cut 11 ,nter name of student ]+ cin MM F. name + cout 11 ,nter age+ cinMM s.age+ cout 11 ,ntete Fex+ cin MM s. sex+ showdata -s. : // 6unction call getch -.+ 4 #oid showdata -student F . / cout 11 >ame : 11 s. name+ cout 11 endl11]age+]]11 F.age+ cout 11 endl11]Fex:]11 s. sex + 4

21/62

Q-2 !rite a &ro3ra$K 0"ic" so)(es t"e /o))o0in3 e?&ression6 @aA c1a*, @,A c1a7, @cA c1aN, @'A c1aI, Ans #oid main-. / int a)b)c+ cout113enter a and b3+ cinMMaMMb+ c(a+b+ cout11c+ c(aCb+ cout11c+ c(a b+ cout11c+ c(a/b+ cout11c+ 4

SUBJECT: C++ (PGDCA/MSC-1)


p(NnLHiI+ cout11 p+ i+++ p+++ 4 4 Q-Ans

22/62

!"at 'o +ou $ean ,+ strin3 "an')in3% E?&)ain a)) t"e strin3 "an')in3 /unctions 0it" e?a$&)es% Ftring library functions are the functions) which are used regularly and stored in library file and whene#er these functions are needed) you need to include the reJuired header file in your program. There are different types of functions Str)en@A6 This function is used to count the characters in a string. 5t calculate the length of the string. S+nta?6 strlen-array #ariable.+ strc&+@A6 This function copies the contents of one string into another S+nta?6 strcpy-target)source.+ strcat@A6 This function is used to concatenate the source string at the end of the target string. S+nta?6 strcat-target)source.+ strc$&@A6 This function compares the two strings to find out whether they are same or different. The two strings are compared character by character until there is a mismatch or end of the string. These function returns ? if both the strings are identical. S+nta?6 strcmp-stringL)string8.+ !rite (arious &ara'i3$sK too)sK notations an' 3ra&" use' in o,Dect oriente' s+ste$ 'e(e)o&$ent OB !"at are c"aracteristic o/ o,Dect oriente' )an3ua3es% .e/inition6 Asing obDect oriented programming language we can represent information as series of obDects. *bDect will be of class type. *nce class is created) any number of obDects of that class type can be created. PABA.IGMS6 L. ,mphasis is on data rather than procedure. 8. "rograms are di#ided into what are !nown as obDects. 7. Eata structures are designed such that they characteri<e the obDects. 9. 6unctions that operate on data of an obDect are tied together in the data structure. 0. Eata is hidden and cannot be accessed by external functions. U. *bDects may communicate with each other through functions. T. >ew data and functions can be easily added whene#er necessary. :. 5t follow bottom up approach in program design. TOO>S L.Vational rose 8.

Q-4

Ans

VeJisite pro

NOTATIONS AN. GBAP4 1 *bDect Eiagram 2 Ase case Eiagram - Collaboration Eiagram

SUBJECT: C++ (PGDCA/MSC-1)


4 2 6 5 8 Ftate Eiagram ;cti#ity Eiagram "hysical Eiagram Eeployment Eiagram Component Eiagram Q-6 !rite a &ro3ra$ to &rint t"e &asca) trian3)e Ans #oid main-. / int i)D)l)m)n+ cout113enter no of rows3 cinMM n+ m(L+ for-i(L+i1n+i++. / for-i(9?C7 l+iM?+iCC. cout113 2+ for-D(?+D1(l+D++. / if--D((?.RR -l((?.. m(L+ else m(-m -lCD+L../D+ cout11m+ 4 cout11endl+ 4 getch-.+ 4

23/62

Q-2 !rite a &ro3ra$ to 'is&)a+ t"e c"aracters )ine ,+ )ine Ans Yinclude1 fstream.hM Yinclude1string.hM int main-. / char stringH:?I+ cout 113enter string3+ cinMM string+ int len(strlen-string.+ fstream file+ fileopen-2T,^T3) ios::in R ios::out.+ for-int i(?+i1len+i++. file.put-stringHiI.+ file.see!g-?.+ char ch+ while-file. / file.get-ch.+ cout11ch+ 4 return ?+ 4

SUBJECT: C++ (PGDCA/MSC-1) Section J [QUESTIONS 1 TO 1;]


Q1 Ans

24/62

2 Marks Questions [PAGE 22 TO 22]

!"at is a constructor% #an t"ere ,e $ore t"an one constructor% ; constructor is a special member function for automatic initiali<ation of an obDect. Khene#er an obDect is created) the constructor will be executed automatically. 5t has the same name as that of class. 5t is declared with no return type. ; class may ha#e a number of constructors. They can be defined by #arying the number of parameters passed in the constructor. !"at are 'estructors% ; destructor is a function that automatically executes when an obDect is destroyed. 5t is executed when an instance of the class to which it belongs goes out of class or goes out of existence. Fome rules for writing a destructor function are: L. The name of destructor is the same as that of class. 8. The first character of name must be tilde -_. 7. 5t cannot be o#erloaded. 9. 5t has no return type. 0. 5t cannot accept any parameters. !"at is co&+ constructor% 5t is used when compiler has to create a temporary copy of a class obDect. The copy constructors are used in following situations L. The initiali<ation of an obDect by another obDect of same class. 8. Veturn of obDects as function #alue. 7. Ftating the obDect as by #alue parameters of a function. !"at are c)asses% 4o0 c)asses are 'i//erent /ro$ structures% ; class is a user defined data type) which holds both the data and functions. The internal data of a class is called member data and the functions are called member functions. The member functions mostly manipulate the internal data of a class. The member data of a class should not normally be addressed outside a member function. The #ariables of a class are called obDects or instances of a class. Ftructure contains one or more data item) which are grouped together as a single unit. *n the other hand class not only contain the data members but also the functions to manipulate that data. Fecondly) in a structure) all elements are public by default) while in a class they are pri#ate. .e/ine Enu$erate' 'ata t+&es ;n enumerated data type is userCdefined data type) which pro#ides a way for attaching names) thereby increasing comprehensibility of the code. The enum !eyword automatically enumerates a list of words by assigning them #alues ?)L)8 and so on. enum colour/red) green) blue) pin!4+ A /rien' /unction cannot ,e use' to o(er)oa' t"e assi3n$ent o&erator 1 E?&)ain 0"+% ;lthough the friend function cannot directly access the members that are declared as pri#ate) still the friend function has the right to access these members. 5n other words) there is nothing a class can hide from its friend. &ut the friend function is not within the scope of any class. ;nd it is defined out of class. ;lso when the function is called) it is called without any obDect reference. The only need is to pass the obDect of class as parameters in to the function. Fo it can not be used to o#erload(operator

Q2 Ans

QAns

Q4 Ans

Q2 Ans

Q6 Ans

SUBJECT: C++ (PGDCA/MSC-1)


Q5 Ans

25/62

!"at is $u)ti&)e in"eritance% Gultiple inheritance: multiple inheritance is the process of creating a new class from more than one base classes. S+nta?6 Class ; / C C C 4+ Class & / C C C 4+ Class C : public ;) public & / C C 4+

The class C is deri#ed from both classes ; and &. 5n multiple inheritance a class is deri#ed to inherit the properties of two or more parent classes. Gultiple inheritance can combine the beha#ior of multiple base classes in a single deri#ed class. 5t has ad#antages o#er single inheritance .5t can combine the beha#ior of multiple base classes in a single deri#ed class. 5t has ad#antages o#er single inheritance such as rich semantics and ability to directly express complex structures. Q8 Ans !rite a S"ort Note on O&erator o(er)oa'in3 The wor!ing of an operator can be redefined by using operator o#erloading .The operators) which already exist in a language) can only be used to ma!e language more natural to read and write. ,#en debugging of such codes are much easier. O&erator o(er)oa'in36 5t is accomplished by means of special function. The function we want to declare as operator o#erloading function must be of a class. The syntax is return type operator operator to be overloaded (parameters ..); The !eyword operator must be preceded by the return type of the functions which gi#es the compiler) the information that operator is being o#erloaded. 4o0 =i)e 4an')in3 is 'one in #**% 6ile is a collection of data or a set of characters. There are two types of files in C++. FeJuential and Vandom access. 5n seJuential files the data or text will be stored or read bac! seJuentially. 5n random access files) data can be accessed and processed randomly. T"e /o))o0in3 $et"o's are use' in #** to rea' an' 0rite /i)es6 ifstream [ To read a stream of obDect from a specified file. ofstream [ To write a stream of obDect on a specified file. T"e /o))o0in3 attri,utes are use' /or (arious /i)e o&erations6 ios :: in open a file for reading. ios :: out open a file for writing ios :: app append at end ios :: binary open in binary mode. !"at are t"e (arious access )a,e)s use' in t"e 'ec)aration o/ c)asses% T"ree t+&es o/ )a,e)s are use'6 L. public 8. pri#ate 7. protected !"at are &it/a))s o/ o&erator o(er)oa'in3 an' 'ata con(ersion% O&erator o(er)oa'in3 1 5t is not possible to o#erload all operators. 2 Fome programmers try to define e#erything as an operator so it is o#er utili<ed. - *perator o#erloading facility is not a#ailable in all type of languages li!e Da#a. .ata con(ersion

Q; Ans

Q1< Ans

Q11 Ans.

SUBJECT: C++ (PGDCA/MSC-1)

26/62

&y con#erting data from one type to another accuracy is reduced .5f we con#ert float data into an integer then rounding of all digits after decimal reduces accuracy. Q12 Ans !"at is nestin3 o/ c)asses% Class within class is called nested class Here class is declared as member of another class. The name of nested class is local to enclosing class. Class student / pri#ate char name H8?I int roll no + public : class date / pri#ate : int day) month) year+ public: 4+ // end of date class 4+ //end of student class !"at 'o +ou $ean ,+ o,Dect re/erence% C++ allows the use of a reference) which is simply another name of obDect that is being initiali<ed. Class o+ Class NoL(o+ Here oL is alternati#e name of o. !"at is )ate ,in'in3% !"at is ear)+ ,in'in3% 4o0 t"ese ,in'in3s are i$&)e$ente'% OB !"at is static &o)+$or&"is$% !"at is '+na$ic &o)+$or&"is$% Ear)+ ,in'in36 Choosing a function in normal way) during compilation time is called as ear)+ ,in'in3 or static ,in'in3 or static )inka3e or static Po)+$or&"is$ Euring compilation time) C++ compiler determines which function is used based on parameters passed to the function or function return type. The compiler then substitutes the correct function for each in#ocation. &y default) c++ follows early binding. C++ supports late binding also. Late binding is called as run ti$e ,in'in3 or e?ecution ti$e ,in'in3 or '+na$ic &o)+$or&"is$ >ate binding is implemented using #irtual function. !"at is "+,ri' in"eritance% 5t is combination of more than one inheritance. 5n following figure classL) class 8) class7 are related to each other using the concept of multile#el inheritance. Khereas class8) class 7) class 9 are related using the concept of multiple inheritance. Fo o#erall concept is of hybrid inheritance. &y combining all four classes we get hybrid inheritance ClassL

Q1Ans

Q14 Ans

Q12 Ans

class8

class7

Q16 Ans

Class9 4o0 &ointer to a c)ass is 'ec)are'% The pointer will hold address of obDect of class .The pointer to obDect of class can be accessed using following syntax: *bDectname CM membername(#ariable+

SUBJECT: C++ (PGDCA/MSC-1)


*r - *bDectname..membername(#ariable+ Q15 Ans 4o0 in"eritance 0orks in 'i//erent )a,e)s% E?&)ain 0it" suita,)e e?a$&)e In &u,)ic in"eritance6 ,ach public member in the base class is public in the deri#ed class. ,ach protected member in the base class is protected in the deri#ed class. ,ach pri#ate member in the base class is pri#ate in the deri#ed class. In &ri(ate in"eritance6 ,ach public member in the base class is pri#ate in the deri#ed class. ,ach protected member in the base class is pri#ate in the deri#ed class. ,ach pri#ate member in the base class is pri#ate in the deri#ed class. In &rotecte' in"eritance6 ,ach public member in the base class is public in the deri#ed class. ,ach protected member in the base class is protected in the deri#ed class. ,ach pri#ate member in the base class is pri#ate in the deri#ed class.

27/62

Q18 Ans

!"at is t"is &ointer% C++ uses a uniJue !eyword called 'this to represent an obDect that in#o!es a member function. this is a pointer that points to obDect for which this function was called. 6or example the function call ;. max-. will set the pointer to the address of the obDect ;. The starting address is the same as the address of the #ariable in the class structure. !"at is 'e/au)t constructor% The constructor without arguments is called as default constructor. 5t has no return type. 5t has same name as that of class. 5t is automatically called when obDect of classes is created. Class abc / pri#ate: CCCCCCCCC CCCCCCCCC public: abc-.+ CCCCCCCCCC CCCCCCCCC 4+ #oid main-. / abc-.+ CCCCCCC 4

Q1; Ans

SUBJECT: C++ (PGDCA/MSC-1) Section J [QUESTIONS 1 TO 2;] 2 Marks Questions [PAGE 26 TO 46]

28/62

Q1 !rite a &ro3ra$ to create a c)ass t"at can store t"e 'ata o/ t0o e$&)o+ees Ans Yinclude1iostream.hM Yinclude1conio.hM class employee/ char nameH8?I)designH8?I+ long int bsal) age+ public: #oid getdata- . / cout113,nter the name of employee3+ cinMMname+ cout113,nter the age of employee3+ cinMMage+ cout113,nter the designation3+ cinMMdesign+ cout113,nter the basic salary3+ cinMMbsal+ 4 #oid showdata- . / cout113\n>ame : 211name+ cout113\n ;ge : 211age+ cout113\n Eesignation : 211design+ cout113\n &asic Falary 311bsal+ 4 4+ #oid main- . / employee eL)e8+ eL.getdata- .+ e8.getdata- .+ eL.showdata - .+ e8.showdata- . + 4

Q2 !rite a &ro3ra$ usin3 c)asses to /in' t"e roots o/ Oua'ratic eOuation Ans Yinclude1iostream.hM Yinclude1conio.hM Yinclude1math.hM class Zuad/ int a)b)c+ float d) alpha) beta+ public: #oid getabc- . / cout113,nter the #alues of a) b N c3+ cinMMaMMbMMc+ 4 #oid calc- . / d(b b [ 9 a c + if -d((?. / cout113Voots are same 2+ alpha( Cb/8 a+ cout11alpha+ 4 else if -d1?. cout113Voots are imaginary3+ else / alpha( -Cb + sJrt-d.. /8 a+ beta( -Cb C sJrt-d.. /8 a+ cout113alpha : 211alpha+ cout11endl113beta : 211beta+ 4 4 4+ #oid main- . / Zuad obD+ obD.getabc- .+ obD.calc- .+ getch- .+ 4

Q- Usin3 o&erator o(er)oa'in3K 0rite a &ro3ra$ /or co$&)e? nu$,er

Q4 !rite a Pro3ra$ t"at re$o(es 'u&)icates /ro$ a strin3 )ist o/ n

SUBJECT: C++ (PGDCA/MSC-1)


o&eration )ike 9*: an' 979 Ans Yinclude1iostream.hM struct comp/ float real+ float imag+ 4+ comp operator+-comp a) comp b. / comp c+ c.real(a.real+b.real+ c.imag(a.imag+b.imag+ return -c .+ 4 comp operator [-comp a) comp b.+ / comp c+ c.real(a.real+b.real+ c.imag(a.imag+b.imag+ return - c .+ 4 #oid main- . / comp a)b)c+ cout113,nter Lst complex number3+ cinMMa.realMMa.imag+ cout113,nter 8nd complex number3+ cinMMb.realMMb.imag+ cout113Complex number operations3+ cout113 a C M add3113s C M subtract 2+ cout11endl113,nter your choice3+ char ch+ cinMMch+ switch - ch. / case 'a : c(a+b+ cout11endl113;ddition of two complex numbers is :3+ cout11c.real113+5311c.imag+ brea!+ case 's: c(aCb+ cout113subtraction of numbers is :3+ cout11c.real113+5311c.imag+ brea!+ 4 4 Q2 Ans

29/62

nu$,ers Ans Yinclude 1iostream .hM Yinclude 1conio.hM int n+ #oid dele -int a) int loc. / int i + fol -i(loc + i1nCL+ i++. aHiI (aHiI (aHi+LI+ 4 nCC+ #oid main -. / int a HL??I ) bHL??I) i) fi cout 11 ,nter the range in array ]+ cinMM n+ for -i(?+ i1L??+5++.//to initiali<e b array . bHiI(CL for -i(?+51n+ i++. / cout 11 ,nter array elements$ cinMM aHiI+ 4 i(bH?I) D(aH?I+ for -i(L+ i1n+c++. / for -i(?+ D1i+ D++. / if -aHiI( ( bHiI / dele -a)i.+ brea!+ 4 4 if -i ( ( D. bHDI ( aHiI+ 4 cout 11 after remo#al list is 11 endl+ for -i(o i1n+ i++. cout 11end l 11aHiI+ 4

!"at is In"eritance% !"at are its A'(anta3es an' t+&es% 5nheritance is the process of creating new classes) called deri#ed classes) from existing classes) the existing class is the base class. The deri#ed class inherits all the capabilities of the base class but can add properties of its own A'(anta3es6 C C"rotection can be increased in deri#ed classes. CThe deri#ed class can add data and function members to the class without affecting the

SUBJECT: C++ (PGDCA/MSC-1)


C&ase class beha#ior. CCode reusability T+&es6 C L. Fingle inheritance 8. Gultiple inheritance 7. Gultile#el inheritance 9. Hybrid inheritance. 4 Hierarchical inheritance Q6 Ans

30/62

!"at is t"e use o/ static ke+0or' in 9#**:% !"+ are static $e$,ers create' in a c)ass% The main characteristic of the static #ariables is that the static #ariables are automatically initiali<ed to <ero unless it has been initiali<ed by some other #alue explicitly. 5n C++) static member of a class can be categori<ed into two types) static data member and static member function. Khene#er a data or function member is declared as a static type) it belongs to a class) not to instances or obDects of the class. Static 'ata $e$,er6 Ftatic data members are data obDects that are common to all the obDects of a class. They exist only once in all obDects of this class. They are already created before the finite obDect of the respecti#e class. This property may lead a person to thin! that static data member is same as that of global) but it is not true. Ftatic data member may be declared as pri#ate) protected or public. Static $e$,er /unction6 The !eyword static is used to precede the member function to ma!e a member function static. The static function is a member function of a class and the static member function can manipulate only on static member data of the class. The static member function acts as global for members of class without affecting the rest of the program. The purpose of static member is to reduce the need for global #ariables.

Q5 Ans

!"at are t"e 'i//erent t+&es o/ /rien' /unctions% E?&)ain eac" 0it" e?a$&)e 6riend function is a special mechanism for letting nonC member functions access pri#ate data. ; friend function may be either declared or defined within scope of a class definition. The !eyword friend informs the compiler that it is not a member function of the class. ;ccessing pri#ate data by non member function through friend The friend function can access the pri#ate members of a class. Khen it is necessary to access the pri#ate data by nonC member functions) then a class may ha#e a friend function. E?a$&)e6 Yinclude1iostream.hM class sample / pri#ate : int x+ public: #oid getdata- . / cout113,nter the #alue of x3+ cinMMx+ 4 friend #oid display- sample.+ 4+ #oid display-sample abc. / cout113entered number is 211abc.x+ 4 #oid main- . /

SUBJECT: C++ (PGDCA/MSC-1)


sample obD+ obD.getdata- .+ display-obD.+ 4

31/62

=rien' /unction 0it" in)ine su,stitution6 5f a friend function is defined within the scope of the class definition) then the inline code substitution is automatically made. 5f it is defined outside the class definition) then it is reJuired to precede the return type with the !eyword inline in order to ma!e a inline code substitution. E?a$&)e6 Yinclude1iostream.hM class sample/ pri#ate : int x+ public: inline #oid getdata- . / cout113,nter the #alue of x3+ cinMMx+ 4 friend #oid display- sample.+ 4+ inline #oid display-sample abc. / cout113entered number is 211abc.x+ 4 #oid main- . / sample obD+ obD. getdata- .+ display-obD.+ 4 Q8 Ans !rite a &ro3ra$ to 3rant /rien's"i& to anot"er c)ass ; class can ha#e friendship with another class. Let there be two classes) first and second. 5f the class first grants its friendship with the other class second) then the pri#ate data members of the class first are permitted to be accessed by the public members of the class second. Yinclude1iostream.hM class first / friend class second+ pri#ate: int x+ public : #oid getdata- . / cout113enter the number3+ cinMMx+ 4 4+ class second / public: #oid disp -first a.+

SUBJECT: C++ (PGDCA/MSC-1)


4+ inline #oid second::disp-first a. / cout113,ntered number is 211a.x+ 4 #oid main- . / first obDx+ second obDy+ obDx.getdata- .+ obDy.disp-obDx.+ 4 Q; Ans

32/62

!rite a &ro3ra$ to 'e/ine t0o c)asses "a(in3 t"e sa$e /rien' ; nonCmember function may ha#e friendship with one or more classes. Khen a function has declared to ha#e friendship with more than one class) the friend classes should ha#e forward declaration. 5t implies that it needs to access the pri#ate members of both classes. E?a$&)e6 class second+//forward declaration class first / pri#ate: int x+ public: #oid getdata- . / cout113enter the #alue for x3+ cinMMx+ 4 #oid disp- . / cout113,ntered number is -x.311x+ 4 friend int sum-first ) second.+ 4+ class second/ pri#ate: int y+ public: #oid getdata- . / cout113,nter the #alue for y3+ cinMMy+ 4 #oid display- . / cout113,ntered number is -y. 211y+ 4 friend int sum-first) second.+ 4+ int sum- first one ) second two. / int c+ c(one.x+two.y+

SUBJECT: C++ (PGDCA/MSC-1)


return c+ 4 #oid main - . / first a+ second b+ a.getdata- .+ b.getdata- .+ a.disp- .+ b.display- .+ int c(sum-a)b.+ cout113Fum of the two pri#ate data #ariables is 211c+ 4 Q1< Ans

33/62

!"at is /unction o(er)oa'in3% 4o0 t"e co$&i)er 0i)) 'eci'e 0"ic" /unction to use% E?&)ain 0it" e?a$&)e 6unction o#erloading is a logical method of calling se#eral functions with different arguments and data types that perform basically identical things by the same name. The compiler classifies the o#erloaded function by its name and the number and type of arguments in the function declaration. The function declaration and definition is essential for each function with the same function name but different arguments and data types. 5n this example) a function ' ;dd ' is o#erloaded to find the sum of integer #ariables. if we pass aNb then ;dd-int )int. is executed. if we pass a)bNc then ;dd-int )int)int. is executed. 5f we pass a)b)c)d then ;dd-int )int)int)int. is executed. Yinclude1iostream.hM #oid ;dd-int)int.+ #oid ;dd-int)int)int.+ #oid ;dd-int)int)int)int.+ #oid main- . / int a(9)b(0)c(U)d(T+ ;dd-a)b.+ ;dd-a)b)c.+ ;dd-a)b)c)d.+ 4 #oid ;dd-int a)int b. / cout112sum of aNb(211a+b+ 4 #oid ;dd-int a)int b)int c. / cout112sum of a)b)c(211a+b+c + 4 #oid ;dd-int a)int b)int c)int d. / cout112a+b+c+d(211a+b+c+d+ 4

Q11 Ans

!"at is o&erator o(er)oa'in3% 4o0 9*: can ,e o(er)oa'e' 0it" $atri? a''ition% C++ has the ability to o#erload operators. *bDects deri#ed from composed types can accept operators) which would not be accepted otherwise) and we can e#en modify the effect of operators that they already admit. Here is a list of all the operators that can be o#erloaded: + C / ( 1 M +( C( ( /( 11 MM

SUBJECT: C++ (PGDCA/MSC-1)

34/62

11( MM( (( Q( 1( M( ++ CC O N ` Q R _ N( `( R( NN RR O( HI -. new delete To o#erload an operator we only need to write a class member function whose name is operator followed by the operator sign that we want to o#erload) following this prototype: type operator sign (parameters); Yinclude 1iostream.hM class dis / pri#ate : int feet + float inch+ public : dis- int f)float 5. / feet ( ft+ inch(5 + 4 #oid getdist- . / cout112,nter feet :3+ cinMMfeet+ cout112,nter inch :3+ cinMMinch+ 4 #oid showdist- . / cout 11feet112C311inch+ 4 dis operator + -dis.+ 4+ dis dis::operator + -dis d8. / int f(feet+d8.feet + float 5 (inch+d8.inch+ while-5M(L8. / 5 C (L8 + f++ + 4 return dis-f)5. 4 #oid main- . / dis distL + distL.getdist- . + dis dist8 + dist8.getdist- . + dis dist7 ( distL+dist8+ cout112dist(2+ dist7.showdist- . + 4 Q12 Ans !"at is sin3)e in"eritance% !rite a &ro3ra$ to s"o0 t"e conce&t o/ sin3)e In"eritance Sin3)e in"eritance6

SUBJECT: C++ (PGDCA/MSC-1)

35/62

Fingle inheritance is the process of creating new classes from an existing base class. The existing class is !nown as the direct base class and the newly created class is called as a singly deri#ed class. Fingle inheritance is the ability of a deri#ed class to inherit the member functions and #ariables of the existing base class. E?a$&)e6 Yinclude1iostream.hM class basicBinfo/ pri#ate: char nameH8?I+ long int rollno+ char sex+ public: #oid getdata- . / cout113,nter the name of student3+ cinMMname+ cout113,nter the rollno3+ cinMMrollno+ cout113,nter the sex3+ cinMMsex+ 4 #oid display- . / cout11name11\t11rollno11\t11age+ 4 4+ class physical :public basicBinfo/ pri#ate: float height) weight+ public: #oid getdata- . / basicBinfo::getdata- .+ cout113,nter height and weight3+ cinMMheight11weight+ 4 #oid display- . / basicBinfo::display- .+ cout11height11\t11weight+ 4 4+ #oid main- . / physical a+ a.getdata- .+ cout113\n>ame \t Vollno \t Fex \t Height \t Keight3+ a.display- .+ 4 Q1Ans !"at is In'irect Jase c)ass% E?&)ain 0it" E?a$&)e Eeri#ed class can itself ser#e as a base class. Khen a deri#ed class is declared as a base of another class) the newly deri#ed class inherits the properties of its base classes including its

SUBJECT: C++ (PGDCA/MSC-1)

36/62

data members and member functions. ; class is called as an indirect base if it is not a direct base) but is a base class of one of the classes mentioned in the base list. E?a$&)e6 class base ; / CCCCCCCCCCC CCCCCCCCCCC 4+ class deri#ed&:public base; / CCCCCCCCCCC CCCCCCCCCCC 4+ class deri#edC : public deri#ed& / CCCCCCCCCCC CCCCCCCCCCC 4+ deri#ed& is a base of the class deri#edC that is called as in indirect base. Mu)ti&)e in"eritance ; deri#ed class could inherit from more than one base classes. Khen this is done it is called multiple inheritance. E?a$&)e6 class ; / CCCCC 4+ class &/ CCCCCC 4+ class C:public ;) public &/ CCCCCCC 4+ The class C is deri#ed from both ; and &. Q14 Ans !"at is a$,i3uit+ in 9#**:% !rite a &ro3ra$ to s"o0 t"e a$,i3uit+ in $u)ti&)e in"eritance Khene#er a data member and member function are defined with the same name in both the base and the deri#ed classes) these names must be without ambiguity. The scope resolution operator may be used to refer to any base member explicitly. This allows access to a name that has been redefined in the deri#ed class. E?a$&)e to s"o0 "o0 a$,i3uit+ occurs in ,ot" ,ase c)ass an' 'eri(e' c)ass6 Yinclude1iostream.hM class base;/ public: int a+ 4+ class base&/ public : int a+ 4+

SUBJECT: C++ (PGDCA/MSC-1)


class deri#edC: public base;) base&/ public : int a+ 4+ #oid main- . / deri#edC obD+ obD.a(L?+// local to the deri#ed class 4

37/62

The obDect of deri#ed class can directly access to its own member rather than the members of the base classes. 5f one wants to access the members of base classes then the code can be written li!e #oid main- . / deri#edC obD+ obD.a(L?+ obD.base;::a(8?+ // accessing the base class ; member obD.base&::a(@?+// accessing the base class & member+ 4 Q12 Ans !"at are (irtua) /unctions% Gi(e t+&esK ru)es E?&)ain 0it" e?a$&)e 5t would be nice if the appropriate member function could be selected while the program is running. This is !nown as runtime polymorphism. C++ support a mechanism !nown as #irtual function to achie#e runtime polymorphism. ;t runtime) when it is !nown what class obDect are under consideration) the appropriate #ersion of the function is called. Fince the function is lin!ed with a particular class much later after the compilation) this binding is termed as late or dynamic binding. T+&es L. Fimple #irtual function-as shown in example below. 8. "ure #irtual function-; pure #irtual function is a #irtual function with no body.. Bu)es 1 %irtual !eyword is necessary with #irtual function. 2 5ts body can be outside or inside class. - "ure #irtual function is without body. //program for demonstration of #irtual function Yinclude1iostream.hM Yinclude1conio.hM class base;/ public: #irtual #oid display- . / cout113\n*ne3+ 4 4+ class deri#ed&:public base; / public: #irtual #oid display- . / cout113\nTwo3+ 4 4+ class deri#edC:public deri#ed&

SUBJECT: C++ (PGDCA/MSC-1)


/ public: #irtual #oid display - . / cout113\nThree3+ 4 4+ #oid main- . / base; obDa+ deri#ed& obDb+ deri#edC obDc+ base; ptrH7I+ ptrH?I(NobDa+ ptrHLI(NobDb+ ptrH8I(NobDc+ for-int i(?+i17+i++. / ptrHiICMdisplay- .+ 4 4 Q16 Ans

38/62

.escri,e t"e i$&ortance o/ 'estructor /unctions an' 0rite a &ro3ra$ t"at i))ustrates t"e 0orkin3 o/ 'estructor /unction ; destructor is a function that automatically executes when an obDect is destroyed. ; destructor function gets executed whene#er an instance of the class to which it belongs goes out of existence. The primary usage of the destructor function is to release space on the heap. PBOPEBTIES O= .ESTBU#TOB =UN#TION6 L. They ha#e same name as that of class. 8. These are automatically called when obDect is destroyed. 7. They ha#e no return type. 9. These cannot be declared static) const) #olatile. 0. They accept no arguments. Yinclude1conio.hM Yinclude1iostream.hM class ;&C/ public: ;&C- .//constructor / cout113\nClass initiali<ed3+ 4 _;&C- . / cout113\nEata deleted3+ 4 4+ #oid main- . / ;&C obD+ / ;&C obDL+ 4 4

SUBJECT: C++ (PGDCA/MSC-1)


Q15 Ans

39/62

!"at are in)ine /unctions% 4o0 are t"e+ create' in 9#**:% E?&)ain 0it" E?a$&)e The inline specifier is a hint to the compiler that inline substitution of the function body is to be preferred to the usual function call implementation. The si<e of the obDect code is considerably reduced with the use of inline function. The use of inline function increases the execution speed of program. Pro3ra$ to in&ut 'ate an' 'is&)a+ it usin3 in)ine /unctions6 Yinclude1iostream.hM Yinclude1conio.hM class date / pri#ate: int day)month)year+ public: #oid setin-int dayin)int monthin)int yearin.+ #oid show-.+ 4+ inline #oid date ::setin-int dayin)int monthin)int yearin. / day(dayin+ month(monthin+ year(yearin+4 inline #oid date::show-. / cout11day11]C]11month11]C]11year11endl+ 4 #oid main-. / date dL)d8)d7+ dL.setin-89)0)8???.+ d8.setin-7?)T)@:. + d7.setin-L7)T)@@.+ cout11]first date(]+ dL.show-.+ cout11]second date]+ d8.show-.+ cout11]third date]+ d7.show-.+ getch-.+ 4 !rite a &ro3ra$ to ca)cu)ate t"e area o/ a trian3)eK rectan3)eK circ)e an' sOuare usin3 in"eritance Class Common / protected : int a)b+ float res + 4+ Class triangle : public common / public : #oid getch - . / cout 11 2,nter base N height 2+ #oid showarea -. / res( 7.L9 a a+ cout 113 ;rea of cirlce ] 11 res 4 4+ class sJuare : public common / public #oid getside -. / cout 113 ,nter side for sJuare ] +

Q18 Ans

SUBJECT: C++ (PGDCA/MSC-1)


cin aMM b+ 4 #oid showarea - . / res (?.0 a b+ cout 11 2;rea of triangle311res+ 4 4+ Class rectangle : public common / public : #oid getlb -. / cout 11 2enter length N breadth of rectangle 2+ cinMM aMM bi+ 4 #oid showarea -. / res(a b+ cout 11 2;rea of Vectangle3 11 res 4 4+ class circle : public common / public : #oid gets -. / cout 113 ,nter radius ]+ cin MM ai+ Q1; Ans 4 !rite a &ro3ra$ to $aintain e$&)o+ee recor' Class employee / pri#ate : char name H8?I int age+ long int basic + public : #oid get data -. / #out 11,nter name of employee]+ cin MM name : cout 11 ,nter age N basic pay] cin MM name : cout 11 ],nter age N basic pay: cin M age MM baisc + 4 #oid Fhow -. / cout 11 >ame : 11 name + cout 11 endl 11 ]age + 11age+ cout 11 endl 11 Fex $11 sex + 4 4+ cin MM a+ 4 #oid show area -. / res (a a+ cout 11 2;rea of sJuare311 res+ 4 4+ #oid main -. / Triangle t + Circle c+ FJuare s+ Vectangle r + t.getch -. + t.showarea -.+ c.gets -.+ c.showarea -.+ s.getside -.+ s.showarea -.+ r.getlb -.+ r.showarea -.+ 4

40/62

SUBJECT: C++ (PGDCA/MSC-1)


%oid main -. / employee eL ) e< + el. getdata-.+ e<. getdata -.+ el . show -.+ e<. show -.+ 4 Q2< Ans !rite a &ro3ra$ to s"o0 o&erator o(er)oa'in3 Class area / pri#ate: int a) b+ float ar + #oid input -int aL. / a( aL+ 4 #oid input -int aL) int bL. / a(aL+ b(bL+ 4 ;rea operator ++ -. / ar ( 7.L9 a a+ 4 ;rea operator [ - . / ar ( a b+ return this+ 4 ;rea show-. / cout11ar+ 4 4+ %oid main -. / ;rea Vect ) Cir+ Vect.input -8?) 7?.+ Vect +++ Cir.input -L?. : Cir CC+ Vect . Fhow -.+ Cir . show - . + 4 Q21 Ans .i//erentiate ,et0een a)) t"e con(ersions 1 Jasic to c)ass t+&e

41/62

SUBJECT: C++ (PGDCA/MSC-1)

42/62

This con#ersion form basic to class type is easily carried type. 5t automatically done by the compiler with the help of inCbuilt routines or by applying typecasting. 5n this the leftChand operand of ( sign is always class type and rightChand operand is always basic type. The program gi#en below explains the con#ersion from basic to class type. 2 #)ass t+&e to ,asic 'ata t+&e 5n this type) left hand operand is always of basic data type and right [hand operand is always of class type. Khile carrying this con#ersion) the statement should satisfy the following conditions: L. The con#ersion function should not ha#e any argument. 8. Eo not mention return type 7. 5t should be a class member function. - One c)ass t+&e to anot"er c)ass t+&e Khen an obDect of one class is assigned to obDect of another class. 5t is necessary to gi#e clearCcut instructions to the compiler. How to ma!e con#ersion between these two user defined data type. The method must be instructed to compiler. There are two ways to con#ert obDect data type from one class to another. L. Eefine con#ersion operator function in source class 8. *ne argument constructor in a destination class Q22 Ans !rite a c** &ro3ra$ to e?tract a ro0 or co)u$n /ro$ a $atri? Yinclude1iostream.hM Yinclude1conio.hM #oid main-. / int aHL?IHL?I)m)n)i)D)p)J+ clrscr-.+ cout11]enter no of row and col]+ cinMMmMMn+ cout11]enter data in matrix]+ for-i(?+i1m+i++. for-D(?+D1n+D++. cinMMaHiIHDI+ cout11]display data in matrix]+ for-i(?+i1m+i++. / for-D(?+D1n+D++. / cout11]\t]11aHiIHDI+ 4 cout11]\n]+ 4 4 cout11]\nenter row to extract]+ cinMMp+ for-i(?+i1n+i++. cout11]\t]11aHpIHiI+ cout11]\nenter col to extract]+ cinMMJ+ for-i(?+i1m+i++. cout11]\n]11aHiIHJI+ getch-.+ 4

SUBJECT: C++ (PGDCA/MSC-1)


Q2Ans

43/62

!rite a &ro3ra$ to rea' a set o/ /)oatin3 &oint nu$,ers usin3 conce&t o/ o(er)oa'in3 Yinclude1iostream.hM Yinclude1conio.hM #oid getdata-int x)int y.+ #oid getdata-int x)int y)int <.+ #oid main-. / float i)D)!+ clrscr-.+ cout11]enter data]+ cinMMiMMDMM!+ getdata-i)D.+ getdata-i)D)!.+ getch-.+ 4 #oid getdata-int x)int y. / cout11]sum(]11x+y+ 4 #oid getdata-int x)int y)int <. / cout11]sum(]11x y <+ 4

Q24 Ans

!rite a #** &ro3ra$ t"at 'ec)ares a c)ass ca))e' e$&)o+ee 0it" 'ata $e$,ers6 na$eK /at"er na$eK resi'ence a''ress class employee / pri#ate: char nameHL?I+ char fnameH8?I+ char addressH8?I+ public: #oid getdata-.+ / cout113enter data3 cinMMname+ cinMMfname+ cinMMaddress+ 4 #oid display-. / cout11name+ cout11fname+ cout11address+ 4 4+ #oid main-. / employee e+

SUBJECT: C++ (PGDCA/MSC-1)


clrscr-.+ e.getdata-.+ e. display-.+ getch-.+ 4 Q22 Ans !"at are 'i//erent t+&es o/ $e$,ers"i& /unctions% E?&)ain structure o/ c)ass Me$,ers"i& /unctions: L. Constructor 8. 6riend function 7. Eestructor. 9. Ftatic member function 0. %irtual function U. 5nline member function STBU#TUBE O= #>ASS Class 1classnameM / pri#ate: datamember L+ datamember 8+ datamember 7+ public: member functionL-.+ member function8-.+ member function7-.+ 4+

44/62

Q26 Ans

4o0 constructors an' 'estructors can ,e in"erite'% 5f any base class contains a constructor with one or more arguments) then it is mandatory for deri#ed class to ha#e a constructor and pass arguments to base class constructors. Khile applying inheritance we usually create obDects using deri#ed class. Thus it ma!es sense for the deri#ed class to pass arguments to base class constructor. Khen both deri#ed and base class contains constructors) the base class constructor is executed first and then constructor in deri#ed class is executed. The constructor of the deri#ed class recei#es the entire list of #alues as its arguments and passes them on to the base constructors in the order in which they are declared in the deri#ed class. The base constructors are called and executed before the statements in the body of deri#ed constructor. Genera) =or$ o/ 'eri(e' constructor6 &aseL-arglistL. &ase8-arglist8. SSSSSS base>-arglist>. / // body of deri#ed constructor 4 ,xample: Yinclude 1iostreamM using namespace std+ class alpha / int x+ public: alpha-int 5. /

SUBJECT: C++ (PGDCA/MSC-1)


x ( i+ cout11 3alpha initiali<ed \n3+ 4 #oid showBx-#oid. / cout11 2x ( 211x 11 2\n3+ 4 4+ class beta / float y+ public: beta-float D. / y ( D+ cout11 2 beta initiali<ed \n3+ 4 #oid showBy-#oid. / cout11 2 y ( 2 11y 11 2\n3+ 4 4+ class gamma: public beta) public alpha / int m) n+ public: gamma-int a) float b) int c) int d.: alpha-a.) beta-b. / m ( c+ n ( d+ cout11 2gamma initiali<ed \n3+ 4 #oid showBmn-#oid. / cout11 2 m ( 211m 113\n3+ cout113 n ( 211n 113\n3+ 4 4+ int main- . / gamma g-0) L?.T0) 8?) 7?.+ cout11 2\n3+ g.showBx- .+ g.showBy- .+ g.showBmn- .+ return ?+ 4 Q25 Ans

45/62

#an 0e &ass entire structure as ar3u$ent to /unction% Wes) entire structure can be passed as argument to a function and can also be returned. 6or example struct student /

SUBJECT: C++ (PGDCA/MSC-1)


char name H8?I + int age + int fee+ 4+ struct student sH I+ #oid main-. / CCCCCCCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCCCCCCC fi -struct student sH I . 4 struct student fi -struct student sH I . / C C C C 4

46/62

Q28 Ans

Usin3 o&erator o(er)oa'in3K 0rite a &ro3ra$ /or /)oatin3 &oint nu$,er o&eration )ike 9*: an' 979 Yinclude1iostream.hM struct complex / float real+ float imag+ 4+ complex operator +-complex a) complex b. / complex c+ c.real(a.real+b.real+ c.imag(a.imag+b.imag+ return -c .+ 4 complex operator [-complex a) complex b.+ / complex c+ c.real(a.real+b.real+ c.imag(a.imag+b.imag+ return - c .+ 4 #oid main- . / complex a)b)c+ cout113,nter the first complex number3+ cinMMa.realMMa.imag+ cout113,nter the second complex number3+

SUBJECT: C++ (PGDCA/MSC-1)


cinMMb.realMMb.imag+ cout113\nComplex number operations3+ cout11endl113 a C M add311endl113s C M subtract 2+ cout11endl113,nter your choice3+ char ch+ cinMMch+ switch - ch. / case 'a : c(a+b+ cout11endl113;ddition of two complex numbers is :3+ cout11c.real113+5311c.imag+ brea!+ case 's: c(aCb+ cout11endl113subtraction of two complex numbers is :3+ cout11c.real113+5311c.imag+ brea!+ 4 4 Q2; Ans

47/62

.i//erentiate ,et0een a,straction an' 'ata "i'in3 !"+ c)asses in #** are a,stract% **" encapsulates data and functions into pac!ages called obDects. The data N functions of an obDect are intimately tied together. *bDects ha#e the property of information hiding. This means that although obDects may !now how to communicate with each other) they normally do not !now how other obDects are implemented. That is) implementation details are hidden within the obDects themsel#es. ;bstraction is #ery close to data hiding. ;bstraction refers to the act of representing essential features without including the bac!ground details or explanations. Eata abstraction is concerned with separation the beha#iour of data obDect from its representation or implementation. A,stract c)ass6 ;n abstract class is one that is not used to create obDect. Classes that declare a pure #irtual function is called an abstract class. 5t is used as a base class for deri#ing. 5t defines properties common to other classes deri#ed from it. Fince an abstract class contains one or more functions for which there is no definition) no obDects can be created using an abstract class.

SUBJECT: C++ (PGDCA/MSC-1) Section # [QUESTIONS 1 TO -<]


Q1 Ans

48/62

2 Marks Questions [PAGE 45 TO 4;]

!"at are t"e 'i//erent /i)e $o'es% T"ere are t"ree /i)e o&enin3 $o'es T"ese are6 Vead mode Krite mode ;ppend mode %arious streams are used to open the files in such modes) these are: ios :: in:C 6or read mode ios :: out:C 6or writing in a file ios :: app:C ;ppend at end of file ios::ate:C Poto end of file on opening. The file can also be set to be a binary file by using binary !eyword as C ios :: binary !"at is use o/ re'irection o&erator% The 11 and MM are used as redirection operators. These operators accept output from one stream that output will act as input to other stream. !"at is a strea$% Strea$6 5t is defined as collection of bytes. 5t acts either as a source from which the input data can be obtained or as a destination to which the output data can be sent. The source stream that pro#ides data to program is called as in&ut strea$ and destination stream that recei#es output from program is called as out&ut strea$ !"at is Ju//er% 5t is a temporary memory used to store data. 6stream class inherits two buffers one for input and another for output) and synchroni<es the mo#ement of the file pointers on these buffers. !"at are t"e /unctions a(ai)a,)e in #** to $ani&u)ate t"e /i)e &ointers% E?&)ain

Q2 Ans QAns

Q4 Ans Q2

Ans

O&en @A6 This is the function used to open a file. ; string parameter) which is actually the name of the file to be opened) is passed to the function.
#)ose @A6 This is the function used to close the already opened file. Eo/ @A6 this function is used to chec! whether a file pointer has reached at end of the file. =ai) @A6 The function return true if it failed to open the file reJuested.

Q6 Ans

!"at is a &riorit+ Oueue% "riority Jueues are essentially a list of items in which each item has a priority associated with it. The priorities are associated depending on preference rules. Eifferent items ha#e different priorities to them. ;n item ha#ing higher priority is gi#en preference o#er lower priority. "riority Jueues are generally used by the operating system to manage #arious resources such as printer and processor. 4o0 is t"e $i' &oint in a ,inar+ tree ca)cu)ate'% Voot of the binary tree is considered to be the mid point of the tree. !"at is an arra+% 4o0 arra+ is store' in $e$or+% ;rray is collection of homogeneous data elements. They are stored in continuous memory locations. They are accessed by using index #alue. 5nt aH0I+ L8 9 90 UT U: L??? L??8 L??9 L??U L??:

Q5 Ans Q8 Ans

SUBJECT: C++ (PGDCA/MSC-1)

49/62

L??? is the location of the first element of the array. ;s the int data type ta!es two bytes of the memory so the next element is stored at L??8 and so on. Q; Ans .e/ine $u)ti'i$ensiona) arra+ Gultidimensional arrays can be defined as two or more arrays clubbed together. The array that is grouped together can be two dimensional in nature or more. ;n example of the two dimensional array is the matrix .i//erentiate ,et0een structure' an' $o'u)ar &ro3ra$$in3 Khen a monolith software is di#ided into modules is called modular programming. 5t is easy to sol#e a smaller problem than a bigger problem. ;ll the modules are combined to sol#e a bigger problem. ; structured approach follows the concept of coupling) cohesion) information hiding) E6Es etc. !"at is 3ar,a3e co))ection% The operating system of a computer may periodically collect all the deleted spaces onto the free storage list. ;ny techniJue) which does this collection) is called Parbage Collection. T"is co))ection can ,e 'one in t0o &asses6 Markin3 &"ase6 5n this phase all the allocated bloc! are tagged. #o))ection P"ase6 5n this phase all the untagged bloc!s are stored into free list. Gi(e t0o a&&)ications o/ ,inar+ tree User inter/ace6 The best example for this is file system organi<ation and windows graphical interface. .ata,ase S+ste$6 &alanced search trees are good in situations that reJuire both seJuential efficiency and random access while performing insertion and deletion. !"at 'o +ou $ean ,+ circu)ar Oueue% ; circular Jueue is the same as a Jueue but the front and rear ends of a Jueue are Doined together to form a circular ring. !"at is (a)ue o/ /o))o0in3 &ost/i? e?&ression% 2K 4K 6K *K NK 4K ;K -K IK *K N 70?. .e/ine AG> tree ; binary search tree in which the difference of heights of the right and left subCtrees of any node is less than or eJual to one is !nown as ;%L tree. The name is deri#ed from the names of in#entors who are ;delsonC%els!ii and Landi. !"at 'o +ou $ean ,+ s&arse $atri?% ;n m x n matrix is said to be sparse if many of its elements are ?. ; matrix that is not sparse is called dense matrix. !"at is a stack% ; stac! is a list of elements in which an element may be inserted or deleted only at one end) called the top of the stoc!. .e/ine Oueue ; Jueue is a linear list of elements in which deletions can ta!e place only at one end) called the 'front N insertions can ta!e place only at the other end called the 'rear.

Q1< Ans

Q11 Ans

Q12 Ans

Q1Ans Q14 Ans Q12 Ans

Q16 Ans Q15. Ans

Q18 Ans

SUBJECT: C++ (PGDCA/MSC-1)


Q1;

50/62

Ans

!"at is a )inke' )ist% ; lin!ed list or oneCway list is a linear collection of data elements) called nodes) where the linear order is gi#en by means of pointers. ,ach node is di#ided into 8 parts. The first part contains the information of the element N the second part called the lin! field) contains the address of the next node in the list. !"at is ,inar+ searc" tree% ; binary tree in which all elements in the left sub tree of a node are less than the contents of root N all elements in the right sub tree are greater than or eJual to the contents of the root. Fuch a tree is called a binary search tree. !"at are t"e a&&)ications o/ ,inar+ trees% ; binary tree is a useful data structure when twoC way decisions must be made at each point in a process. ,.g. Fuppose that we want to find all duplicates in a list of numbers. The no. of comparisons may be reduced by placing the first number in the root. ,ach successi#e node is compared to the root) if it matches) we ha#e a duplicate of a number is lesser) we examine the left sub tree) else if it is larger) we examine the right sub tree. !"at is t"e )e(e) P "ei3"t o/ a ,inar+ tree% >e(e)6 The le#el of any mode is eJual to length of its path from root to the mode: The root of any tree has le#el eJual to <ero. 4ei3"t6 5t is eJual to one + maximum le#el in a tree. !"at is a 'ata structure% The logical or mathematical model of a particular organi<ation of data is called a data structure. .i//erentiate ,et0een )inear P non7)inear 'ata structure 1 >inear .ata Structure6 ; data structure is said be linear if its elements are stored seJuentially in the form of a linear list e.g. stac!s) lin!ed lists. 2 Non7)inear .ata structure6 ; data structure is said to be nonClinear if its elements are not stored seJuentially in the form of linear list e.g. trees N graphs. !"at are t"e a&&)ications o/ stacks% Asing stac!s) we can perform the process of recursion. Ftac!s are used in recursion to fetch an element from top one by one. The other application of stac! is calculation of postfix expression where each operator is fetched one by one. !"at are t"e a&&)ications o/ Oueues% *ne of the important areas to which Jueues can be applied is that of simulation. 5t is the process of forming an abstract model from a real situation in order to understand the impact of modifications N the effect of introducing #arious strategies on the situation. The maDor ad#antage of simulation is that it allows experimentation without modifying the real situation. ;reas such as military operations are safer to simulate.

Q2< Ans

Q21 Ans

Q22 Ans

Q2Ans Q24 Ans

Q22 Ans

Q26 Ans

Q25 Ans Q28 Ans

!"at is 'eOueue% ; deJueue also !nown as double ended Jueue is a lin! of Jueues in which elements can be added or remo#ed from at either end but not in the middle. !"at is ti$e P s&ace co$&)e?it+% Ti$e co$&)e?it+ is related to the performance reJuirements of an algorithm.

SUBJECT: C++ (PGDCA/MSC-1)


S&ace co$&)e?it+ is the amount of memory it needs to run to completion. Q2; Ans Q-< Ans

51/62

!"at are &ri$iti(e 'ata structures% These are the data structures that are directly operated upon by machine le#el instructions. ,xamples are integers) real numbers) characters) logical data item etc. !"at is a 'ou,)+ )inke' )ist% ; singly lin!ed list can mo#e only in one direction in certain applications) it is sometimes reJuired that the list be tra#ersed in either a forward or re#erse direction. This property of a lin!ed list implies that each mode must contain two lin! fields instead of one. The lin!s are used to denote the predecessor N successor of a mode. The lin! denoting the predecessor N of a node is called the left lin! N that de#oting its successor is called the right lin!. ; list containing this type of mode is called a doubly lin!ed list.

SUBJECT: C++ (PGDCA/MSC-1)

52/62

Section # [QUESTIONS 1 TO 2<]


Q1 Ans

2 Marks Questions [PAGE 2< TO 6<]

4o0 =i)e 4an')in3 is 'one in #**% 6ile is a collection of data or a set of characters. There are two types of files in C++. FeJuential and random access. 5n seJuential files the data or text will be stored or read bac! seJuentially. 5n random access files) data can be accessed and processed randomly. The handle file fstream in supports the input/outs stream processing techniJues. The =o))o0in3 $et"o's are use' in #** to rea' an' 0rite /i)es6 I/ strea$ [ To read a stream of obDect from a specified file. of stream [ to write a stream of obDect on a specified file. The following attributes are used for #arious file operations. ios :: in open a file for reading. ios :: out open a file for writing ios :: app append at end ios :: binary open in binary mode.

Q2 Ans

E?&)ain t"e /o))o0in3 /unctions

aA Eo/ @A6 5t is function to chec! whether a file pointer has reached the end of file character or not. 5t has then the function return non <ero else return ?. ,A =ai) @A6 5t is used to chec! if file has been opened successfully. 5f it fails then it return non <ero character. cA Ja' @A6 5t return non <ero when in#alid file operation has been attempted. 'A Goo' @A: 5t is function to chec! whether the pre#ious file operation has been successfully or not. Q!"at is a ran'o$ access /i)e% E?&)ain t"e s+ntactic ru)e /or t"e /o))o0in3 ran'o$ access /i)e $e$,er /unction% aA seek& ,A seek3 cA te))3 'A te))& BAN.OM =I>E6 5n random access file the file pointer can be mo#ed to any location in the file instead of mo#ing it seJuentially. This approach is used with database files. SEEQP6 Go#es put pointer to specified location. ,.g. infile.see!p-L?.+ 5t will mo#e pointer to L? number byte. 5t can ta!e 8 arguments also. Fee!p-offset)refposition.+ SEEQG6 Go#es get pointer to specified location. ,.g. infile.see!g-L?.+ 5t can ta!e 8 arguments also. Fee!g-offset)refposition.+

Ans

SUBJECT: C++ (PGDCA/MSC-1)


TE>>G6 Pi#es the current position of get pointer. ,.g. ofstream fileout+ fileout.open-2hello3)ios::app.+ int p(fileout.tellg-.+ TE>>P6 Pi#en the current position of get pointer. ,.g. ofstream fileout+ fileout.open-2hello3)ios::app.+ int p(fileout.tellp-.+ Q4 Ans

53/62

!rite an a)3orit"$ /or Ju,,)e sort P e?&)ain 0it" an e?a$&)e ;lgorithm &A&&L, -E;T;) >. Here E;T; is an array with n elements. This algorithm sorts the elements in E;T;. L. 8. 7. Vepeat steps 8 N 7 for ! ( 5 to >C5 Fet "TV: ( L H5nitiali<es pass pointerI Vepeat while "TV a >Cb H,xecute passI a. 5f E;T; H"TVI M E;T; H"TV +LI) then interchange E;T; H"TVI N E;T; H"TV+LI H,nd of 5f structureI b. Fet "TV: ( "TV+L H,nd of inner loopI H,nd of step L outer loopI ,xit ,xample: 78 ;L 0L ;8 8T ;7 :0 ;9 UU ;0 87 ;U L7 ;T 0T ;:

9.

a. b. c. d. e. f. g.

Compare ;LN ;8: 78 10L c no change ;8N;7: 0L M 8T) interchanging 0L N 8T ;7N;9 : no change ;9N;0: :0 M UU) interchange :0 N UU ;0N;U: :0 M 87) interchange 87 N :0 ;UN;T: :0 M L7) interchange L7 N :0 ;TN;:: :0 M 0T) interchange 0T N :0 This is pass L Fimilarly) in e#ery pass the greater element will be mo#ed towards the end. Fince the array has : elements) it is sorted after the se#enth pass i.e. -nCL. in pass.

Q2 Ans

!rite non7recursi(e P recursi(e &roce'ures to /in' t"e /actoria) o/ a 3i(en nu$,er "rocedure: 6;CT*V5;L -6;CT) >. This procedure calculates >Q N returns the #alue of the #ariable 6;CT in a nonCrecursi#e manner. L. 8. 7. 9. 5f >(?) then set 6;CT:(LNVeturn. Fet 6;CT: (L H5nitiali<es 6;CT for roopI Vepeat for b ( 5 to > Fet 6;CT: ( b 6;CT H,nd of roopI Veturn

SUBJECT: C++ (PGDCA/MSC-1)

54/62

"rocedure: 6;CT*V5;L -6;CT) >. This procedure ultimate >Q N returns the #alue in the #ariable 6;CT in a recursi#e manner. L. 8. 7. 9. Q6 Ans 5f >(?) then Fet 6;CT: ( L N Veturn Call 6;CT*V5;L -6;CT) >CL. Fet 6;CT ( > 6;CT Veturn.

E?&)ain t"e ,asic o&erations on stack !rite &roce'ures to i$&)e$ent t"ese o&erations ; stac! is a list of elements in which an element may be inserted or deleted only at one end called the top of the stac!. T"e t0o ,asic o&erations &er/or$e' on stacks are6 iA Pus"6 is the term used to insert an element into a stac!. iiA Po&6 is the term used to delete an element from stac!. Proce'ure6 "AFH -FT;Cb) T*") G;^FTb) 5T,G. This procedure pushes an 5T,G on to a stac!. L. HFtac! already filledI 5f T*"(G;^FTb) than print: *%,V6L*K N return. 8. Fet T*": ( T*" + L H5ncreases T*" by LII 7. Fet FT;Cb HT*"I: ( 5T,G H5nserts 5T,G in new T*" positionI. 9. ,xit Proce'ure6 "*" -FT;Cb) T*") 5T,G. This procedure deletes the top element of FT;Cb N assigns it to the #ariable 5T,G. L. HFtac! has an item to be remo#edXI 5f T*" (?) then "rint A>E,V6L*K N Veturn. 8. Fet 5T,G: (FT;Cb HT*"I. H;ssigns top element t itemI 7. Fet T*": ( T*"CL HEecreases T*" by LI
9. Veturn.

Q5 Ans

!rite an a)3orit"$ /or e(a)uatin3 a &ost/i? e?&ression 6ollowing algorithm uses a stac! to calculate postfix expression. Fuppose " is an arithmetic expression written in postfix notation. The following algorithm) which uses a FT;Cb to hold operands) e#aluates ". This algorithm finds the %;LA, of an arithmetic expression " written in postfix notation. L. ;dd a right parenthesis '. at the end of ". 8. Fcan " from left to right and repeat steps 7 N 9 for each element " until the '. is encountered. 7. 5f an operand is encountered) then: 9. 5f an operator is encountered) then: a. Vemo#e the two top elements of FT;Cb) where ; is the top element and & is nextCto top element. b. ,#aluate & & c. "lace the result of -b. bac! on FT;Cb 0. Fet %;LA, eJual top element on FT;Cb U. Veturn. !rite an a)3orit"$ /or )inear searc" A)3orit"$6 L5>,;V -E;T;) >) 5T,G) LEC.

Q8 Ans

SUBJECT: C++ (PGDCA/MSC-1)

55/62

Hire E;T; is a linear array with > elements N 5T,G is a gi#en item of information. This algorithm finds the location L*C of 5T,G in E;T;) or sets L*C: ( ? if the search is unsuccessful. L. 8. 7. H5nsert 5T,G at the end of E;T;I Fet E;T; H>+LI: ( 5T,G H5nitiali<e counterI. Fet L*C: (L Fearch for 5T,GI Vepeat while E;T; HL*CI 5T,G Fet L*C: L*C +L H,nd of loopI HFuccessfulXI 5f L*C( >+L) then Fet L*C: ( ? ,xit. Q1< !rite an a)3orit"$ to 'e)ete a )ea/ no'e or t"e no'eK 0"ic" "as e?act)+ one c"i)' Ans Garia,)es to ,e use'6 L.5>6* is the information field of node. 8.L,6T points to left child 7.V5PHT "oints to right child 9.";V points to parent node 0.L*C points to 5T,G if exists otherwise points to >ALL U.5T,G which is to search T.V**T is the root of tree :.CH5LE is the child to delete A)3orit"$6 @.5f L,6THL*CI(>ALL and V5PHTHL*CI(>ALL Fet CH5LE:(>ALL ,lse if L,6THL*CI>ALL Fet CH5LE:(L,6THL*CI ,lse Fet CH5LE:(V5PHTHL*CI L?.5f ";V>ALL 5f L*C(L,6TH";VI Fet L,6TH";VI:(CH5LE ,lse: Fet V5PHTH";VI:(CH5LE ,lse: Fet V**T:(CH5LE LL.Veturn

9. 0.

Q; !rite an a)3orit"$ to searc" an e)e$ent /ro$ a ,inar+ searc" tree Ans Garia,)es to ,e use'6 L.5>6* is the information field of node. 8.L,6T points to left child 7.V5PHT "oints to right child 9.";V points to parent node 0.L*C points to 5T,G if exists otherwise points to >ALL U.5T,G which is to search T.V**T is the root of tree A)3orit"$6 L. 5f V**T(>ALL) then L*C:(>ALL and ";V:(>ALL 8. 5f 5T,G(5>6*HV**TI then set L*C:(V**T and ";V:(>ALL 7. 5f 5T,G15>6*HV**TI) then Fet "TV:(L,6THV**TI and F;%,:(V**T ,lse: Fet "TV:(V5PHTHV**TI and F;%,:(V**T L.Vepeat steps 0 and U while "TV>ALL: 8.5f 5T,G(5>6*H"TVI) then: set L*C:("TV and ";V:(F;%, and return 7.5f 5T,G15>6*H"TVI) then: set F;%,:("TV and "TV:(L,6TH"TVI else set F;%,:("TV and "TV:(V5PHTH"TVI set L*C:(>ALL and ";V:(F;%,. ,xit

SUBJECT: C++ (PGDCA/MSC-1)


Q11 Ans

56/62

.iscuss t"e a'(anta3es P 'isa'(anta3es o/ circu)ar )inke' )ist Circular lists ha#e certain ad#antages o#er singly lin!ed list. The first ad#antage is that in a circular list e#ery mode is accessible from a gi#en mode. ; second ad#antage is concerned with the deletion operation. ;s we !now that in order to delete a mode in a singly lin!ed list) it is necessary to gi#e the address of the first mode of the list. This is necessary because we need to find the predecessor of the node to be deleted to find the predecessor of a search is reJuired starting from the first node of the list. 5n the case of circular list) this reJuirement does not exist since the search for the processor of the mode to be deleted can be initiated from that mode itself. Howe#er) there is a disad#antage in using circular lists. 5t is possible to get into an infinite loop. 5n processing a circular list) it is important that we are able to detect the end of the list. !"at are t"e o&erations t"at can ,e &er/or$e' on a Oueue% !rite &roce'ures to i$&)e$ent t"ese o&erations ; Jueue is linear list of elements in which deletions can ta!e place only at one end) called the 2front3 N insertions can ta!e place only at the other end called the 2rear3. Proce'ure6 Z5>F,VT -Z) 6) >) V) W. Pi#en 6 N V) pointers to the front N rear elements of a Jueue) a Jueue Z consisting of > elements N an element W) this procedure inserts W at the rear of Jueue. 5n the beginning) 6NV ha#e been set to <ero. L. 8. 7. 9. H*#erflowXI 5f Vd> then write -*%,V6L*K. Veturn. H5ncrement rear pointerI V: (V+L H5nsert elementI ZHVI: (W H5s front pointer properly setXI 5f 6(? Then 6:(L Veturn.

Q12 Ans

Proce'ure6 ZE,L,T, -Z) 6) V. Pi#en 6NV) pointers to the front N rear elements) N the Jueue Z) which they correspond) this function deletes N returns the last element of the Jueue. W is a temporary #ariable. L.. HAnderflowI 5f 6(? Than write -'underflow. Veturn -?. H? de#iates an empty JueueI HEelete elementI W eZH6I HZueue emptyXI 5f 6(V then 6: (V: (? ,lse 6: (6+L Veturn elementI Veturn -W.

8.. 7.. 9..

Q1Ans

!rite an a)3orit"$ /or trans/or$in3 in/i? e?&ression into &ost/i? e?&ression 0it" e?a$&)e PO>IS4 @QK PA

SUBJECT: C++ (PGDCA/MSC-1)

57/62

Fuppose Z is an arithmetic expression written in infix mutation. This algorithm finds the eJui#alent postfix expression ". L. 8. 7. 9. 0. "ush 2-2 onto FT;Cb N add. 2 to the end of Z Fcan Z from left to right N repeat steps 7 to U for each element of Z until the stac! is empty. 5f an operand is encountered) add it to ". 5f a left parenthesis is encountered) push it onto FT;Cb. 5f an operator Z is encountered) then a. Vepeatedly pop from FT;Cb N add to " each operator) which has the same precedence as or higher precedence than Z. b. ;dd Z toy FT;Cb H,nd of 5f structureI 5f a right parenthesis is encountered a. Vepeatedly pop from FT;Cb N add to " each operator until a left parenthesis is encountered. b. Vemo#e the left parenthesis HEo not add the left parenthesis to "I H,nd of 5f structureI H,nd of step 8 LoopI ,xit E?a$&)e6 Z: ;+ -& CC-E/,6. Fymbol Fcanned L. ; 8. N 7. 9. & 0. U. C T. CC :. @. E L?. / LL. , L8. L7. 6 L9. . L0. LU. P LT. . L:. L@. L+ 8?. . Pill. Y H FT;Cb -+ -+-+-+-+-+-C -+-C-+-C-+-C-/ -+-C-/ -+-C -/ -+ -C - -+ -C -+-C -+ -C -+ -+ -+ ,xpression " ; ; ; ;& ;& ;&C ;&C ;&C ;&C E ;&C E ;&C E, ;&C E, ;&C E,6 ;&C E,/ ; & C E , 6 / ; & C E , 6/P ; & C E, 6P C ; & C E , 6P C ;&C E,6 /P CH ;&C E,6/PCH +

U.

T.

Q14 Ans

!rite &roce'ure /or &er/or$in3 insertion P 'e)etion o&erations on a circu)ar Oueue ; circular Jueue is the same as a Jueue but the front N rear ends of a Jueue are Doined together to form a circular ring.

SUBJECT: C++ (PGDCA/MSC-1)


Proce'ure6 CZ5>F,VT -6) V) Z) >) W. L. Veset rear pointerX I 5f V ( > then V: (L ,lse V: ( V+L 8. H*#erflowXI 5f 6 ( V Then write -'o#erflow. Veturn 7. H5nsert elementI ZHVI W 9. H5s front pointers properly setXI 5f 6(? Then 6L Veturn. =unction6 CZE,L,T, -6) V) Z) >. L. HAnderflowXI 5f 6(? then write -'underflow. Veturn -?. 8. HEelete elementI W Z H6I 7. HZueue ,mptyXI 5f 6(V Then 6: V: (E Veturn -y. 9. H5ncrement front pointerI 5f 6(> then 6:(L ,lse 6: (6 + L Veturn -y. Q12 Ans

58/62

!rite a)3orit"$s /or Tree tra(ersa)s A)3orit"$ PBEOB.EB @TA6 Pi#en a binary tree whose root mode address is gi#en by a pointer #ariable Toy) this algorithm tra#erse the tree in preorder in a recursi#e manner. L. H"rocess the root nodeI 5f Toy >ALL then write -E;T; -Toy. . ,lse write -',mpty Tree3. Veturn. 8. H"rocess the left subtreeI 5f L"TV >ALL Then call "V,*VE,V -L"TV -T. . 7. H"rocess the right subtree? 5f V"TV -T. >ALL Then call "V,*VE,V -V"TV -T. . 9. ,xit

A)3orit"$ INOB.EB @TA6 L. HChec! for empty treeI 5f T( >ALL Then write -'empty tree. Veturn. 8. H"rocess the left subtreeI

SUBJECT: C++ (PGDCA/MSC-1)


5f L"TV >ALL Then call 5> *VE,V -L"TV -T. H"rocess the root modeI Krite -E;T; -T.. H"rocess the right subtreeI 5f V"TV >ALL Then call V5>*VE,V -V"TV -Toy... ,xit.

59/62

7. 9. 0.

A)3orit"$ POSTOB.EB @TA6 L. HChec! for empty treeI 5f Toy(>ALL then write -',mpty tree. Veturn 8. H"rocess the left subtreeI 5f L"TV -T. >ALL Then call "*FT*VE,V -L"TV -T.. 7. H"rocess the right subtreeI 5f V"TV -Toy. >ALL Then call "*FT*VE,V -V"TV -T.. 9. H"rocess the root modeI Krite -E;T; -Toy. 0. ,xit Q16 Ans !"at are )inke' )ists 4o0 'o t"e+ o(erco$e t"e 'ra0,acks o/ arra+s >inear >inke' >ists >inke' >ist List means to a linear collection of data items. Till now we are storing elements in array. ;rrays has some disad#antages li!e: L.Kastage of memory) because total space allocated must be !nown in ad#ance) otherwise enough space can be wasted. 8.Fome operations li!e 5nsertion and Eeletions reJuire extra time) because insertion and deletion reJuires enough shifting of elements. Eue to these disad#antages we use dynamic memory allocation i.e.) using Lin!ed List. ; lin!ed list is a linear collection of data elements) called nodes. "ointers gi#e the linear order. ,ach node is di#ided into two or more parts. Concept of lin!ed list uses dynamic memory allocation. ; lin!ed can be of the following type. Linear lin!ed list or oneCway list Eouble lin!ed list or two way list >inear )inke' )ist6 5n a linear lin!ed list) also called singly lin!ed list) each node is di#ided in two parts: 6irst part contains the information of the element) and Fecond part) called the lin! field contains the address of the next node in the list Ke reJuire a pointer #ariable Ftart) used that contains the address of the first element of the list. ,nd of list is denoted by >ALL. Lin! field of last node contains >ALL. This is shown in fig 1<< Head 1<1 1<2 11< ?

SUBJECT: C++ (PGDCA/MSC-1)


Q15 Ans

60/62

.e/ine &ointer !rite an a)3orit"$ to create a )inke' )ist P insert an ite$ into a )inke' )ist ; pointer is a #ariable that stores the address of another #ariable. A)3orit"$6 5>65VFT -5>6*) L5>b) FT;VT) ;%;5L) 5T,G.. This algorithm inserts 5T,G as the first mode in the list. L. H*#erflowXI 5f ;%;5L ( >ALL then: Krite o#erflow L ,xit 8. Vemo#e first mode from ;%;5L listI Fet >,K: ( ;%;5L and ;%;5L:( L5>b H;%;5LI 7. Fet 5>6* H>,KI: ( 5T,G HCopies new data into new mode. 9. Fet L5>b H>,KI: (FT;VT H>ew mode points to original first modeI. 0. Fet FT;VT: ( >,K HChanges FT;VT so it points to the new modeI. U. ,xit.

Q18 Ans

!rite a &ro3ra$ to $aintain a /i)e #oid main -. / ofstreams in file + infile .open -]abc. txt].+ char name H8?I: int age+ cout11] ,nter name +] cin M name+ cout 11 ,nter age]+ cin MM age+ infile 11 name 115t 11 age+ infile close -.+ 4

Q1; Ans

!rite a &ro3ra$ to co&+ t"e content o/ one /i)e to anot"er Yinclude1iostream.hM Yinclude1fstream.hM Yinclude1iomanip.hM #oid main-. / ofstream ofile+ ifstream ifile+ char fnameLHL?I)fname8HL?I+ char ch+ cout113,nter the source file name3+ cinMMfnameL+ cout113,nter the target file name3+ cinMMfname8+ ifile.open-fnameL.+ if- ifile.fail-.. / cerr1136ile not found3+ return+ 4 ofile.open-fname8.+

SUBJECT: C++ (PGDCA/MSC-1)


if -ofile.fail-.. / cout113can not ma!e file3+ return+ 4 while- Q ifile.eof-.. / ch(-char. ifile.get-.+ ofile.put-ch.+ 4 ifile.close-.+ ofile.close-.+ 4 Q2< Ans Usin3 c)asses 0rite a &ro3ra$ to co&+ te?t /ro$ one /i)e to anot"er Yinclude1iostream.hM Yinclude1fstream.hM class student / pri#ate: char nameH8?I+ int age+ public: #oid getdata- . / cout113,nter the name and age of the student3+ cinMMnameMMage+ 4 #oid show- . / cout113>ame : 211name+ cout11endl113;ge :311age+ 4 4+ #oid main- . / student s+ fstream infile) outfile+ outfile.open-2stucopy3)ios::out.+ // file opened in write mode infile.open-2stu3)ios::in.+ // file opened to read data from

61/62

while -Q infile.eof- .. / infile.read--char . Ns) si<eof- s..+ outfile.write--char . Ns) si<eof-s..+ 4 infile.close- .+ outfile.close - .+ outfile.open-2stucopy3)ios::in.+ // file in which data was copied is opened in read mode while -Q outfile.eof- .. / outfile.read--char . Ns) si<eof- s..+

SUBJECT: C++ (PGDCA/MSC-1)


s.show- .+ 4 outfile.close- .+ 4

62/62

Anda mungkin juga menyukai