notice c++

62
1/62 Section A 2 Marks Questions [QUESTIONS 1 TO 42] [PAGE 1 TO 6] Q1 . Wh at are Comments ? Ans. Comments are pieces of source code discarded from the code by the compiler. They don’t 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 /* block comment */ Q2. What i s a preprocessor di rec tiv e? What is i ts rol e in C ++? Or Why symbolic statements are used? Ans. Preprocessor directives 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 making the first verifications and digestions of the program's code. Q3. Di ff erentia te be tween constant s and varia bl es. Ans. Variables are the named memory location in computer memory and vary their value at run time. But constants remain the same and cannot change their value at run time. Q4 . Di ff eren ti ate bet ween = and = = ope rators. Ans. ‘=’ operator is one of the assignment operator, used to assign the value to a variable. ‘= =’ Operator is one of the relational operator; used to check the relation between two variables. Q5 . Wr it e a sh or t note on type cast in g. Ans. Type casting is used to convert the data type from lower data type to higher data type and converse for temporary period so that calculations can be performed with both the data types. Example void main() { int a=5; float b; cout<<“value of a ”<<a;  b=(float)a; cout<<“value of b ”,b; } Q6. Wha t a re k ey wor ds? How these are dif fer ent from iden tif iers? Ans. The keywords are the reserved words. The keywords are identifiers but cannot be user defined. It is mandatory that all the keywords should be in lower case letters. For example for, while, do, if, continue, break etc. There are 32 keywords in C and 48 in C++. Identifier can be defined as name of variable and some other program elements using the combination of following characters. Alphabet: a to z, A to Z  Numerals: 0 to 9 Underscore: _ Lakhvinder singh grewal

Upload: lakhvinder-singh

Post on 10-Apr-2018

233 views

Category:

Documents


0 download

TRANSCRIPT

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 1/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 1/62

Section – A 2 Marks Questions

[QUESTIONS 1 TO 42] [PAGE 1 TO 6]

Q1. What are Comments?

Ans. Comments are pieces of source code discarded from the code by the compiler. They don’tchange 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

/* block comment */

Q2. What is a preprocessor directive? What is its role in C++?

Or

Why symbolic statements are used?

Ans. Preprocessor directives 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 making

the first verifications and digestions of the program's code.

Q3. Differentiate between constants and variables.

Ans. Variables are the named memory location in computer memory and vary their value at run

time. But constants remain the same and cannot change their value at run time.

Q4. Differentiate between = and = = operators.

Ans. ‘=’ operator is one of the assignment operator, used to assign the value to a variable.

‘= =’ Operator is one of the relational operator; used to check the relation between two

variables.

Q5. Write a short note on type casting.

Ans. Type casting is used to convert the data type from lower data type to higher data type and

converse for temporary period so that calculations can be performed with both the data types.

Example

void main()

{

int a=5;

float b;

cout<<“value of a ”<<a;

 b=(float)a;

cout<<“value of b ”,b;}

Q6. What are key words? How these are different from identifiers?

Ans. The keywords are the reserved words. The keywords are identifiers but cannot be user 

defined. It is mandatory that all the keywords should be in lower case letters. For example

for, while, do, if, continue, break etc.

There are 32 keywords in C and 48 in C++.

Identifier can be defined as name of variable and some other program elements using the

combination of following characters.

Alphabet: a to z, A to Z

 Numerals: 0 to 9

Underscore: _ 

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 2/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 2/62

Q7. Differentiate between compiler and interpreter? Also give the name of the various

compilers of C and C++.

Ans. Compiler and interpreter both are used to convert the high-level language program into the

object source code. Differences are:

Interpreter: - Interprets the program line by line. It is slow

Compiler: - Compiles the whole program at a time. It is fast.

Also, interpreter can be more easily designed than compilers.

 Name of the C and C++ compilers: Borland C, ANSI C, Turbo C.

Q8. How C is different from ‘C++’?

Ans. C++ is the superset of C. C is structured programming language where as C++ is object

oriented programming language. Many of the features available in C++ were not there in C.

• Data is encapsulated in classes in C++, but not in C.

• Inheritance is done in C++, and not in C

• Data abstraction is a very important concept included in C++.

• By the means of the data hiding we can protect the data.

• Functions cannot be overloaded in C, where as it is possible in C++.

Q9. Define array. How will you declare and store values in an array?

Ans. Arrays are subscripted variables. They are used to give a common name to different memory

locations of same data type. In an array, group of elements can share the same name.

Syntax to declare array is: -

storgeclass datatype arrayname [size];

Example

int a[5];

Q10. What is Procedure oriented programming?

Ans. Using procedural programming we are able to combine returning sequence of statements into

one single place. With the use of procedures, programs can be written in more structured and

error free manner. A program can be viewed as sequence of procedure calls. The main

 program is responsible to pass data to individual calls, data is processed by the procedures

and the result in presented.

Main Program

Procedure 1 Procedure 2 Procedure n

Q11. What is Nested if statement?

Ans. When we combine several if statements, it is referred to as nested if statement. The control ismoved to next if statement only if the first condition is true and after performing the first

statement the next if condition is checked and if this condition is also true, then the second

statement is performed. In case the first condition is false, the control skips the following

statement of both if conditions and moves to the else part, if specified.

Syntax

if(condition1){

statement 1

if (condition 2){

statement 2

}

}

else{

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 3/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 3/62

statements

}

Q12. What do you mean by Manipulators?

Ans. 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

<iomanip.h>. Some manipulators are: endl, hex, dec, oct, setw, setfill, setprecision,

setiosflags etc.

Q13. What is Pointer or Indirection operator?

Ans. The pointer is used for indirect reference of a variable. It holds address of the variable, where

it has been stored in memory. For pointer * operator is used. That’s why it is also called as

indirection operator. Its advantage is that it allows the user to access memory locations and is

also used in call by reference in functions.

Q14. What are the desirable characteristics of a ‘C++’ program?

Ans. A C++ program must contain a class according to the concept of OOPS. The data members

should be declared as private or protected to ensure that there is even no accidental access tothe data members of class. The methods should be declared as public.

The definition of class consists of the following steps:

i. Definition of class

ii. The internal representation of data structures and storage

iii. The internal implementation of the interface.

iv. The external operations for accessing and manipulation the instance of the class.

Q15. Why are functions created in ‘C++’? What is the difference between library functions

and user-defined functions?

Ans. Functions: - A function is a self-contained program segment that carries out some specific,

well-defined task. A function is also known as sub program that can be executed in the

 program. The functions are used to make the program modular.Function basically are classified in two categories

Library functions: - These are needed in every program. They are stored in the library files

known as header files. Commonly used functions are printf() and scanf(). It is to be included

at the beginning of the program using header file. Examples of library files: stdio.h,

iostream.h etc.

User defined functions: - These functions are defined by the users according to their 

requirements. Example: functions to calculate factorial, prime number etc.

Q16. Differentiate between passing arguments by reference and by value.

Ans. Call by reference

In C++, you can declare a function parameter to be a pointer.

For example: void order (int*, int*);It is used to declare the order function. Addresses of arguments are passed when function is

called.

order (int&p, int&q);

It is used to change the values of p and q in calling environment.

Call by value

Argument-passing mechanism where variables are passed as arguments to a function copying

their values to corresponding function parameters without changing them in the calling

environment.

Q17. Define and explain the following:

(a) Abstraction

(b) Polymorphism

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 4/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 4/62

Ans. Abstraction: In OOP data abstraction is defined as a collection of data and methods

(functions). In a class we define the data members as well as the functions, which can access

and use these data members.

Polymorphism: In OOP, polymorphism is defined as how to carry out different processing

steps by a function having the same name. Polymorphism allows you to create definitions for 

operators and functions and at run-time depending on the context a particular definition will

 be used.

Q18. What is a structure? What is the difference between a structure and a union?

Ans. Structure constitutes a super data type, which represents several different data types in a

single unit. It is a collection of dissimilar data type. Structure can be initialized if it is static or 

global. A structure variable contains each of the named members, and its size is large enough

to hold all the members.

A union contains one of the named members at a given time and is large enough to hold the

largest member.

Q19. What is the precedence of operators?

Ans. Precedence is as follows

Arithmetic operators

* Multiplication

/ Division

% Modulus

+ Addition

- Subtraction

Relational operators

< Less than<= Less than or equal to

> Greater than

>= Greater than or equal to

= = Equal to

!= Not equal to

 

Logical operators

! Logical Not

&& Logical And

|| Logical Or  

Q20. How do you declare a single and a two dimensional array?

Ans. Declaration:

1 dimension

storageclass datatype arrayname[size];

Example

static int a[10];

2 dimension

storageclass datatype arrayname[dimension1][dimension2];

Example

static char ch[5][5];

Initialization

1 dimension

storageclass datatype arrayname[size] = {element1, element2,…., element n};

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 5/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 5/62

Example

static int a[10] = {1,2,5,4,7,90,-3,4,5,6};

2 dimension

storageclass datatype arrayname[dimension1][dimension2] = {element1, element2….,

element n};

Example

static int ch[2][2] = {

{2,3},

{4,1}

};

Q21. What is type conversion?

Ans. Type conversion is to convert the set of declared type of a variable to other required type.

Conversion can be divided in two ways.

- Converting by assignment

- Using cast operator 

Q22. What do you mean by preprocessor?Ans. Preprocessor is generally used to include library files and also to define macros.

Built 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.

E.g. gets(), puts( ), getch( ) etc.

Q23. What special operators are used in C++?

Ans. Two special operators introduced in C++, which are different than C are

Insertion operator(<<)

Extraction operator(>>)

cout is used to display an object onto the standard device(monitor). It uses the insertion

operator.

The syntax is : cout<<variable1<<variable2…cin is used to enter values from standard device (keyboard) in variables.

The syntax is: cin>>variable1>>variable2…

Q24. What are the advantages of using identifier with long names?

Ans. C++ allows using long names for identifiers. Its advantages are:

1. Long name describe identifier clearly.

2. Readability and understandability of identifier is increased by using long names

Q25. Is cascading of input and output operators possible? If yes explain how?

Ans. The multiple uses of insertion or extraction operators in one statement is called cascading.

Cascading is possible in C++

For exampleCascading of input using cin:

cin>>a>>b>>c;

Cascading of output using cout:

cout<<a<<b<<c;

Q26. Give some characteristics of atoi() function?

Ans. Some characteristics of atoi are:

1. It converts string to integer.

2 It is a utility function.

3 It is defined in stdlib.h.

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 6/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 6/62

Q27. How does pointer work with two-dimensional array?

Ans. In two-dimensional array, pointers contain address of first element i.e. is address of zeroth row

and zeroth column assigned to pointer . If we increment pointer, pointer will be incremented to

next data in two-dimensional arrays that is equal to value. i.e. value[0][1] because two-

dimensional array store data by row order.

Example ptr=&value[0][0];

Q28. What is meant by data hiding?

Ans. Data hiding provides facility of exposing information as much is needed by the user. Data

hiding is implemented using abstraction and encapsulation. It can be implemented by using

three access-specifiers:

• Private

• Public

• Protected

It is also called as data abstraction.

Q29. What is encapsulation?Ans. It 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.

Only member functions of class can access data. These functions provide interface between

object data and program.

Q30. What is object oriented programming? What is the difference between an object and a

class?

Ans. Object oriented programming treat data as a critical element in program development and

does not flow freely around the system. It ties data more closely to functions that operate on it

in a data structure called Class. Objects are instances of Class. Class is a template from which

objects take their shape. A Class can have more than one object. Collection of number of 

entities is called as objects. Class is also defined as collection of data members and member functions.

Concepts of OOP are:

• Objects

• Classes

• Data abstraction and Encapsulation

• Inheritance

• Polymorphism

• Dynamic Binding

• Message Passing

Q31. State two rules for naming identifiers.

Ans. 1. Only alphabetic characters, digits and underscores are permitted

2. It should not begin with numeric data.

3. For using multiple word variables, underscore is used, as space is not allowed.

4. Declared keywords cannot be used as variable names.

Q32. Can a conditional operator replace an if statement always?

Ans. Yes. By putting the conditional operator within parenthesis we can write as many conditions.

Example:

(a>b &&a >c)?cout<<a: ((b>c)?cout<<b:cout<<c);

Q33. How will you classify operators in C++?

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 7/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 7/62

Ans. Operators in C++ can be classified on the following basis:

1. Arithmetic operators

2. Relational operators

3. Comparison operators

4. Bit wise operators

5. Unary operators

6. Special Operators like new, delete, scope resolution etc.

Q34. What is the difference between “b” and ‘b’?

Ans. ‘b’ is in single quotes so it is a character whereas “b” is in double quotes, it is treated as

string. ‘b’ would take 1 byte whereas “b” would take 2 bytes in memory as “b” also contains a

null value. Strings are always terminated with a null character.

Q35. What is a reference variable?

Ans. It is new type of variable provided by C++. It provides facility of alias name or alternative

name. For example: If we make variable sum as reference variable to total, then sum and total

can be interchangeably used to represent that variable.

Syntax: Datatype & reference-name=variable nameExample:

float total=100;

float &sum=total;

Q36. Differentiate between a structure and an array.

Ans. Structure and array both are user defined data types. But structure is collection of dissimilar 

data type whereas array is collection of similar data type. Structures are records of user-

defined data whereas arrays are subscripted variables.

Q37. What are the various characteristics of object oriented languages?

Ans. Object oriented programming languages have different characteristics from traditional

 procedural languagesCharacteristics of object oriented languages

• Objects

• Classes

• Data Abstraction

• Encapsulation

• Inheritance

• Polymorphism

• Dynamic Binding

• Message passing

Q38. What is pointer to a constant?

Ans. int const *ptr2=&m; here ptr2 is declared as pointer to constant. It can point to any variable of 

correct type, but the contents of what it points to cannot be changed.

Q39. What are the various output statements used in C++? Explain with examples.

Ans. cout: It can display data of any type. It can print integer, float, character, double type. It is a

member of the iostream class.

Example: cout<<a<<b;

put: It is used to display a line of text, character by character. It is a member of the ostream

class

Example: cout.put(ch);

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 8/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 8/62

write: The write() function displays an entire line and has he following form.

Example: cout.write(string1, 10);

Q40. How can we allocate and deallocate memory to an array?

Ans. Memory can be allocated to an array by using new operator and can be deallocated using

delete operator.

Int *ptr=new int[20]; will allocate memory for 20 integers.

Delete[] ptr; will deallocate memory .

Q41. How does C++ help to produce flexible and extensible software?

Ans. Using C++ we can create software that can represent real life entities. The systems design

using C++ has open interfaces. It provides facility of inheritance using which class can be

extended by keeping its previous form as it is and adding new features to it. C++ is flexible

 because it industrializes software development.

Q42. Can we pass entire structure as argument to function?

Ans. Yes entire structure can be passed as argument to a function and can also be returned.

For examplestruct student

{

char name [20] ;

int age, fee;

};

struct student function1 (struct student s)

{

----------

----------

}

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 9/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 9/62

Section – A 5 Marks Questions

[QUESTIONS 1 TO 36] [PAGE 7 TO 21]

Q1. What are the different data types available in ‘C++’?

Ans. While programming, we store the variables in our computer's memory. For it, the compiler 

needs to know the datatype of the variable, so that it could allocate memory to the variables.

Various data types are:

1. Character data type: any character belonging to the ASCII character set is considered as a

character data type whose maximum size is 8 bits long. The ‘char’ keyword is used to

represent character data type in C++. Character constants are always represented within single

quotes. An array of characters is called a string.

2. Integer data: the keyword ‘int’ stands for the integer data type in C++ and its size is either 

16 or 32 bits. A 16-bit integer falls in the range of -215 to 215 -1, while 32 bit integers fall in

the range of -231 to 231 - 1.

Various integer data types are:

a) Short integer data type: Normally the short int is used to declare the short integer data

type in C++. Its maximum size is 16 bits long. It falls in the range between

-32768 to 32767. When we write int in our program, it is considered as short int.

b) Long integer data type: The long int stands for the long integer data type used in C++. Its

size is 32 bits. It may fall in the range of -2147483648 to 2147483647.

3. Floating point data type: The numbers which are stored in the form of floating point

representation are known as floating point numbers. They can be declared as ‘float’ in C++

whose maximum size is a rational number approximately between -3.4E-38 to 3.4E+38

4. Double data type: ‘double’ is a keyword that is used to represent double precision floating

 point numbers in C++. The size of double data type varies from -1.7E-308 to 1.7+308

5. Void: void is a special data type used in C++. Uses of void are:

• To specify the return type of a function when it is not returning any value.• To indicate an empty argument list to a function.

• It is also used in context of pointers

Example: void function1(void);

void *p;

OR 

In how many ways can we represent an integer?

Integer data: the keyword ‘int’ stands for the integer data type in C++ and its size is either 16

or 32 bits. A 16-bit integer falls in the range of -215 to 215 -1, while 32 bit integers fall in the

range of -231 to 231 - 1.Various integer data types are:

a) Short integer data type: Normally the short int is used to declare the short integer data

type in C++. Its maximum size is 16 bits long. It falls in the range between

-32768 to 32767. When we write int in our program, it is considered as short int.

b) Long integer data type: The long int stands for the long integer data type used in C++. Its

size is 32 bits. It may fall in the range of -2147483648 to 2147483647.

Q2. What are pre processors? Write a program to define a macro with parameters using

#define pre-processor.

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 10/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 10/62

Ans. Preprocessor is a directive that modifies the C++ source program according to conditions

given 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 “#” symbol and known as

 preprocessors directives. They make the compiler to include the contents of specified file.

Using preprocessor we can also specify the macros. They commonly useable preprocessors

are #include and #define.

The preprocessor carries out the following actions:

• Replacement of identifiers by some values.

• Conditional execution of parts of the source file.

• Inclusion of other file.

• Renumbering of source file and renaming of the source file itself.

Program with definition of macro with parameter:

#define SQUARE (x) x*x

#include <iostream.h>

void main( )

{

int a=SQUARE (5);int b=SQUARE(6);

cout<< a<<b;

}

Q3. What do you mean by manipulators? Explain some inbuilt I/O manipulators.

Ans. Manipulator functions are special stream functions that change certain characteristics of the

input and output. They change the format flags and values 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 <iomanip.h>.

Endl. The endl is an output manipulator. It generate carriage return or line feed.

Setbase( ). It is used to convert the base of numeric value into another base.

Dec – decimal base (base=10)

Hex - hexadecimal base (base=16)

Oct – octal base (base =8)

Setw ( ) The setw( ) stands for set width. It is used to specify the minimum number of 

character positions on the output field a variable will consume.

Setfill( ) The setfill( ) manipulator function is used to specify a different character to fill the

unused field width of the value.

Q4. What are the different control structure available in ‘C++’? Explain with example.

Ans. Control statements are used to make decision. These statements are required to take an action

according to the condition. The various control statements are as under: -

1. if statement 2. if – else statement 3. nested if 1. if statement :- Executes the statements if condition is true.

Syntax: -

if (condition)

{

statements;

}

2. if–else statement: - Executes the block of statements if condition is true. Otherwise

execute else block.

if (condition)

{

statements;

}else

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 11/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 11/62

{

statements;

}

3. Nested if :- Executes one block out of number of blocks of statements which specify

the condition other wise executes else block statements.

if (condition){

statements;

}

else if(condition)

{

statement;

}

else

{

statements;

}

Case statements :- These statements are used to make decision from the number of choices.In “C++” case control instruction is the switch statement.

Switch statement :- switch statement provide better alternative for series of if –else

statements, because any part of the code can be executed on the value of an expression.

Syntax: -

switch(expression)

{

case value:

statement1;

case value:

statement2:

default:

statements}

Default statement is used as optional.

Branching statements: These statements transfer the control to another part of the program.

There are three types of branching statement.

(a) Continue statement

(b) Break statement

(c) Goto statement

i. continue :- The continue statement takes the control at the beginning of the

loop and remaining statements skipped and control move to the last stub.

ii. break :- The break statement is used to terminate the loop or a sequence of 

statement in a switch statement. A break statement enforces immediate

termination of program.

iii. goto :- The goto statement is used to alter the normal sequence of program

execution by transferring the control to some of the defined level in the

 program.

Syntax

goto label;

label :

statements;

Iterations statements/Loop statements: - Loops are used execute a set of statements

repeatedly until desired condition is meet. There are different types of loops in C++

1. while

2. do while3. for  

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 12/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 12/62

While loop: -

This statement is used to execute the loop till the condition true.

while (expression or condition)

{

statements

}

Do while: -

Statements will execute when the condition is true but in this loop the statements will execute

first then condition checked.

do

{

statements

}while (expression);

For loop: -

In the for loop the initialization , condition and increment or decrement can be done at one

 place.

for (initial value; expression; increment/decrement)

{statements ;

}

Q5. Write a program to calculate the

sum of all odd numbers between 1 and

1000.

Ans.

#include<iostream.h>

#include<conio.h>

void main( )

{int i;

long int sum=0;

for(i=1;i<=1000;i+=2)

sum+=i;

cout<<”Sum of odd numbers between 1

and 1000 is : “<<sum;

getch( );

}

Q6. Write a program to input a word.

Display on screen “Hello” as many times

as, the number of a’s present in the

word.

Ans.

#include<iostream.h>

void main( )

{char str[20];

int k;

cout<<”Enter a string”;

cin>>str;

k=0;

while(str[k] !=’\0’)

{

if(str[k]==’a’)

cout<<endl<<”hello”;

k++;

}

}

Q7. Why do we use functions and what are its advantages?

Ans. Functions are used to divide a program in sub parts. There are different advantages of using

functions:

1. Efficiency of maintenance of code

The code written as the body of functions that makes the task simpler. Separating the

code into modular functions makes the program easier to design.

2. Ease of understanding

The use of functions makes the program understand easily as each operation is placed

in different function. And it can be written or checked immediately.

3. Elimination of redundancy of codeUsing this we don’t have any need to rewrite the code again and again to perform the

same type of task.

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 13/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 13/62

4. Reusability of code

Functions once defined can be used any number of times just by calling them by their 

name.

Q8. How parameters can be passed to a function. Explain?

Ans. To make the communication between the calling and called functions, parameters can be

 passed to the functions. Formal parameters are passed to the user-defined function. The

communication can be one way or two way. If the function defined does not return any thing

then it is one-way communication. If the function returns some thing then it is two-way

communication.

Example:

int square ( int a) {

statements;

---------

return ; }

Here square is the user-defined function getting one parameter of type int. The function isalso returning a value of type int.

Q9. What are storage classes? Explain their types.

Ans. The storage class specifier refers to how widely it is known among a set of functions in a

 program. Storage class provides information about its visibility, lifetime and location.

 Normally a variable can be declared as belonging to any one of the following groups:

1. Automatic variable

2. Register variable

3. Static variable

4. External variable

Automatic variable: These are also called local or internal variables. They are declared

inside a function. They are referred to as automatic because their memory space isautomatically allocated as the function is entered and released as soon as it leaves. In other 

words, automatic variables are given only temporary memory space. Their scope is within the

function in which they are declared.

Register variable: The only difference between automatic and register variables is that of 

their memory location. The register variables are stored in the CPU registers. Thus the time

taken to access the register variables is much less than the memory variables. But only limited

variables can be declared with register storage class. If there are not sufficient registers to

hold these variables then they will be stored in memory, hence will be treated as automatic

variables.

Static variables: Static variables are defined within a function and they have the same scope

rules as that of automatic variables but in the case of static variables, the contents of the

variables will be retained throughout the program.External variable: Variables, which are declared outside the main, are called external

variables. These variables will have the same data type in main and other functions. The life

of these variables is in whole program. It can be accessed in each and every function of the

 program.

Q10. What is recursion? Why recursion is used? Write a program to calculate sum of first

five numbers using recursion.

Ans. A function, which calls itself directly or indirectly again and again, is known as the recursive

function. Recursive functions are very useful while constructing the data structures like trees.

The recursive function will be invoked by itself as long as the given condition is satisfied.

Program to calculate the sum of first five numbers:

int sum(int x)

{

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 14/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 14/62

if (x==1)

return 1;

else

return ( x+ sum(x-1));

}

void main( )

{

cout<< sum(5);

getch( );

}

Q11. Create a function to find whether

the character is in uppercase or

lowercase.

Ans.

#include<stdio.h>

#include<conio.h>

void letter(char);void main()

{

char c;

clrscr();

cout<<”enter any letter”;

cin>>c;

letter(c);

getch();

}

void letter(char c)

{

if((c>'a')&&(c<'z'))cout<<"letter is in lower case";

else

cout<<"letter is in upper case";

}

Q12. WAP to pass array as parameter in

the function and to find the greatest

number from the list of array.

Ans.

int greatest (int a[ ] , int n )

{

int j , max ;max = a[0];

for ( j=1; j<n;j++)

{

if (max <a[j])

max= a[j];

}

return max;

}

void main ( ) {

int a [ 50 ], n , j ;

cout<<”Enter the range”;

cin>> n;for (j=0;j<n; j++)

{

cout<<”Enter the array element “;

cin>> a[j];

}

cout<<”The greatest element in array is”;

greatest( a, n);

}

Q13. WAP to pass a structure in the function as parameter and return the structure from the

function.

Ans. struct complex {

float real;

float imag;

};

complex add (complex a, complex b)

{

complex c;

c.real=a.real+b.real;

c.imag=a.imag+b.imag;

return c;

}

void main( ){

complex a,b,c;

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 15/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 15/62

cout<<”Enter the first complex number”;

cin>>a.real>>a.imag;

cout<<”Enter the second real number”;

cin>>b.real>>b.imag;

c=add(a,b);

cout<<endl<<”Addition of two complex numbers”;

cout<<c.real<<” i ”<<c.imag;

}

Q14. What is an array? Write a program to sort an array in ascending order.

Ans. An array is collection of elements of homogeneous data type. All the elements in array are

referred with common name. An index or subscript is used to access the element in the array.

Program to sort an array:

#include<iostream.h>

#include<conio.h>

void main( )

{

nt a[10], i, j, temp ;

for(i=0;i<10;i++){

out<<”Enter the array element”;

cin>>a[i];

}

for(i=0;i<9;i++)

{

for(j=i+1;j<10;j++)

{

if (a[i]>a[j])

{

temp=a[i];

a[i]=a[j];a[j]=temp;

}

}

}

for(i=0;i<10;i++)

{

cout<<a[i];

}

}

Q15. WAP to display the matrix of 

two by two.

Ans.

#include<stdio.h>

#include<conio.h>

void main()

{

int a[2][2]={{1,2},{2,3}},i,j;

clrscr();

for(i=0;i<2;i++)

{

for(j=0;j<2;j++)

{cout<<"Enter element for”<< i+1<<”

row”<<j+1<<” column”;

Q16. WAP to perform the

multiplication of two matrices.

Ans.

#include<iostream.h>

#include<conio.h>

void main( )

{

int a[3][3], b [3] [3], c [3] [3], i, j, k;

cout<<”Enter the first array”;

for (i=0;i<3;i++)

for(j=0;j<3;j++)

cin>>a[i][j];

cout<<”Enter the second array”;for (i=0;i<3;i++)

for(j=0;j<3;j++)

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 16/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 16/62

cin>>[i][j];

}

}

for(i=0;i<2;i++)

{

for(j=0;j<2;j++)

{

cout<<a[i][j]);

}

cout<<endl;

}

getch();

}

 

cin>>b[i][j];

for(i=0;i<3;i++)

{

for(j=0;j<3;j++)

{

c[i][j]=0;

for(k=0;k<3;k++)

c[i][j] + = a[i][k] * b[k][j];

}

}

for(i=0;i<3;i++)

{

cout<<endl;

for(j=0;j<3;j++)

{

cout<<”\t”<<c[i][j];

}

}getch( );

}

Q17. What is pointer? WAP to display the values of single dimensional array using pointer.

Ans. Pointer:

Pointer is an indirection operator, which refers to any other variable. Pointers are variables,

which store the address of another variable. That variable may be a scalar (including another 

 pointer), or an aggregate (array or structure). The pointer to object may be part of a larger 

object, such as a field of a structure or an element in an array.

Program to show the elements of an array-using pointer:

#include<iostream.h>

#include<conio.h>#define MAX 100

void show( int * a, int n)

{

int j;

for(j=0;j<n;j++)

cout<<endl<<*(a+j);

}

void main( )

{

int arr[MAX], n, k;

cout<<”Enter the no. of elements to be entered in array”;

cin>> n;

cout<<”Enter the array”;

for(k=0;k<n;k++)

{

cout<<”Enter the array element”;

cin>>arr[k];

}

show(arr, n);

getch( );

}

Q18. What is the difference between array of pointers and pointers to an array?Ans. A pointer to an array contains the address of the first element. In a one-dimensional array, the

first element is &[0]. In two-dimensional array, it is &value[0][0].

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 17/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 17/62

The address of the zeroth row and the zeroth column of the two-dimensional array value is

assigned to the pointer variable value.

For example:

int a[ ] [ ];

int *ptr;

 ptr=&a[0][0]; // or ptr= a;

Array of pointers:

The pointer may also declared like any other data type. The declaration of an integer pointer 

array of size 10 is

int *ptr[10];

Where ptr is an array of pointers. It can hold the addresses of various arrays.

Q19. What is the difference between call by value and call by reference? WAP to swap the

value of two parameters using pointers.

Ans. Pass by reference passes a pointer to the value. This allows the caller to modify the variable

directly. Pass by value gives a copy of the value to the caller. This allows the caller to modify

the value without modifying the variable. (In other words, the caller simply cannot modify thevariable, since it lacks a reference to it.)

Program to swap two numbers using pointers:

#include<iostream.h>

#include<conio.h>

void swap( int * x, * y)

{

int temp;

temp=* x;

*x= * y;

*y=temp;

}

void main( ){

int first, second;

cout<<”Enter the first number”;

cin>>first;

cout<<”enter the second number”;

cin>>second;

swap(&first, & second); // call by reference

cout<<”After swapping values are :”;

cout<<”First : “<<first;

cout<<”Second: “<<second;

getch( );

}

Q20. Write a function that will round

floating-point number to an indicator

decimal place.

Ans.

#include<manip.h>

void main()

{

float a=5,b=3,c d;

c=a/b;

cout<<”enter d”;cin>>d;

cout<<setprecision(d)<<c;

Q21. Write a c++ program to compute

the size of union.

Ans.

union stu

{

  int a,b;

};

void main()

{

union stu q;int j;

j=sizeof(q);

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 18/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 18/62

} cout<<j;

}

Q22. What is a header file? What is the purpose of using these files?

Ans. A file with extension .h is called header file. It is a library, which contains the definition of 

various functions. These functions assist the programmer to prepare the program in anefficient 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. As these

libraries contain several inbuilt functions, we don't need to redeclare these functions

ourselves. we can include a library and use its functions by just calling them with their 

appropriate parameter.

Most C ++ compliers support the following standard library facilities:

1) Operations on characters 2) Operations on strings.

2) Mathematical operation 4) Storage allocation procedures

5) Input /Output operations

Q23. Using pointer write a program to add

two matrixes. [IN EXAM]Ans.

#include<iostream.h>

#include<conio.h>

void main( )

{

int a[3][3], b [3] [3], c [3] [3], i, j, k;

int *p1[3], *p2[3],*p3[3];

cout<<”Enter the first array”;

for (i=0;i<3;i++)

for(j=0;j<3;j++)

cin>>a[i][j];

cout<<”Enter the second array”;for (i=0;i<3;i++)

for(j=0;j<3;j++)

cin>>b[i][j];

 p1=&a[0][0];

 p2=&b[0][0];

 p3=&c[0][0];

for(i=0;i<3;i++)

{

for(j=0;j<3;j++)

{

 p3[i][j] = p1[i][j] + p2[i][j];

}

}

for(i=0;i<3;i++)

{

cout<<endl;

for(j=0;j<3;j++)

{

cout<<”\t”<<c[i][j];

}

}

getch( );

}

Q24. Program to convert decimal into

hexadecimal.Ans. 

# include <iostram.h>

# include <conio.h>

#include <string.h>

void main ()

{

long int n, m; char res[20]; int r,i;

for (i =o; i<20;c++)

res [i] =\;; // to initialize string

i=0;

cont<<' counter the number ; cin >> n;

m=n;while (m >0)

{

r= m%16;

if (r<=a)

{

res[i] = r +'0'

{

res[i]= r+'0';

}

else

{

switch (a)

{

case 10: res[i] ='a';

 break;

case 11: res[i] ='b' ; break;

case 12; res[i] ='c' break;

case13: res [i] ='d' break 

case 14: res[i] ='e' break 

case 15: res[i] ='f' break 

}

}

i++im/16;

}

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 19/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 19/62

straw (res);

cout <<' Hexadecimal equivalent of "<<n<< is

<< res;

getch ();

Q25. WAP to sort an array using

pointer.

Ans.

# include<iostream.h>

#include<conio.h>

#define MAX 100

void sort( int * a, int n)

{

int i, temp, j;

for( i=n;i>0;i--){

for( j=0;j<i;j++)

{

if (a[j]>a[j+1])

{

temp=*a[j];

*a[j]=*a[j+1];

*a[j+1]=temp;

}

}

}

}void main( )

{

int arr[MAX], n , index;

cout<<”Enter the size of array”;

cin>>n;

for(index=0;index<n;index++)

{

cout<<”Enter the array elements”;

cin>>arr[index];

}

sort( &arr[0],n); // function called and

reference to the array is passed

cout<<”Sorted array is “;

for(index=0;index<n;index++)

cout<<endl<<arr[index];

getch( );

}

Q26. Write a program to count number

of vowels, consonants, blank spaces and

words in a line of text.

Ans.

#include<iostream.h>

#include<stdio.h>

#include<conio.h>

void main()

{

int cons=0, vow=0, bsp=0, w=1, I=0;

chat str[50];cout<<”Enter a string”;

gets(str);

while(str[I] !=’\0’)

{

if((str[I]>=’a’ && str[I]<=’z’) ||(str[I]>=’A’

&& str[I]<=’Z’))

{

if((str[I] ==’a’ || str[I]==’e’ || str[I]==’i’ ||

str[I]==’o’ || str[I]==’u’)||(str[I] ==’A’ ||

str[I]==’E’ || str[I]==’I’ || str[I]==’O’ ||

str[I]==’U’))

{vow++;

}

else

cons++;

}

}

else if( str[I]==’ ‘)

{

 bp++;

w++;

}

I++;

}

cout<<”Number of vowels are”<<vow;

cout<<endl<<”Number of consonants

are”<<cons;

cout<<endl<<”Number of blank spaces are

“<<bsp;

cout<<endl<<”Number of words are”<<w;

getch();

}

Q27. Explain IF Statement in detail.

Ans. SIMPLE IF

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 20/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 20/62

if (condition)

{

statements

}

if ..... else

if (Condition)

{

statement

:

}

else

{

statements

:

}

If ladderif (Condition)

{

if (condition)

{

statements

}

else

{

statements

}

}

else{

statements

}

Q28. What is register storage class? 

Ans. The variable, which requires to be processed more then other can be set as register storage

class. For example the variable used as index variable in for loop may be set register storage

class.

e.g.

void main()

{

int a[10];register int i;

for (i=0 ; i<10; i++)

{

cout << Enter array element;

cin >> a[i];

}

for (i=0; ; i<10; i++)

cout << end l<< a[i];

}

Q29. Program to add all odd no'sbetween 10-1000.

Ans.

Q30. Program to maintain studentrecord using structure.

Ans.

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 21/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 21/62

void main ()

{

long int s=0, i;

for (i =11 ; i<1000 i +=2)

s+= i;

cont << " sum is << s;

float Average (int n)

{

int i, a;

float s=0;

for (i =o << = n; i ++)

{

cout << Enter the number 

cin >> a;

s= s+a;

}

s= s/n;

}s=s/n;

}

void main ()

{

int n;

float avg

cout << Enter the value of n;

cin >> n;

Avg = Average (n);

cout << Average is << avg ;

}

struct student {

char name [20] :

int age ;

char sex ;

};

void showdata (student ):// Prototype

void main ()

{

student s;

cut << Enter name of student ";

cin >> S. name ;

cout << Enter age;

cin>> s.age;

cout << Entete Sex;

cin >> s. sex;

showdata (s) : // Function call

getch ();

}void showdata (student S )

{

cout << Name : << s. name;

cout << endl<<"age;""<< S.age;

cout << endl<<"Sex:"<< s. sex ;

}

Q31. Program to print string in reverse

order.

Ans.

#include<string.h>

void main()

{

char n[20],n1[20];

int c=0,i;

clrscr();

cout<<"enter string";

gets(n);

for(i=0;n[i]!=NULL;i++)

{

c++;

}

for(c=c-1,i=0;c>=0;c--,i++)

{

n1[i]=n[c];

}

n1[i]='\0';

char *p;

i=0;while(n1[i]!='\0')

{

Q32. Write a program, which solves the

following expression:

c=a+b (b) c=a-b (c) c=a*b

(d) c=a/b

Ans.

void main()

{

int a,b,c;

cout<<”enter a and b”;

cin>>a>>b;

c=a+b;

cout<<c;

c=a-b;

cout<<c;

c=a*b;

cout<<c;

c=a/b;

cout<<c;

}

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 22/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 22/62

 p=&n1[i];

cout<<*p;

i++;

 p++;

}

}

Q33. What do you mean by string handling? Explain all the string handling functions with

examples?

Ans. String library functions are the functions, which are used regularly and stored in library file

and whenever these functions are needed, you need to include the required header file in your 

 program.

There are different types of functions

Strlen(): This function is used to count the characters in a string. It calculate the length of the

string.

Syntax:

strlen(array variable);

strcpy(): This function copies the contents of one string into another Syntax:

strcpy(target,source);

strcat(): This function is used to concatenate the source string at the end of the target string.

Syntax:

strcat(target,source);

strcmp(): 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 0 if both the strings are identical.

Syntax:

strcmp(string1,string2);

Q34. Write various paradigms, tools, notations and graph used in object oriented systemdevelopment.

OR 

What are characteristic of object oriented languages?

Ans. Definition:

Using object oriented programming language we can represent information as series of 

objects. Object will be of class type. Once class is created, any number of objects of that class

type can be created.

PARADIGMS:

1. Emphasis is on data rather than procedure.

2. Programs are divided into what are known as objects.

3. Data structures are designed such that they characterize the objects.

4. Functions that operate on data of an object are tied together in the data structure.

5. Data is hidden and cannot be accessed by external functions.

6. Objects may communicate with each other through functions.

7. New data and functions can be easily added whenever necessary.

8. It follow bottom up approach in program design.

 

TOOLS

1.Rational rose

2. Reqisite pro

 

NOTATIONS AND GRAPH

1. Object Diagram2. Use case Diagram

3. Collaboration Diagram

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 23/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 23/62

4. State Diagram

5. Activity Diagram

6. Physical Diagram

7. Deployment Diagram

8. Component Diagram

Q35. Write a program to display the

characters line by line.

Ans.

#include< fstream.h>

#include<string.h>

int main()

{

char string[80];

cout <<”enter string”;

cin>> string;

int len=strlen(string);

fstream file;fileopen(“TEXT”, ios::in | ios::out);

for(int i=0;i<len;i++)

file.put(string[i]);

file.seekg(0);

char ch;

while(file)

{

file.get(ch);

cout<<ch;

}

return 0;

}

Q36. Write a program to print the

pascal triangle.

Ans.

void main()

{

int i,j,l,m,n;

cout<<”enter no of rows”

cin>> n;

m=1;

for(i=1;i<n;i++)

{

for(i=40-3*l;i>0;i--)cout<<” “;

for(j=0;j<=l;j++)

{

if((j==0)|| (l==0))

m=1;

else

m=(m*(l-j+1))/j;

cout<<m;

}

cout<<endl;

}

getch();}

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 24/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 24/62

Section – B 2 Marks Questions

[QUESTIONS 1 TO 19] [PAGE 22 TO 25]

Q1. What is a constructor? Can there be more than one constructor?Ans. A constructor is a special member function for automatic initialization of an object. Whenever 

an object is created, the constructor will be executed automatically. It has the same name as

that of class. It is declared with no return type. A class may have a number of constructors.

They can be defined by varying the number of parameters passed in the constructor.

Q2. What are destructors?

Ans. A destructor is a function that automatically executes when an object is destroyed. It is

executed when an instance of the class to which it belongs goes out of class or goes out of 

existence. Some rules for writing a destructor function are:

1) The name of destructor is the same as that of class.

2) The first character of name must be tilde (~)

3) It cannot be overloaded.

4) It has no return type.

5) It cannot accept any parameters.

Q3. What is copy constructor?

Ans. It is used when compiler has to create a temporary copy of a class object. The copy

constructors are used in following situations

1) The initialization of an object by another object of same class.

2) Return of objects as function value.

3) Stating the object as by value parameters of a function.

Q4. What are classes? How classes are different from structures?Ans. A 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 variables of a class are called

objects or instances of a class.

Structure contains one or more data item, which are grouped together as a single unit. On the

other hand class not only contain the data members but also the functions to manipulate that

data. Secondly, in a structure, all elements are public by default, while in a class they are

 private.

Q5. Define Enumerated data types.

Ans. An enumerated data type is user-defined data type, which provides a way for attaching names,thereby increasing comprehensibility of the code. The enum keyword automatically

enumerates a list of words by assigning them values 0,1,2 and so on.

enum colour{red, green, blue, pink};

Q6. A friend function cannot be used to overload the assignment operator =. Explain why?

Ans. Although the friend function cannot directly access the members that are declared as private,

still the friend function has the right to access these members. In other words, there is nothing

a class can hide from its friend.

But the friend function is not within the scope of any class. And it is defined out of class.

Also when the function is called, it is called without any object reference. The only need is to

 pass the object of class as parameters in to the function. So it can not be used to

overload=operator 

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 25/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 25/62

Q7. What is multiple inheritance?

Ans. Multiple inheritance: multiple inheritance is the process of creating a new class from more

than one base classes.

Syntax:

Class A {

-

-

-

};

Class B {

-

-

-

};

Class C : public A, public B

{

-

-

};

The class C is derived from both classes A and B. In multiple inheritance a class is derived to

inherit the properties of two or more parent classes. Multiple inheritance can combine the

 behavior of multiple base classes in a single derived class. It has advantages over single

inheritance .It can combine the behavior of multiple base classes in a single derived class. It

has advantages over single inheritance such as rich semantics and ability to directly express

complex structures.

Q8. Write a Short Note on Operator overloading.

Ans. The working of an operator can be redefined by using operator overloading .The operators,

which already exist in a language, can only be used to make language more natural to read

and write. Even debugging of such codes are much easier.

Operator overloading: It is accomplished by means of special function. The function we

want to declare as operator overloading function must be of a class. The syntax is

return –type operator operator to be overloaded (parameters ..);

The keyword operator must be preceded by the return type of the functions which gives the

compiler, the information that operator is being overloaded.

Q9. How File Handling is done in C++?Ans. File is a collection of data or a set of characters. There are two types of files in C++.

Sequential and Random access. In sequential files the data or text will be stored or read back 

sequentially. In random access files, data can be accessed and processed randomly.

The following methods are used in C++ to read and write files:

ifstream – To read a stream of object from a specified file.

ofstream – To write a stream of object on a specified file.

The following attributes are used for various 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.

Q10. What are the various access labels used in the declaration of classes?

Ans. Three types of labels are used:

1. public

2. private

3. protected

Q11. What are pitfalls of operator overloading and data conversion?

Ans. Operator overloading

1. It is not possible to overload all operators.

2. Some programmers try to define everything as an operator so it is over utilized.

3. Operator overloading facility is not available in all type of languages like java.Data conversion

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 26/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 26/62

By converting data from one type to another accuracy is reduced .If we convert float data

into an integer then rounding of all digits after decimal reduces accuracy.

Q12. What is nesting of classes?

Ans. 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 {

 private

char name [20]

int roll no ;

 public :

class date {

 private :

int day, month, year;

 public:

}; // end of date class

}; //end of student class

Q13. What do you mean by object reference?

Ans. C++ allows the use of a reference, which is simply another name of object that is being

initialized.

Class o;

Class &o1=o;

Here o1 is alternative name of o.

Q14. What is late binding? What is early binding? How these bindings are implemented?

OR 

What is static polymorphism? What is dynamic polymorphism?

Ans. Early binding: Choosing a function in normal way, during compilation time is called asearly binding or static binding or static linkage or static Polymorphism. During

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 invocation.

By default, c++ follows early binding. C++ supports late binding also. Late binding is

called as run time binding or execution time binding or dynamic polymorphism. Late

 binding is implemented using virtual function.

Q15. What is hybrid inheritance?

Ans. It is combination of more than one inheritance. In following figure class1, class 2, class3 are

related to each other using the concept of multilevel inheritance. Whereas class2, class 3,

class 4 are related using the concept of multiple inheritance. So overall concept is of hybridinheritance. By combining all four classes we get hybrid inheritance

Class1

 

class2 class3

 

Class4

Q16. How pointer to a class is declared?

Ans. The pointer will hold address of object of class .The pointer to object of class can be accessed

using following syntax:

Objectname -> membername=variable;

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 27/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 27/62

Or 

(*Objectname).membername=variable;

Q17. How inheritance works in different labels? Explain with suitable example.

Ans. In public inheritance:

•Each public member in the base class is public in the derived class.• Each protected member in the base class is protected in the derived class.

• Each private member in the base class is private in the derived class.

In private inheritance:

• Each public member in the base class is private in the derived class.

• Each protected member in the base class is private in the derived class.

• Each private member in the base class is private in the derived class.

In protected inheritance:

• Each public member in the base class is public in the derived class.

• Each protected member in the base class is protected in the derived class.

• Each private member in the base class is private in the derived class.

Q18. What is this pointer?

Ans. C++ uses a unique keyword called ‘this’ to represent an object that invokes a member 

function. this is a pointer that points to object for which this function was called. For 

example the function call A. max() will set the pointer to the address of the object A. The

starting address is the same as the address of the variable in the class structure.

Q19. What is default constructor?

Ans. The constructor without arguments is called as default constructor. It has no return type. It has

same name as that of class. It is automatically called when object of classes is created.

Class abc

{

 private:---------

---------

 public:

abc();

----------

---------

};

void main()

{

abc();

-------

}

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 28/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 28/62

Section – B 5 Marks Questions

[QUESTIONS 1 TO 29] [PAGE 26 TO 46]

Q1. Write a program to create a classthat can store the data of two

employees.

Ans.

#include<iostream.h>

#include<conio.h>

class employee{

char name[20],design[20];

long int bsal, age;

 public:

void getdata( )

{

cout<<”Enter the name of employee”;

cin>>name;

cout<<”Enter the age of employee”;

cin>>age;

cout<<”Enter the designation”;

cin>>design;

cout<<”Enter the basic salary”;

cin>>bsal;

}

void showdata( )

{

cout<<”\nName : “<<name;cout<<”\n Age : “<<age;

cout<<”\n Designation : “<<design;

cout<<”\n Basic Salary ”<<bsal;

}

};

void main( )

{

employee e1,e2;

e1.getdata( );

e2.getdata( );

e1.showdata ( );

e2.showdata( ) ;}

Q2. Write a program using classes tofind the roots of quadratic equation.

Ans.

#include<iostream.h>

#include<conio.h>

#include<math.h>

class Quad{

int a,b,c;

float d, alpha, beta;

 public:

void getabc( )

{

cout<<”Enter the values of a, b & c”;

cin>>a>>b>>c;

}

void calc( )

{

d=b*b – 4*a*c ;

if (d==0)

{

cout<<”Roots are same “;

alpha= -b/2*a;

cout<<alpha;

}else if (d<0)

cout<<”Roots are imaginary”;

else

{

alpha= (-b + sqrt(d)) /2*a;

 beta= (-b - sqrt(d)) /2*a;

cout<<”alpha : “<<alpha;

cout<<endl<<”beta : “<<beta;

}

}

};

void main( ){

Quad obj;

obj.getabc( );

obj.calc( );

getch( );

}

Q3. Using operator overloading, write a

program for complex number

Q4.Write a Program that removes

duplicates from a string list of n

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 29/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 29/62

operation like ‘+’ and ‘-‘.

Ans.

#include<iostream.h>

struct comp{

float real;

float imag;

};

comp operator+(comp a, comp b)

{

comp c;

c.real=a.real+b.real;

c.imag=a.imag+b.imag;

return (c );

}

comp operator –(comp a, comp b);

{

comp c;

c.real=a.real+b.real;c.imag=a.imag+b.imag;

return ( c );

}

void main( )

{

comp a,b,c;

cout<<”Enter 1st complex number”;

cin>>a.real>>a.imag;

cout<<”Enter 2nd complex number”;

cin>>b.real>>b.imag;

cout<<”Complex number operations”;

cout<<” a - > add”<<”s - > subtract “;cout<<endl<<”Enter your choice”;

char ch;

cin>>ch;

switch ( ch)

{

case ‘a’ : c=a+b;

cout<<endl<<”Addition of two complex

numbers is :”;

cout<<c.real<<”+I”<<c.imag;

 break;

case ‘s’: c=a-b;

cout<<”subtraction of numbers is :”;cout<<c.real<<”+I”<<c.imag;

 break;

}

}

numbers.

Ans.

#include <iostream .h>

#include <conio.h>

int n;

void dele (int * a, int loc)

{

int i ;

fol (i=loc ; i<n-1; i++)

a[i] =a[i] =a[i+1];

}

n--;

void main ()

{

int a [100] , b[100], i, fi

cout << Enter the range in array ";

cin>> n;

for (i=0; i<100;I++)//to initialize b array . b[i]=-1

for (i=0;I<n; i++)

{

cout << Enter array elements'

cin>> a[i];

}

i=b[0], j=a[0];

for (i=1; i<n;c++)

{

for (i=0; j<i; j++)

{

if (a[i]= = b[i]{

dele (a,i); break;

}

}

if (i = = j)

 b[j] = a[i];

}

cout << after removal list is << endl;

for (i=o i<n; i++)

cout <<end l <<a[i];

}

Q5. What is Inheritance? What are its Advantages and types?

Ans. Inheritance is the process of creating new classes, called derived classes, from existing

classes, the existing class is the base class. The derived class inherits all the capabilities of the

 base class but can add properties of its own

Advantages: -

-Protection can be increased in derived classes.

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 30/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 30/62

-The derived class can add data and function members to the class without affecting

the

-Base class behavior.

-Code reusability

Types: - 1. Single inheritance

2. Multiple inheritance

3. Multilevel inheritance

4. Hybrid inheritance.

4. Hierarchical inheritance

Q6. What is the use of static keyword in ‘C++’? Why are static members created in a class?

Ans. The main characteristic of the static variables is that the static variables are automatically

initialized to zero unless it has been initialized by some other value explicitly. In C++, static

member of a class can be categorized into two types, static data member and static member 

function. Whenever a data or function member is declared as a static type, it belongs to a

class, not to instances or objects of the class.

Static data member:Static data members are data objects that are common to all the objects of a class. They exist

only once in all objects of this class. They are already created before the finite object of the

respective class. This property may lead a person to think that static data member is same as

that of global, but it is not true. Static data member may be declared as private, protected or 

 public.

Static member function:

The keyword static is used to precede the member function to make 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 variables.

Q7. What are the different types of friend functions? Explain each with example.

Ans. Friend function is a special mechanism for letting non- member functions access private data.

A friend function may be either declared or defined within scope of a class definition. The

keyword friend informs the compiler that it is not a member function of the class.

Accessing private data by non member function through friend

The friend function can access the private members of a class. When it is necessary to access

the private data by non- member functions, then a class may have a friend function.

Example:

#include<iostream.h>

class sample

{

 private :int x;

 public:

void getdata( )

{

cout<<”Enter the value of x”;

cin>>x;

}

friend void display( sample);

};

void display(sample abc)

{

cout<<”entered number is “<<abc.x;

}

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 31/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 31/62

void main( )

{

sample obj;

obj.getdata( );

display(obj);

}

Friend function with inline substitution:

If a friend function is defined within the scope of the class definition, then the inline code

substitution is automatically made. If it is defined outside the class definition, then it is

required to precede the return type with the keyword inline in order to make a inline code

substitution.

Example:

#include<iostream.h>

class sample{

 private :

int x;

 public:inline void getdata( )

{

cout<<”Enter the value of x”;

cin>>x;

}

friend void display( sample);

};

inline void display(sample abc)

{

cout<<”entered number is “<<abc.x;

}

void main( ){

sample obj;

obj. getdata( );

display(obj);

}

Q8. Write a program to grant friendship to another class.

Ans. A class can have friendship with another class. Let there be two classes, first and second. If 

the class first grants its friendship with the other class second, then the private data members

of the class first are permitted to be accessed by the public members of the class second.

#include<iostream.h>

class first{

friend class second;

 private:

int x;

 public :

void getdata( )

{

cout<<”enter the number”;

cin>>x;

}

};

class second

{

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 32/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 32/62

 public:

void disp (first a);

};

inline void second::disp(first a)

{

cout<<”Entered number is “<<a.x;

}

void main( )

{

first objx;

second objy;

objx.getdata( );

objy.disp(objx);

}

Q9. Write a program to define two classes having the same friend.

Ans. A non-member function may have friendship with one or more classes. When a function has

declared to have friendship with more than one class, the friend classes should have forwarddeclaration. It implies that it needs to access the private members of both classes.

Example:

class second;//forward declaration

class first

{

 private:

int x;

 public:

void getdata( )

{

cout<<”enter the value for x”;cin>>x;

}

void disp( )

{

cout<<”Entered number is (x)”<<x;

}

friend int sum(first , second);

};

class second{

 private:

int y;

 public:void getdata( )

{

cout<<”Enter the value for y”;

cin>>y;

}

void display( )

{

cout<<”Entered number is (y) “<<y;

}

friend int sum(first, second);

};

int sum( first one , second two)

{

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 33/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 33/62

int c;

c=one.x+two.y;

return c;

}

void main ( )

{

first a;

second b;

a.getdata( );

 b.getdata( );

a.disp( );

 b.display( );

int c=sum(a,b);

cout<<”Sum of the two private data variables is “<<c;

}

Q10. What is function overloading? How the compiler will decide which function to use?

Explain with example.Ans. Function overloading is a logical method of calling several functions with different arguments

and data types that perform basically identical things by the same name.

The compiler classifies the overloaded 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.

In this example, a function ‘ Add ‘ is overloaded to find the sum of integer variables.

if we pass a&b then Add(int ,int) is executed.

if we pass a,b&c then Add(int ,int,int) is executed.

If we pass a,b,c,d then Add(int ,int,int,int) is executed.

#include<iostream.h>

void Add(int,int);void Add(int,int,int);

void Add(int,int,int,int);

void main( )

{

int a=4,b=5,c=6,d=7;

Add(a,b);

Add(a,b,c);

Add(a,b,c,d);

}

void Add(int a,int b)

{

cout<<“sum of a&b=“<<a+b;}

void Add(int a,int b,int c)

{

cout<<“sum of a,b,c=“<<a+b+c ;

}

void Add(int a,int b,int c,int d)

{

cout<<“a+b+c+d=“<<a+b+c+d;

}

Q11. What is operator overloading? How ‘+’ can be overloaded with matrix addition?

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 34/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 34/62

Ans. C++ has the ability to overload operators. Objects derived from composed types can accept

operators, which would not be accepted otherwise, and we can even modify the effect of 

operators that they already admit. Here is a list of all the operators that can be overloaded:

+ - * / = < > += -= *= /= << >>

<<= >>= == != <= >= ++ -- % & ^ ! |

~ &= ^= |= && || %= [] () new delete

To overload an operator we only need to write a class member function whose name is

operator followed by the operator sign that we want to overload, following this prototype:

type operator sign (parameters);

#include <iostream.h>

class dis {

private :

int feet ;

float inch;

 public :

dis( int f,float I)

{

feet = ft;inch=I ;

}

void getdist( )

{

cout<<“Enter feet :”;

cin>>feet;

cout<<“Enter inch :”;

cin>>inch;

}

void showdist( )

{

cout <<feet<<“-”<<inch;}

dis operator + (dis);

};

dis dis::operator + (dis d2)

{

int f=feet+d2.feet ;

float I =inch+d2.inch;

while(I>=12)

{

I - =12 ;

f++ ;

}return dis(f,I)

}

void main( )

{

dis dist1 ;

dist1.getdist( ) ;

dis dist2 ;

dist2.getdist( ) ;

dis dist3 = dist1+dist2;

cout<<“dist=“;

dist3.showdist( ) ;

}

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 35/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 35/62

Q12. What is single inheritance? Write a program to show the concept of single

Inheritance.

Ans. Single inheritance:

Single inheritance is the process of creating new classes from an existing base class. The

existing class is known as the direct base class and the newly created class is called as a

singly derived class.

Single inheritance is the ability of a derived class to inherit the member functions and

variables of the existing base class.

Example:

#include<iostream.h>

class basic_info{

 private:

char name[20];

long int rollno;

char sex;

 public:

void getdata( )

{cout<<”Enter the name of student”;

cin>>name;

cout<<”Enter the rollno”;

cin>>rollno;

cout<<”Enter the sex”;

cin>>sex;

}

void display( )

{

cout<<name<<’\t’<<rollno<<’\t’<<age;

}

};class physical :public basic_info{

 private:

float height, weight;

 public:

void getdata( )

{

 basic_info::getdata( );

cout<<”Enter height and weight”;

cin>>height<<weight;

}

void display( ){

 basic_info::display( );

cout<<height<<’\t’<<weight;

}

};

void main( )

{

 physical a;

a.getdata( );

cout<<”\nName \t Rollno \t Sex \t Height \t Weight”;

a.display( );

}

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 36/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 36/62

Q13. What is Indirect Base class? Explain with Example.

Ans. Derived class can itself serve as a base class. When a derived class is declared as a base of 

another class, the newly derived class inherits the properties of its base classes including its

data members and member functions. A 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.

Example:

class base A

{

-----------

-----------

};

class derivedB:public baseA

{

-----------

-----------

};

class derivedC : public derivedB

{

-----------

-----------

};

derivedB is a base of the class derivedC that is called as in indirect base.

Multiple inheritance

A derived class could inherit from more than one base classes. When this is done it is called

multiple inheritance.

Example:

class A {-----

};

class B{

------

};

class C:public A, public B{

-------

};

The class C is derived from both A and B.

Q14. What is ambiguity in ‘C++’? Write a program to show the ambiguity in multipleinheritance.

Ans. Whenever a data member and member function are defined with the same name in both the

 base and the derived 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 derived class.

Example to show how ambiguity occurs in both base class and derived class:

#include<iostream.h>

class baseA{

 public:

int a;

};

class baseB{

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 37/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 37/62

 public :

int a;

};

class derivedC: public baseA, baseB{

 public :

int a;

};

void main( )

{

derivedC obj;

obj.a=10;// local to the derived class

}

The object of derived class can directly access to its own member rather than the members of 

the base classes.

If one wants to access the members of base classes then the code can be written like

void main( )

{derivedC obj;

obj.a=10;

obj.baseA::a=20; // accessing the base class A member 

obj.baseB::a=90;// accessing the base class B member;

}

Q15. What are virtual functions? Give types, rules. Explain with example.

Ans. It would be nice if the appropriate member function could be selected while the program is

running. This is known as runtime polymorphism. C++ support a mechanism known as

virtual function to achieve runtime polymorphism. At runtime, when it is known what class

object are under consideration, the appropriate version of the function is called. Since the

function is linked with a particular class much later after the compilation, this binding istermed as late or dynamic binding.

Types

1. Simple virtual function(as shown in example below)

2. Pure virtual function(A pure virtual function is a virtual function with no body).

Rules

1. Virtual keyword is necessary with virtual function.

2. Its body can be outside or inside class.

3. Pure virtual function is without body.

//program for demonstration of virtual function

#include<iostream.h>

#include<conio.h>class baseA{

 public:

virtual void display( )

{

cout<<”\nOne”;

}

};

class derivedB:public baseA

{

 public:

virtual void display( )

{

cout<<”\nTwo”;

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 38/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 38/62

}

};

class derivedC:public derivedB

{

 public:

virtual void display ( )

{

cout<<”\nThree”;

}

};

void main( )

{

 baseA obja;

derivedB objb;

derivedC objc;

 baseA *ptr[3];

 ptr[0]=&obja;

 ptr[1]=&objb; ptr[2]=&objc;

for(int i=0;i<3;i++)

{

 ptr[i]->display( );

}

}

Q16. Describe the importance of destructor functions and write a program that illustrates the

working of destructor function.

Ans. A destructor is a function that automatically executes when an object is destroyed. A

destructor function gets executed whenever 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.

PROPERTIES OF DESTRUCTOR FUNCTION:

1. They have same name as that of class.

2. These are automatically called when object is destroyed.

3. They have no return type.

4. These cannot be declared static, const, volatile.

5. They accept no arguments.

#include<conio.h>

#include<iostream.h>

class ABC{

 public:

ABC( )//constructor {

cout<<”\nClass initialized”;

}

~ABC( )

{

cout<<”\nData deleted”;

}

};

void main( )

{

ABC obj;

{

ABC obj1;

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 39/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 39/62

}

}

Q17. What are inline functions? How are they created in ‘C++’? Explain with Example.

Ans. 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 size of the object code is considerably reduced with the use of inline function.

The use of inline function increases the execution speed of program.

Program to input date and display it using inline functions:

#include<iostream.h>

#include<conio.h>

class date

{

 private:

int day,month,year;

 public:

void setin(int dayin,int monthin,int yearin);

void show();};

inline void date ::setin(int dayin,int monthin,int yearin)

{

day=dayin;

month=monthin;

year=yearin;}

inline void date::show()

{

cout<<day<<"-"<<month<<"-"<<year<<endl;

}

void main()

{date d1,d2,d3;

d1.setin(24,5,2000);

d2.setin(30,7,98) ;

d3.setin(13,7,99);

cout<<"first date=";

d1.show();

cout<<"second date";

d2.show();

cout<<"third date";

d3.show();

getch();

}

Q18. Write a program to calculate the area of a triangle, rectangle, circle and square using

inheritance.

Ans.

Class Common

{

 protected :

int a,b;

float res ;

};

Class triangle : public common{

 public :

void showarea ()

{

res= 3.14 * a*a;

cout <<” Area of cirlce " << res

}

};

class square : public common{

 public

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 40/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 40/62

void getch ( )

{

cout << “Enter base & height “;

cin a>> b;

}

void showarea ( )

{

res =0.5* a*b;

cout << “Area of triangle”<<res;

}

};

Class rectangle : public common

{

 public :

void getlb ()

{

cout << “enter length & breadth of 

rectangle “;cin>> a>> bi;

}

void showarea ()

{ res=a*b;

cout << “Area of Rectangle” << res

}

};

class circle : public common

{

 public :

void gets (){ cout <<” Enter radius ";

cin >> ai;

}

void getside ()

{

cout <<” Enter side for square " ;

cin >> a;

}

void show area ()

{

res =a*a;

cout << “Area of square”<< res;

}

};

void main ()

{

Triangle t ;

Circle c;

Square s;

Rectangle r ;

t.getch () ;t.showarea ();

c.gets ();

c.showarea ();

s.getside ();

s.showarea ();

r.getlb ();

r.showarea ();

}

Q19. Write a program to maintain employee record.

Ans.

Class employee

{

 private :

char name [20]

int age;

long int basic ;

 public :

void get data ()

{

vout <<Enter name of employee";

cin >> name :

cout << Enter age & basic pay"

cin >> name :

cout << "Enter age & basic pay:

cin > age >> baisc ;

}

void Show ()

{ cout << Name : << name ;

cout << endl << "age ; <<age;

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 41/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 41/62

cout << endl << Sex '<< sex ;

}

};

Void main ()

{

employee e1 , ez ;

el. getdata();

ez. getdata ();

el . show ();

ez. show ();

}

Q20. Write a program to show operator overloading.

Ans. Class area

{

 private:

int a, b;

float ar ;void input (int a1)

{

a= a1;

}

void input (int a1, int b1)

{

a=a1;

 b=b1;

}

Area operator ++ ()

{

ar = 3.14 * a*a;}

Area operator – ( )

{

ar = a*b;

return * this;

}

Area show()

{

cout<<ar;

}};

Void main ()

{

Area Rect , Cir;

Rect.input (20, 30);

Rect ++;

Cir.input (10) :

Cir --;

Rect . Show ();

Cir . show ( ) ;

}

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 42/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 42/62

Q21. Differentiate between all the conversions.

Ans. 1. Basic to class type

This conversion form basic to class type is easily carried type. It automatically done by the

compiler with the help of in-built routines or by applying typecasting. In this the left-hand

operand of = sign is always class type and right-hand operand is always basic type. The

 program given below explains the conversion from basic to class type.

2. Class type to basic data type

In this type, left hand operand is always of basic data type and right –hand operand is

always of class type. While carrying this conversion, the statement should satisfy the

following conditions:

1. The conversion function should not have any argument.

2. Do not mention return type

3. It should be a class member function.

3. One class type to another class type

When an object of one class is assigned to object of another class. It is necessary to give

clear-cut instructions to the compiler. How to make conversion between these two user 

defined data type. The method must be instructed to compiler. There are two ways to convert

object data type from one class to another.1. Define conversion operator function in source class

2. One argument constructor in a destination class

Q22. Write a c++ program to extract a row or column from a matrix.

Ans.

#include<iostream.h>

#include<conio.h>

void main()

{

int a[10][10],m,n,i,j,p,q;

clrscr();

cout<<"enter no of row and col";cin>>m>>n;

cout<<"enter data in matrix";

for(i=0;i<m;i++)

for(j=0;j<n;j++)

cin>>a[i][j];

cout<<"display data in matrix";

for(i=0;i<m;i++)

{

for(j=0;j<n;j++)

{

cout<<"\t"<<a[i][j];}

cout<<"\n";

}

}

cout<<"\nenter row to extract";

cin>>p;

for(i=0;i<n;i++)

cout<<"\t"<<a[p][i];

cout<<"\nenter col to extract";

cin>>q;

for(i=0;i<m;i++)

cout<<"\n"<<a[i][q];

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 43/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 43/62

getch();

}

Q23. Write a program to read a set of floating point numbers using concept of overloading.

Ans.

#include<iostream.h>

#include<conio.h>

void getdata(int x,int y);

void getdata(int x,int y,int z);

void main()

{

float i,j,k;

clrscr();

cout<<"enter data";

cin>>i>>j>>k;

getdata(i,j);

getdata(i,j,k);

getch();}

void getdata(int x,int y)

{

cout<<"sum="<<x+y;

}

void getdata(int x,int y,int z)

{

cout<<"sum="<<x*y*z;

}

Q24. Write a C++ program that declares a class called employee with data members: name,father name, residence address.

Ans.

class employee

{

 private:

char name[10];

char fname[20];

char address[20];

 public:

void getdata();

{

cout<<”enter data”cin>>name;

cin>>fname;

cin>>address;

}

void display()

{

cout<<name;

cout<<fname;

cout<<address;

}

};

void main()

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 44/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 44/62

{

employee e;

clrscr();

e.getdata();

e. display();

getch();

}

Q25. What are different types of membership functions? Explain structure of class.

Ans. Membership functions:

1. Constructor 

2. Friend function

3. Destructor.

4. Static member function

5. Virtual function

6. Inline member function

STRUCTURE OF CLASS

Class <classname>{

 private:

datamember 1;

datamember 2;

datamember 3;

 public:

member function1();

member function2();

member function3();

};

Q26. How constructors and destructors can be inherited?Ans. If any base class contains a constructor with one or more arguments, then it is mandatory for 

derived class to have a constructor and pass arguments to base class constructors. While

applying inheritance we usually create objects using derived class. Thus it makes sense for the

derived class to pass arguments to base class constructor.

When both derived and base class contains constructors, the base class constructor is executed

first and then constructor in derived class is executed. The constructor of the derived class

receives the entire list of values as its arguments and passes them on to the base constructors

in the order in which they are declared in the derived class. The base constructors are called

and executed before the statements in the body of derived constructor.

General Form of derived constructor:

Base1(arglist1)

Base2(arglist2)………………

 baseN(arglistN)

{

// body of derived constructor 

}

Example:

#include <iostream>

using namespace std;

class alpha

{

int x;

 public:

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 45/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 45/62

alpha(int I)

{

x = i;

cout<< ”alpha initialized \n”;

}

void show_x(void)

{

cout<< “x = “<<x << “\n”;

}

};

class beta

{

float y;

 public:

 beta(float j)

{

y = j;cout<< “ beta initialized \n”;

}

void show_y(void)

{

cout<< “ y = “ <<y << “\n”;

}

};

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;

cout<< “gamma initialized \n”;

}

void show_mn(void)

{

cout<< “ m = “<<m <<”\n”;

cout<<” n = “<<n <<”\n”;

}

};int main( )

{

gamma g(5, 10.75, 20, 30);

cout<< “\n”;

g.show_x( );

g.show_y( );

g.show_mn( );

return 0;

}

Q27. Can we pass entire structure as argument to function?

Ans. Yes, entire structure can be passed as argument to a function and can also be returned.

For example

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 46/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 46/62

struct student

{

char name [20] ;

int age ;

int fee;

};

struct student s[ ];

void main()

{

----------------------

----------------------

fi (struct student s[ ] )

}

struct student fi (struct student s[ ] )

{

-

-

--

}

Q28. Using operator overloading, write a program for floating point number operation like

‘+’ and ‘-‘.

Ans.

#include<iostream.h>

struct complex

{float real;

float imag;

};

complex operator +(complex a, complex b)

{

complex c;

c.real=a.real+b.real;

c.imag=a.imag+b.imag;

return (c );

}

complex operator –(complex a, complex b);

{

complex c;

c.real=a.real+b.real;

c.imag=a.imag+b.imag;

return ( c );

}

void main( )

{

complex a,b,c;cout<<”Enter the first complex number”;

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 47/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 47/62

cin>>a.real>>a.imag;

cout<<”Enter the second complex number”;

cin>>b.real>>b.imag;

cout<<”\nComplex number operations”;

cout<<endl<<” a - > add”<<endl<<”s - > subtract “;

cout<<endl<<”Enter your choice”;

char ch;

cin>>ch;

switch ( ch)

{

case ‘a’ : c=a+b;

cout<<endl<<”Addition of two complex numbers is :”;

cout<<c.real<<”+I”<<c.imag;

 break;

case ‘s’: c=a-b;

cout<<endl<<”subtraction of two complex numbers is :”;

cout<<c.real<<”+I”<<c.imag; break;

}

}

Q29. Differentiate between abstraction and data hiding. Why classes in C++ are abstract?

Ans. OOP encapsulates data and functions into packages called objects. The data & functions of an

object are intimately tied together. Objects have the property of information hiding. This

means that although objects may know how to communicate with each other, they normally

do not know how other objects are implemented. That is, implementation details are hidden

within the objects themselves.

Abstraction is very close to data hiding. Abstraction refers to the act of representing essential

features without including the background details or explanations. Data abstraction isconcerned with separation the behaviour of data object from its representation or 

implementation.

Abstract class: An abstract class is one that is not used to create object. Classes that declare a

 pure virtual function is called an abstract class. It is used as a base class for deriving. It

defines properties common to other classes derived from it. Since an abstract class contains

one or more functions for which there is no definition, no objects can be created using an

abstract class.

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 48/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 48/62

Section – C 2 Marks Questions

[QUESTIONS 1 TO 30] [PAGE 47 TO 49]

Q1. What are the different file modes? 

Ans.  There are three file opening modesThese are:

Read mode

Write mode

Append mode

Various streams are used to open the files in such modes, these are:

ios :: in:- For read mode

ios :: out:- For writing in a file

ios :: app:- Append at end of file

ios::ate:- Goto end of file on opening.

The file can also be set to be a binary file by using binary keyword as - ios :: binary

Q2. What is use of redirection operator?

Ans. The << and >> are used as redirection operators. These operators accept output from one

stream that output will act as input to other stream.

Q3. What is a stream?

Ans.  Stream: It is defined as collection of bytes. It 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 provides data to program is called as input stream and destination stream that

receives output from program is called as output stream.

Q4. What is Buffer?

Ans. It is a temporary memory used to store data. Fstream class inherits two buffers one for inputand another for output, and synchronizes the movement of the file pointers on these buffers.

Q5.  What are the functions available in C++ to manipulate the file pointers? Explain.

Ans. Open (): This is the function used to open a file. A string parameter, which is actually

the name of the file to be opened, is passed to the function.Close (): This is the function used to close the already opened file.

Eof (): this function is used to check whether a file pointer has reached at end of the file.

Fail (): The function return true if it failed to open the file requested.

Q6. What is a priority queue?

Ans. Priority queues are essentially a list of items in which each item has a priority associated with

it. The priorities are associated depending on preference rules. Different items have different priorities to them. An item having higher priority is given preference over lower priority.

Priority queues are generally used by the operating system to manage various resources such

as printer and processor.

Q7. How is the mid point in a binary tree calculated?

Ans. Root of the binary tree is considered to be the mid point of the tree.

Q8. What is an array? How array is stored in memory?

Ans. Array is collection of homogeneous data elements. They are stored in continuous memory

locations. They are accessed by using index value.

Int a[5];

12 4 45 67 68

1000 1002 1004 1006 1008

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 49/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 49/62

1000 is the location of the first element of the array. As the int data type takes two bytes of 

the memory so the next element is stored at 1002 and so on.

Q9. Define multidimensional array.

Ans. Multidimensional 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. An example of the two

dimensional array is the matrix

Q10. Differentiate between structured and modular programming.

Ans. When a monolith software is divided into modules is called modular programming. It is easy

to solve a smaller problem than a bigger problem. All the modules are combined to solve a

 bigger problem.

A structured approach follows the concept of coupling, cohesion, information hiding, DFD’s

etc.

Q11. What is garbage collection?

Ans. The operating system of a computer may periodically collect all the deleted spaces onto thefree storage list. Any technique, which does this collection, is called Garbage Collection. This

collection can be done in two passes:

Marking phase: In this phase all the allocated block are tagged.

Collection Phase: In this phase all the untagged blocks are stored into free list.

Q12. Give two applications of binary tree.

Ans.  User interface: The best example for this is file system organization and windows graphical

interface.

Database System: Balanced search trees are good in situations that require both sequential

efficiency and random access while performing insertion and deletion.

Q13. What do you mean by circular queue?Ans. A circular queue is the same as a queue but the front and rear ends of a queue are joined

together to form a circular ring.

Q14. What is value of following postfix expression?

5, 4, 6, +, *, 4, 9, 3, /, +, *

Ans. 350.

Q15. Define AVL tree.

Ans. A binary search tree in which the difference of heights of the right and left sub-trees of any

node is less than or equal to one is known as AVL tree. The name is derived from the names

of inventors who are Adelson-Velskii and Landi.

Q16. What do you mean by sparse matrix?

Ans. An m x n matrix is said to be sparse if many of its elements are 0. A matrix that is not sparse

is called dense matrix. 

Q17. What is a stack?

Ans. A stack is a list of elements in which an element may be inserted or deleted only at one end,

called the top of the stock.

Q18. Define queue.

 Ans. A queue is a linear list of elements in which deletions can take place only at one end, called

the ‘front’ & insertions can take place only at the other end called the ‘rear’.

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 50/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 50/62

Q19. What is a linked list?

Ans.  A linked list or one-way list is a linear collection of data elements, called nodes, where the

linear order is given by means of pointers. Each node is divided into 2 parts. The first part

contains the information of the element & the second part called the link field, contains the

address of the next node in the list.

Q20. What is binary search tree?

Ans. A binary tree in which all elements in the left sub tree of a node are less than the contents of 

root & all elements in the right sub tree are greater than or equal to the contents of the root.

Such a tree is called a binary search tree.

Q21. What are the applications of binary trees?

Ans. A binary tree is a useful data structure when two- way decisions must be made at each point

in a process. E.g. Suppose 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. Each successive node is

compared to the root, if it matches, we have a duplicate of a number is lesser, we examine the

left sub tree, else if it is larger, we examine the right sub tree.

Q22. What is the level & height of a binary tree?

Ans. Level: The level of any mode is equal to length of its path from root to the mode: The root of 

any tree has level equal to zero.

Height: It is equal to one + maximum level in a tree.

Q23. What is a data structure?

Ans. The logical or mathematical model of a particular organization of data is called a data

structure.

Q24. Differentiate between linear & non-linear data structure.

Ans. 1. Linear Data Structure:

A data structure is said be linear if its elements are stored sequentially in the form of a linear list e.g. stacks, linked lists.

2. Non-linear Data structure:

A data structure is said to be non-linear if its elements are not stored sequentially in the form

of linear list e.g. trees & graphs.

Q25. What are the applications of stacks?

Ans. Using stacks, we can perform the process of recursion. Stacks are used in recursion to fetch

an element from top one by one. The other application of stack is calculation of postfix

expression where each operator is fetched one by one.

Q26. What are the applications of queues?

Ans. One of the important areas to which queues can be applied is that of simulation. It is the

 process of forming an abstract model from a real situation in order to understand the impact

of modifications & the effect of introducing various strategies on the situation. The major 

advantage of simulation is that it allows experimentation without modifying the real situation.

Areas such as military operations are safer to simulate.

Q27. What is dequeue?

Ans. A dequeue also known as double ended queue is a link of queues in which elements can be

added or removed from at either end but not in the middle.

Q28. What is time & space complexity?

Ans. Time complexity is related to the performance requirements of an algorithm.

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 51/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 51/62

Space complexity is the amount of memory it needs to run to completion.

Q29. What are primitive data structures?

Ans. These are the data structures that are directly operated upon by machine level instructions.

Examples are integers, real numbers, characters, logical data item etc.

Q30. What is a doubly linked list?

Ans. A singly linked list can move only in one direction in certain applications, it is sometimes

required that the list be traversed in either a forward or reverse direction. This property of a

linked list implies that each mode must contain two link fields instead of one. The links are

used to denote the predecessor & successor of a mode. The link denoting the predecessor & of 

a node is called the left link & that devoting its successor is called the right link. A list

containing this type of mode is called a doubly linked list.

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 52/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 52/62

Section – C 5 Marks Questions

[QUESTIONS 1 TO 20] [PAGE 50 TO 60]

Q1. How File Handling is done in C++?

Ans. File is a collection of data or a set of characters. There are two types of files in C++.

Sequential and random access. In sequential files the data or text will be stored or read back 

sequentially. In random access files, data can be accessed and processed randomly.

The handle file fstream in supports the input/outs stream processing techniques. The

Following methods are used in C++ to read and write files:

If stream – To read a stream of object from a specified file. of stream – to write a stream of 

object on a specified file.

The following attributes are used for various file operations.ios :: in open a file for reading.

ios :: out open a file for writing

ios :: app append at end

ios :: binaryopen in binary mode.

Q2. Explain the following functions.

Ans.

a) Eof (): It is function to check whether a file pointer has reached the end of file character 

or not. It has then the function return non zero else return 0.

b) Fail (): It is used to check if file has been opened successfully. If it fails then it return non

zero character.

c) Bad (): It return non zero when invalid file operation has been attempted.d) Good (): It is function to check whether the previous file operation has been successfully

or not.

Q3. What is a random access file? Explain the syntactic rule for the following random access

file member function?

a) seekp

b) seekg

c) tellg

d) tellp

Ans.  RANDOM FILE: In random access file the file pointer can be moved to any location in thefile instead of moving it sequentially. This approach is used with database files.

SEEKP: Moves put pointer to specified location.

E.g. infile.seekp(10);

It will move pointer to 10 number byte.

It can take 2 arguments also.

Seekp(offset,refposition);

SEEKG: Moves get pointer to specified location.

E.g. infile.seekg(10);

It can take 2 arguments also.

Seekg(offset,refposition);

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 53/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 53/62

TELLG: Gives the current position of get pointer.

E.g. ofstream fileout;

fileout.open(“hello”,ios::app);

int p=fileout.tellg();

TELLP: Given the current position of get pointer.

E.g. ofstream fileout;

fileout.open(“hello”,ios::app);

int p=fileout.tellp();

Q4. Write an algorithm for Bubble sort & explain with an example.

Ans. Algorithm BUBBLE (DATA, N)

Here DATA is an array with n elements. This algorithm sorts the elements in DATA.

1. Repeat steps 2 & 3 for k = I to N-I

2. Set PTR: = 1 [Initializes pass pointer]

3. Repeat while PTR ≤ N-K [Execute pass]

a) If DATA [PTR] > DATA [PTR +1], then interchange DATA [PTR] & DATA

[PTR+1][End of If structure]

 b) Set PTR: = PTR+1

[End of inner loop]

[End of step 1 outer loop]

4. Exit

Example: 32 51 27 85 66 23 13 57

A1 A2 A3 A4 A5 A6 A7 A8

a) Compare A1& A2: 32 <51 → no change

 b) A2&A3: 51 > 27, interchanging 51 & 27c) A3&A4 : no change

d) A4&A5: 85 > 66, interchange 85 & 66

e) A5&A6:  85 > 23, interchange 23 & 85

f) A6&A7: 85 > 13, interchange 13 & 85

g) A7&A8: 85 > 57, interchange 57 & 85

This is pass 1

Similarly, in every pass the greater element will be moved towards the end.

Since the array has 8 elements, it is sorted after the seventh pass i.e. (n-1) in pass.

Q5. Write non-recursive & recursive procedures to find the factorial of a given number.

Ans.

Procedure: FACTORIAL (FACT, N)

This procedure calculates N! & returns the value of the variable FACT in a non-recursive

manner.

1. If N=0, then set FACT:=1&Return.

2. Set FACT: =1 [Initializes FACT for roop]

3. Repeat for K = I to N

Set FACT: = K * FACT

[End of roop]

4. Return

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 54/62

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 55/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 55/62

Hire DATA is a linear array with N elements & ITEM is a given item of information. This

algorithm finds the location LOC of ITEM in DATA, or sets LOC: = 0 if the search is

unsuccessful.

1. [Insert ITEM at the end of DATA]

Set DATA [N+1]: = ITEM

2. [Initialize counter]. Set LOC: =1

3. Search for ITEM]

Repeat while DATA [LOC] ≠ ITEM

Set LOC: LOC +1

[End of loop]

4. [Successful?] If LOC= N+1, then Set LOC: = 0

5. Exit.

Q9. Write an algorithm to search an

element from a binary search tree.

Ans.

Variables to be used:1.INFO is the information field of 

node.

2.LEFT points to left child

3.RIGHT Points to right child

4.PAR points to parent node

5.LOC points to ITEM if exists

otherwise points to NULL

6.ITEM which is to search

7.ROOT is the root of tree

Algorithm:

1. If ROOT=NULL, thenLOC:=NULL and PAR:=NULL

2. If ITEM=INFO[ROOT] then set

LOC:=ROOT and PAR:=NULL

3. If ITEM<INFO[ROOT], then

Set PTR:=LEFT[ROOT] and

SAVE:=ROOT

Else:

Set PTR:=RIGHT[ROOT] and

SAVE:=ROOT

1.Repeat steps 5 and 6 while PTR ≠

 NULL:2.If ITEM=INFO[PTR], then: set

LOC:=PTR and PAR:=SAVE and return

3.If ITEM<INFO[PTR], then:

set SAVE:=PTR and PTR:=LEFT[PTR]

else

set SAVE:=PTR and PTR:=RIGHT[PTR]

set LOC:=NULL and PAR:=SAVE.

Exit

Q10. Write an algorithm to delete a leaf 

node or the node, which has exactly one

child.

Ans.Variables to be used:

1.INFO is the information field of 

node.

2.LEFT points to left child

3.RIGHT Points to right child

4.PAR points to parent node

5.LOC points to ITEM if exists

otherwise points to NULL

6.ITEM which is to search

7.ROOT is the root of tree

8.CHILD is the child to delete

Algorithm:9.If LEFT[LOC]=NULL and

RIGHT[LOC]=NULL

Set CHILD:=NULL

Else

if 

LEFT[LOC]≠ NULL

Set

CHILD:=LEFT[LOC]

Else

Set CHILD:=RIGHT[LOC]

10.If PAR ≠ NULL

If LOC=LEFT[PAR]

Set LEFT[PAR]:=CHILD

Else: Set

RIGHT[PAR]:=CHILD

Else:

Set ROOT:=CHILD

11.Return

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 56/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 56/62

Q11. Discuss the advantages & disadvantages of circular linked list.

Ans. Circular lists have certain advantages over singly linked list. The first advantage is that in a

circular list every mode is accessible from a given mode.

A second advantage is concerned with the deletion operation. As we know that in order to

delete a mode in a singly linked list, it is necessary to give 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 required starting from the first node of the list. In the case

of circular list, this requirement does not exist since the search for the processor of the mode

to be deleted can be initiated from that mode itself.

However, there is a disadvantage in using circular lists. It is possible to get into an infinite

loop. In processing a circular list, it is important that we are able to detect the end of the list.

Q12. What are the operations that can be performed on a queue? Write procedures to

implement these operations.

Ans. A queue is linear list of elements in which deletions can take place only at one end, called the

“front” & insertions can take place only at the other end called the “rear”.

Procedure: QINSERT (Q, F, N, R, Y)Given F & R, pointers to the front & rear elements of a queue, a queue Q consisting of N

elements & an element Y, this procedure inserts Y at the rear of queue. In the beginning, F&R 

have been set to zero.

1. [Overflow?]

If R≥N then write (OVERFLOW)

Return.

2. [Increment rear pointer]

R: =R+1

3. [Insert element]

Q[R]: =Y

4. [Is front pointer properly set?]If F=0

Then F:=1

Return.

Procedure: QDELETE (Q, F, R)

Given F&R, pointers to the front & rear elements, & the queue Q, which they correspond, this

function deletes & returns the last element of the queue.

Y is a temporary variable.

1.) [Underflow]

If F=0

Than write (‘underflow’)Return (0) [0 deviates an empty queue]

2.) [Delete element]

Y ←Q[F]

3.) [Queue empty?]

If F=R then F: =R: =0

Else F: =F+1

4.) Return element]

Return (Y)

Q13. Write an algorithm for transforming infix expression into postfix expression with

example.

Ans. POLISH (Q, P)

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 57/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 57/62

Suppose Q is an arithmetic expression written in infix mutation. This algorithm finds the

equivalent postfix expression P.

1. Push “(“ onto STACK & add) “ to the end of Q

2. Scan Q from left to right & repeat steps 3 to 6 for each element of Q until the stack is

empty.

3. If an operand is encountered, add it to P.

4. If a left parenthesis is encountered, push it onto STACK.

5. If an operator Q is encountered, then

a) Repeatedly pop from STACK & add to P each operator, which has the same

 precedence as or higher precedence than Q.

 b) Add Q toy STACK 

[End of If structure]

6. If a right parenthesis is encountered

a) Repeatedly pop from STACK & add to P each operator until a left parenthesis is

encountered.

 b) Remove the left parenthesis [Do not add the left parenthesis to P][End of If structure]

[End of step 2 Loop]

7. Exit

Example: Q: A+ (B*C-(D/E↑F) * Gill) # H

Symbol Scanned STACK Expression P

1) A ( A

2) & (+ A

3) ( (+( A

4) B (+( A B

5) * (+(* A B6) C (+(* A B C

7) -- (+(- A B C *

8) ( (+(-( A B C *

9) D (+(-( A B C * D

10) / (+(-(/ A B C * D

11) E (+(-(/ A B C * D E

12) ↑ (+(- (/ ↑ A B C* D E

13) F (+ (- (↑ A B C * D E F

14) ) (+ (- A B C * D E ↑/

15) * (+(- * A B C * D E F ↑/

16) G (+ (- * A B C * D E F↑/G17) ) (+ A B C * DE F↑G*-

18) * (+ * A B C * D E F↑G*-

19) 1+ (+ * ABC *DEF ↑/G * -H

20) ) ABC DEF↑/G-H*+

Q14. Write procedure for performing insertion & deletion operations on a circular queue.

Ans. A circular queue is the same as a queue but the front & rear ends of a queue are joined

together to form a circular ring.

Procedure: CQINSERT (F, R, Q, N, Y)

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 58/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 58/62

1. Reset rear pointer? ]

If R = N then R: =1

Else R: = R+1

2. [Overflow?]

If F = R 

Then write (‘overflow’)

Return

3. [Insert element]

Q[R] ←Y

4. [Is front pointers properly set?]

If F=0

Then F←1

Return.

Function: CQDELETE (F, R, Q, N)

1) [Underflow?]

If F=0 then write (‘underflow’)

Return (0)2) [Delete element]

Y ←Q [F]

3) [Queue Empty?]

If F=R 

Then F: R: =D

Return (y)

4) [Increment front pointer]

If F=N then F:=1

Else F: =F + 1

Return (y)

Q15. Write algorithms for Tree traversals.Ans.  Algorithm PREORDER (T): Given a binary tree whose root mode address is given by a

 pointer variable Toy, this algorithm traverse the tree in preorder in a recursive manner.

1. [Process the root node]

If Toy ≠ NULL then write (DATA (Toy) )

Else write (‘Empty Tree”)

Return.

2. [Process the left subtree]

If LPTR ≠ NULL

Then call PREORDER (LPTR (7) )

3. [Process the right subtree0If RPTR (T) ≠ NULL

Then call PREORDER (RPTR (T) )

4. Exit

Algorithm INORDER (T):

1. [Check for empty tree]

If T= NULL

Then write (‘empty tree’)

Return.

2. [Process the left subtree]If LPTR ≠ NULL

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 59/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 59/62

Then call IN ORDER (LPTR (T)

3. [Process the root mode]

Write (DATA (T))

4. [Process the right subtree]

If RPTR ≠ NULL

Then call RINORDER (RPTR (Toy)))5. Exit.

Algorithm POSTORDER (T):

1. [Check for empty tree]

If Toy=NULL then write (‘Empty tree’)

Return

2. [Process the left subtree]

If LPTR (T) ≠ NULL

Then call POSTORDER (LPTR (T))

3. [Process the right subtree]

If RPTR (Toy) ≠ NULL

Then call POSTORDER (RPTR (T))4. [Process the root mode]

Write (DATA (Toy)

5. Exit

Q16. What are linked lists. How do they overcome the drawbacks of arrays.

Linear Linked Lists

Ans. Linked List

List means to a linear collection of data items. Till now we are storing elements in array.

Arrays has some disadvantages like:

1.Wastage of memory, because total space allocated must be known in advance, otherwise

enough space can be wasted.

2.Some operations like Insertion and Deletions require extra time, because insertion anddeletion requires enough shifting of elements.

Due to these disadvantages we use dynamic memory allocation i.e., using Linked List.

A linked list is a linear collection of data elements, called nodes. Pointers give the linear 

order. Each node is divided into two or more parts. Concept of linked list uses dynamic

memory allocation. A linked can be of the following type.

• Linear linked list or one-way list

• Double linked list or two way list

Linear linked list:

In a linear linked list, also called singly linked list, each node is divided in two parts:

• First part contains the information of the element, and

• Second part, called the link field contains the address of the next node in the list

We require a pointer variable Start, used that contains the address of the first element of the list. End

of list is denoted by NULL. Link field of last node contains NULL.

This is shown in fig

100 101 102 110 x

Head

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 60/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 60/62

Q17. Define pointer. Write an algorithm to create a linked list & insert an item into a linked

list.

Ans. A pointer is a variable that stores the address of another variable.

Algorithm: INFIRST (INFO, LINK, START, AVAIL, ITEM). This algorithm inserts ITEM

as the first mode in the list.

1. [Overflow?] If AVAIL = NULL

then: Write overflow L Exit

2. Remove first mode from AVAIL list]

Set NEW: = AVAIL and AVAIL:= LINK [AVAIL]

3. Set INFO [NEW]: = ITEM [Copies new data into new mode.

4. Set LINK [NEW]: =START [New mode points to original first mode].

5. Set START: = NEW [Changes START so it points to the new mode].

6. Exit.

Q18. Write a program to maintain a file.

Ans.

void main (){

ofstreams in file ;

infile .open ("abc. txt");

char name [20]:

int age;

cout<<" Enter name ;"

cin > name;

cout << Enter age";

cin >> age;

infile << name <<It << age;

infile close ();

}

Q19. Write a program to copy the content of one file to another.

Ans.

#include<iostream.h>

#include<fstream.h>

#include<iomanip.h>

void main()

{

ofstream ofile;

ifstream ifile;

char fname1[10],fname2[10];char ch;

cout<<”Enter the source file name”;

cin>>fname1;

cout<<”Enter the target file name”;

cin>>fname2;

ifile.open(fname1);

if( ifile.fail())

{

cerr<<”File not found”;

return;

}

ofile.open(fname2);

Lakhvinder singh grewal

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 61/62

8/8/2019 Notice C++

http://slidepdf.com/reader/full/notice-c 62/62

SUBJECT: ‘C++’ (PGDCA/MSC-1) 62/62

s.show( );

}

outfile.close( );

}