You are on page 1of 66

II YEAR / IV SEMESTER

(ELECTRICAL AND ELECTRONICS ENGINEERING)


CS6456 - OBJECT ORIENTED PROGRAMMING
UNIT - I
OVERVIEW

COMPILED BY
M.KARTHIKEYAN, M.E., (AP/IT)

VERIFIED BY

HOD

PRINCIPAL

CORRESPONDENT

DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING


SENGUNTHAR COLLEGE OF ENGINEERING TIRUCHENGODE
1

CREDIT POINT
ANNA UNIVERSITY, CHENNAI
AFFILIATED INSTITUTIONS
R-2013
B.E. ELECTRICAL AND ELECTRONICS ENGINEERING
SEMESTER IV

SL.

COURSE

COURSE TITLE

Numerical Methods

EE6401

Electrical Machines - I

3.

CS6456

Object Oriented Programming

4.

EE6402

Transmission and Distribution

5.

EE6403

Discrete Time Systems and Signal Processing

6.

EE6404

Measurements and Instrumentation

Object Oriented Programming Laboratory


Electrical Machines Laboratory - I

0
0
18

0
0
2

3
3
6

2
2
24

No.
CODE
THEORY
1.
MA6459
2.

PRACTICALS
7.
CS6461
8.
EE6411
TOTAL

SYLLABUS
CS6456 - OBJECT ORIENTED PROGRAMMING

LTPC
3003

UNIT I

OVERVIEW

Why Object-Oriented Programming in C++ - Native Types and Statements


Functions and Pointers- Implementing ADTs in the Base Language.
UNIT II
Data

BASIC CHARACTERISTICS OF OOP


Hiding

and

Member

Functions-

Object

9
Creation

and

Destruction-

Polymorphism data abstraction: Iterators and Containers.


UNIT III

ADVANCED PROGRAMMING

Templates, Generic Programming, and STL-Inheritance-Exceptions-OOP Using C++.


UNIT IV

OVERVIEW OF JAVA

Data types, variables and arrays, operators, control statements, classes, objects,
methods - Inheritance
UNIT V

EXCEPTION HANDLING

Packages and Interfaces, Exception handling, Multithreaded programming,


Strings, Input/Output.
TOTAL: 45 PERIODS
TEXT BOOKS:
1. Ira Pohl, Object-Oriented Programming Using C++, Pearson Education Asia, 2003.
2. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003.

REFERENCES:
1. Herbert Schildt, "The Java 2: Complete Reference", Fourth edition, TMH, 2002
2. Bjarne Stroustrup, The C++ Programming Language, Pearson Education, 2004.
3

3. Stanley B. Lippman and Josee Lajoie , C++ Primer, Pearson Education, 2003.
4. K.R.Venugopal, Rajkumar Buyya, T.Ravishankar, "Mastering C++", TMH, 2003.

UNIT I
OVERVIEW

Why Object-Oriented Programming in C++


Native Types and Statements
Functions and Pointers
Implementing ADTs in the Base Language

LIST OF IMPORTANT QUESTIONS

UNIT I
OVERVIEW

PART-A
1. What are the advantages of object oriented programming over structured
programming? [A/M2015][N/D2012] [N/D2011]
2. What is the advantage of an inline function? [A/M2015]
3. Under what situations, the use of pointer is indispensible? [M/J2014]
4. Define the term encapsulation. [M/J2014]
5. Define an object. [N/D2014]
6. List the object oriented languages. [N/D2014]
5

7. What is object oriented programming ? [or] Define the term object oriented
programming. [M/J2013] [or] What is OOPS paradigm? Illustrate with example.
[M/J2012][M/J2016]
8. What is a function? [M/J2013]
9. What is pointer? [M/J2012]
10. Distinguish between Procedure Oriented Programming and Object Oriented
Programming.
11. Define data abstraction.[M/J2016][A/M15][M/J13][M/J12][N/D13]
12. Distinguish between class and object.[M/J2016][M/J2014]

PART-B
1. Explain the characteristics of OOPS.[M/J2016] [8] [OR] Explain the major principles
of object oriented programming with illustrations and neat diagram. (16m) [A/M2015]
(16m)[M/J2013] [M/J2012] [or] Briefly explain the key concepts of object oriented
programming. (16m) [N/D2014] (12m)[N/D2011]
2. Explain the various operators that are available in C++ with neat illustration for each
of it. (16m) [A/M2015] (4m) [N/D2014]
3. List and explain looping (iteration) statements in C++ with examples. (16m)
[M/J2014] (4m)[A/M2011]
4. Explain about pointers with an example.[M/J2016] [7] [OR] What are pointers? What
are the advantages of using pointers in programming? Explain the addressing mode
required to access memory locations using pointers. (16m) [M/J2014] (4m) [N/D2014]
(4m)[M/J2013] (8m)[N/D2012] (6m)[A/M2011]
5. Explain about Functions and Data types in C++. (8m) [N/D2014] [N/D2013]

6. Discuss about i) const function ii) friend function iii) inline function iv) Volatile function
with suitable illustrations. (12m) [M/J2013] (16m)[M/J2012]
7.

Difference

Between

Procedure

Oriented

Programming

(POP)

&

Object

OrientedProgramming (OOP) [M/J2016][9]


8. Write a C++ program to list out prime numbers between the given two limits.
[M/J2016][8]

NOTES
UNIT I
OVERVIEW
PART-A
1. What are the advantages of object oriented programming over structured
programming? [A/M2015]
Object Oriented Programming is an approach that provides a way of
modularizing programs by creating partitioned memory area for both data and functions
that can be used as templates for creating copies of such modules on demand.
7

Advantages:

Eliminate redundant code


Saves development time and leads to higher productivity
Helps to build secure programs
Easy to partition work
Small programs can be easily upgraded to large programs
Software complexity can easily be managed

2. What is the advantage of an inline function? [A/M2015]

Better than a macro.

Function call overheads are eliminated.

Program becomes more readable.

Program executes more efficiently.

3. Under what situations, the use of pointer is indispensible? [M/J2014]

If sufficient memory is not available during runtime for the storage of pointers, the
program may crash (least possible)

If the programmer is not careful and consistent with the use of pointers, the
program may crash (very possible)

4. Define the term encapsulation. [M/J2014]


The wrapping up of data and function into a single unit (called class) is known as
encapsulation. Data and encapsulation is the most striking feature of a class. The data
is not accessible to the outside world, and only those functions which are wrapped in
the class can access it. These functions provide the interface between the objects data
and the program. This insulation of the data from direct access by the program is called
data hiding or information hiding.
5. Define an object. [N/D2014] [N/D2013]

Objects are the basic run time entities in an object oriented system. They are
instance of a class. They may represent a person, a place etc that a program has to
handle. They may also represent user-defined data. They contain both data and code.
Eg:
class Student
{
public:
int rollno;
string name;
}A,B;
Here A and B are the objects of class Student, declared with the class definition.
6. List the object oriented languages. [N/D2014]

C++

C#

COBOL

Java

PHP

Fortran

Visual Basic

7. What is object oriented programming ? [or] Define the term object oriented
programming. [M/J2013] [or] What is OOPS paradigm? Illustrate with example.
[M/J2012][M/J2016]
OOP treats data as a critical element in the program development and does not
allow it to flow freely around the system. It ties data more closely to the function that
operate on it, and protects it from accidental modification from outside function. OOP

allows decomposition of a problem into a number of entities called objects and then
builds data and function around these objects.

8. What is a function? [M/J2013]


A function is a self contained block or sub program of one or more statements
that performs a special task when called.
Use of function
If we want to perform a task repetitively then it is not necessary to re-write the
particular block again and again. The function defined can be used for any number of
times to perform the task. Using functions, large function can be reduced to smaller
ones. It is easy to debug and find out the errors. It also increases the readability.

9. What is pointer? [M/J2012]


The pointer is used to refer the address of another variable.
The general form is
datatype *variable name;
Eg: int *p;
p=&a;

10

10. Distinguish between Procedure Oriented Programming and Object Oriented


Programming.
Procedure Oriented Programming
Emphasis is on algorithm.
Large programs are divided into smaller
programs called functions.
Functions share global data.
Data move openly around the system
from function to function.
Employs top-down approach in program
design.

Object Oriented Programming


Emphasis is on data rather than
procedure.
Programs are divided into objects.
Functions that operate on the data of an
object are tied together.
Data is hidden and cannot be accessed
by external functions.
Follows bottom-up approach

11. Define data abstraction.[M/J2016][A/M15][M/J13][M/J12][N/D13]


The ability to represent data at a very conceptual level without any details.Data
abstraction refers to, providing only essential information to the outside world and hiding
their background details, i.e., to represent the needed information in program without
presenting the details.
i.e., state without actually knowing how class has been implemented internally.

12. Distinguish between class and object.[M/J2016][M/J2014]


Class
Object
A class in C++ is a user defined type
or data structure declared with
keyword class that has data and
functions (also called methods) as its Instance of class or
Definition
members whose access is governed variable of class.
by the three access specifiers private,
protected or public (by default access
to members of a class is private).
Existence
It is logical existence
It is physical existence
Memory space is
Memory space is not allocated , when
Memory Allocation
allocated, when it is
it is created.
11
created.
it is created many time
Declaration/definition Definition is created once.
as you require.

13. State the need for using the object oriented programming techniques.

Object oriented programming has become the preferred programming approach


by the software industries as it offers a powerful way to cope with the complexity
of real world problems

To represent real life entities in system design

To design system with open interfaces

To improve software productivity and decrease software cost

To ensure reusability and extensibility of modules

14. What is the difference between class and structure?


By default the members of a structure are public whereas the members of a class
are private.
15. What is data hiding?
Data encapsulation is the most striking feature of a class. The data is not
accessible to the outside world, and only those functions which are wrapped in the class
can access it. These functions provide the interface between the objects data and the
program. This insulation of the data from direct access by the program is called data
hiding or information hiding.
16. What is a abstract class?
An abstract class is one that is not used to create objects. It is designed only to
act as a base class to be inherited by other classes .It is usually implemented as a class
that has one or more pure virtual (abstract) functions. The following is an example of an
abstract class:
class AB
{
12

public:
virtual void f() = 0;
};
17. Write the features of object oriented programming?

Emphasis is on data rather than procedure.

Programs are divided into what are known as objects.

Data structures are designed such that they characterize the objects.

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

Data is hidden and cannot be accessed by external functions.

Objects may communicate with each other through functions.

New data and functions can be easily added whenever necessary.

18. Write any four advantages of OOPs.

Through, we can eliminate redundant code and extend the use of existing
classes.

It is possible to save development time and higher productivity.

It is possible to have multiple instances of an object to co-exist without any


interfaces.

It is possible to map objects in the problem domain to those in the program.

The principle of data hiding helps the programmer to build secure programs

Oo systems can be easily upgraded from small to large systems

179. What are the comments in C++?

C++ introduces a new comment symbol //(double slash).it is non executable


code for the program.
13

A comment may start anywhere in the line.

The double slash (//) is used for single line comments.

For example, int a,b;//declare the variables.

The multi line comment is /**/

20. Define tokens. List out the tokens in C++.


The smallest individual units in a program are called tokens. The tokens are
keywords, identifiers, constants, operators, strings.

21. Define expression.


An expression is a combination of operators, constants and variables arranged
as per the rules of the language. An expression may consist of one or more operands
and zero or more operators to produce a value.
22. Explain the purpose of a function parameter. What is the difference between a
parameter and an argument?
A function parameter is a variable declared in the prototype or declaration of a
function:
Eg:

void foo(int x) // declaration -- x is a parameter


{
-----}
An argument is the value that is passed to the function in place of a parameter:

foo(6); // 6 is the argument passed to parameter x


foo(y+1); // the value of y+1 is the argument passed to parameter x
When a function is called, all of the parameters of the function are created as
variables, and the value of the arguments are copied into the parameters. For example:
14

void foo(int x, int y)


{
}
foo(6,7);
When foo() is called with arguments 6 and 7, foos parameter x is created and
assigned the value of 6, and foos parameter y is created and assigned the value of 7.

PART-B
1. Explain the characteristics of OOPS.[M/J2016] [8] [OR] Explain the major
principles of object oriented programming with illustrations and neat diagram.
(16m) [A/M2015] (16m)[M/J2013] [M/J2012] [or] Briefly explain the key concepts
of object oriented programming. (16m) [N/D2014] [A/M2011]
C++ Programming features
The core of the pure object-oriented programming is to create an object, in code,
that has certain properties and methods. While designing C++ modules, we try to see
whole world in the form of objects. For example a car is an object which has certain
properties such as color, number of doors, and the like. It also has certain methods such
as accelerate, brake, and so on.
There are a few principle concepts that form the foundation of object-oriented
programming, these include:

Objects

Classes

Data abstraction and encapsulation

Inheritance
15

Polymorphism

Dynamic binding

Message passing

Objects
Objects are the basic run time entities in an object-oriented system. They may
represent a person, a place, a bank account, a table of data or any item that the
program has to handle. They may also represent user-defined data such as vectors,
time and lists. When a program is executed, the objects interact by sending messages
to one another. For example, if customer and account are to object in a program,
then the customer object may send a message to the count object requesting for the
bank balance. Objects can interact without having to know details of each others data
or code.

Representing an object
Classes
The entire set of data and code of an object can be made a user-defined data
type with the help of class. Once a class has been defined, we can create any number
of objects belonging to that class. Each object is associated with the data of type class
with which they are created.
A class is thus a collection of objects similar types. For examples, Mango, Apple
and orange members of class fruit. Classes are user-defined that types and behave like
the built-in types of a programming language. The syntax used to create an object is not

16

different then the syntax used to create an integer object in C. If fruit has been defines
as a class, then the statement
Fruit Mango An object mango belonging to the class fruit.
Data Abstraction and Encapsulation
The wrapping up of data and function into a single unit (called class) is known as
encapsulation. Data and encapsulation is the most striking feature of a class. The data
is not accessible to the outside world, and only those functions which are wrapped in
the class can access it. These functions provide the interface between the objects data
and the program. This insulation of the data from direct access by the program is called
data hiding or information hiding.
Abstraction refers to the act of representing essential features without including
the background details or explanation. Classes use the concept of abstraction and are
defined as a list of abstract attributes such as size, wait, and cost, and function operate
on these attributes. They encapsulate all the essential properties of the object that are
to be created.
The attributes are some time called data members because they hold
information. The functions that operate on these data are sometimes called methods or
member function.
Inheritance
Inheritance is the process by which objects of one class acquired the properties
of objects of another classes. It supports the concept of hierarchical classification. For
example, the bird, robin is a part of class flying bird which is again a part of the class
bird.
In OOP, the concept of inheritance provides the idea of reusability. This means
that we can add additional features to an existing class without modifying it. This is
possible by deriving a new class from the existing one. The new class will have the
combined feature of both the classes.

17

Polymorphism
Polymorphism is another important OOP concept. Polymorphism, a Greek term,
means the ability to take more than on form. An operation may exhibit different behavior
is different instances. The behavior depends upon the types of data used in the
operation.
For example, consider the operation of addition. For two numbers, the operation
will generate a sum. If the operands are strings, then the operation would produce a
third string by concatenation. The process of making an operator to exhibit different
behaviors in different instances is known as operator overloading.
Figure illustrates that a single function name can be used to handle different
number and different types of argument. This is something similar to a particular word
having several different meanings depending upon the context. Using a single function
name to perform different type of task is known as function overloading.

18

Polymorphism plays an important role in allowing objects having different internal


structures to share the same external interface.
Dynamic Binding
Binding refers to the linking of a procedure call to the code to be executed in
response to the call. Dynamic binding means that the code associated with a given
procedure call is not known until the time of the call at run time. It is associated with
polymorphism and inheritance. A function call associated with a polymorphic reference
depends on the dynamic type of that reference.
Consider the procedure draw in figure by inheritance; every object will have this
procedure. Its algorithm is, however, unique to each object and so the draw procedure
will be redefined in each class that defines the object. At run-time, the code matching
the object under current reference will be called.
Message Passing
An object-oriented program consists of a set of objects that communicate with
each other. The process of programming in an object-oriented language, involves the
following basic steps:
1. Creating classes that define object and their behavior,
2. Creating objects from class definitions, and
3. Establishing communication among objects.
19

Objects communicate with one another by sending and receiving information


much the same way as people pass messages to one another. A Message for an object
is a request for execution of a procedure, and therefore will invoke a function
(procedure) in the receiving object that generates the desired results. Message passing
involves specifying the name of object, the name of the function (message) and the
information to be sent. Example:

Object has a life cycle. They can be created and destroyed. Communication with an
object is feasible as long as it is alive.
Benefits of OOP
Reusability: In OOPs programs functions and modules that are written by a user can
be reused by other users without any modification.
Inheritance: Through this we can eliminate redundant code and extend the use of
existing classes.
Data Hiding: The programmer can hide the data and functions in a class from other
classes. It helps the programmer to build the secure programs.
Reduced complexity of a problem: The given problem can be viewed as a collection
of different objects. Each object is responsible for a specific task. The problem is solved
by interfacing the objects. This technique reduces the complexity of the program design.
Easy to maintain and Upgrade: OOP makes it easy to maintain and modify existing
code as new objects can be created with small differences to existing ones.
Message Passing: The technique of message communication between objects makes
the interface with external systems easier.

20

2. Explain the various operators that are available in C++ with neat illustration for
each of it. (16m) [A/M2015] (4m) [N/D2014]
An operator is a symbol that tells the compiler to perform specific mathematical
or logical manipulations. C++ is rich in built-in operators and provides the following
types of operators:

Arithmetic Operators

Relational Operators

Logical Operators

Bitwise Operators

Assignment Operators

Other Operators

Arithmetic Operators:

There are following arithmetic operators supported by C++ language:


Assume variable A holds 10 and variable B holds 20, then:
Operator
+
*
/
%

Description
Adds two operands
Subtracts second operand from the first
Multiplies both operands
Divides numerator by de-numerator
Modulus Operator and remainder of after
an integer division
Increment operator, increases integer
value by one
Decrement operator, decreases integer
value by one

++
--

Example
A + B will give 30
A - B will give -10
A * B will give 200
B / A will give 2
B % A will give 0

A++ will give 11


A-- will give 9

Relational Operators:
There are following relational operators supported by C++ language
Assume variable A holds 10 and variable B holds 20, then:
Operator
==

Description
Checks if the values of two operands are
equal or not, if yes then condition becomes
21

Example
(A == B) is not true.

!=

>

<

>=

<=

true.
Checks if the values of two operands are
equal or not, if values are not equal then
condition becomes true.
Checks if the value of left operand is greater
than the value of right operand, if yes then
condition becomes true.
Checks if the value of left operand is less
than the value of right operand, if yes then
condition becomes true.
Checks if the value of left operand is greater
than or equal to the value of right operand, if
yes then condition becomes true.
Checks if the value of left operand is less
than or equal to the value of right operand, if
yes then condition becomes true.

(A != B) is true.

(A > B) is not true.

(A < B) is true.

(A >= B) is not true.

(A <= B) is true

Logical Operators:
There are following logical operators supported by C++ language
Assume variable A holds 1 and variable B holds 0, then:
Operator
&&
||
!

Description
Called Logical AND operator. If both the operands are
non-zero, then condition becomes true.
Called Logical OR Operator. If any of the two operands
is non-zero, then condition becomes true.
Called Logical NOT Operator. Use to reverses the
logical state of its operand. If a condition is true, then
Logical NOT operator will make false.

Example
(A && B) is
false.
(A || B) is true.
!(A && B) is
true.

Bitwise Operators:
Bitwise operator works on bits and performs bit-by-bit operation. The truth tables for &, |,
and ^ are as follows:
p
0
0
1
1

q
0
1
1
0

p&q
0
0
1
0

p|q
0
1
1
1

p^q
0
1
0
1

Assume if A = 60; and B = 13; now in binary format they will be as follows:
22

A = 0011 1100
B = 0000 1101
----------------A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C++ language are listed in the following table.
Assume variable A holds 60 and variable B holds 13, then:
Operator
&
|
^
~

<<

>>

Description
Binary AND Operator copies a bit to the
result if it exists in both operands.
Binary OR Operator copies a bit if it
exists in either operand.
Binary XOR Operator copies the bit if it
is set in one operand but not both.
Binary Ones Complement Operator is
unary and has the effect of 'flipping'
bits.
Binary Left Shift Operator. The left
operands value is moved left by the
number of bits specified by the right
operand.
Binary Right Shift Operator. The left
operands value is moved right by the
number of bits specified by the right
operand.

Example
(A & B) will give 12 which is 0000
1100
(A | B) will give 61 which is 0011
1101
(A ^ B) will give 49 which is 0011
0001
(~A) will give -61 which is 1100 0011
in 2's complement form due to a
signed binary number.
A << 2 will give 240 which is 1111
0000

A >> 2 will give 15 which is 0000


1111

Assignment Operators:
There are following assignment operators supported by C++ language:
Operator
=
+=

-=

Description
Simple assignment operator, Assigns values
from right side operands to left side operand
Add AND assignment operator, It adds right
operand to the left operand and assign the
result to left operand
Subtract AND assignment operator, It subtracts
right operand from the left operand and assign
23

Example
C = A + B will assign value
of A + B into C
C += A is equivalent to C =
C+A
C -= A is equivalent to C =
C-A

*=

/=

%=

the result to left operand


Multiply AND assignment operator, It multiplies
right operand with the left operand and assign
the result to left operand
Divide AND assignment operator, It divides left
operand with the right operand and assign the
result to left operand
Modulus AND assignment operator, It takes
modulus using two operands and assign the
result to left operand

<<=

Left shift AND assignment operator

>>=

Right shift AND assignment operator

&=

Bitwise AND assignment operator

^=

bitwise exclusive OR and assignment operator

!=

bitwise inclusive OR and assignment operator

C *= A is equivalent to C =
C*A
C /= A is equivalent to C =
C/A
C %= A is equivalent to C =
C%A
C <<= 2 is same as C = C
<< 2
C >>= 2 is same as C = C
>> 2
C &= 2 is same as C = C &
2
C ^= 2 is same as C = C ^
2
C |= 2 is same as C = C | 2

Other Operators
There are few other operators supported by C++ Language.
Operator
sizeof
Condition ? X : Y

.(dot) and
->(arrow)
Cast
&
*

Description
sizeof operator returns the size of a variable. For example, sizeof(a),
where a is integer, will return 4.
Conditional operator. If Condition is true ? then it returns value X :
otherwise value Y
Comma operator causes a sequence of operations to be performed.
The value of the entire comma expression is the value of the last
expression of the comma-separated list.
Member operators are used to reference individual members of
classes, structures, and unions.
Casting operators convert one data type to another. For example,
int(2.2000) would return 2.
Pointer operator & returns the address of an variable. For example &a;
will give actual address of the variable.
Pointer operator * is pointer to a variable. For example *var; will pointer
to a variable var.

24

3. List and explain looping (iteration) statements in C++ with examples. (16m)
[M/J2014] (4m)[A/M2011]
Loop Control Statements
Loop:
A loop is defined as a block of statements which are repeatedly executed for
certain number of times. The various terms/steps in loop are,
Loop variable: It is used in the loop.
Initialization: It is the first step in which starting and final value is assigned to the loop
variable. Each time the updated value is checked by the loop itself.
Incrimination/Decrimination: It is the numerical value added to or subtracted from the
variable in each round of the loop. C language supports three types of loop control
statements,
1) While loop
2) Do while loop
3) For loop
1) While loop
The general syntax is:
While (test condition)
{

Body of the loop

The loop statements will be executed till the condition is true, that is the test
condition is true, and then the body of the loop is executed. When the condition
becomes false the control comes out of the loop.

The test condition may be any expression. It is an entry control statement. Once
the condition is satisfied the control will be transferred inside the loop.

The control will be come out of the loop even in the first attempt if the condition is
false.

Nested While is possible.

Eg:

Output
25

void main()

Enter the limit: 5

{
int i,n;

i=0;

cout<<Enter the limit:;

cin>>n;

while(i<=n)

{
cout<<i;
i++;
}
}
2) Do while loop
The general format is:
do
{
Body of the loop
}while (test condition);

Here the condition is checked at the end of the loop. It is an exit control
statement.

The loop will be executed at least once even if the condition is false initially.

The loop will be executed till the condition is true.

The do while loop should be end with semi colon( ; ).

While loop can be placed inside the do while loop.

Eg:

Output

void main()

Enter the limit: 5

int i,n;

i=0;

cout<<Enter the limit;

3
26

cin>>n;

do

{
cout<<i;
i++;
}while(i<=n);
}
3) For loop
The for loop allows to execute a set of instructions until a certain condition is
satisfied.
The General syntax is,
for (initialization counter; test condition; increment or decrement counter value)
{

Body of the loop

Initialization counter sets a loop to an initial value. This statement is executed


only once. Test condition is a relational expression. Test condition determines the
number of iterations and it determines when to exit from the loop.

When the condition becomes false, the control will be transferred to the next
statement of the for loop.

Counter value should be increment or decrement. The loop will be executed


infinitely if the counter value is not increment or decrement.

Eg:

Output

void main()

Enter the limit: 5

int i,n;

cout<<Enter the limit:;

cin>>n;

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

{
27

cout<<i;
}

The break statement:


Syntax: break;
It is used to exit from the switch case statement. Break statement can also be
used inside for, while and also in do while loop.
The continue statement:
Syntax: continue;
It is used to transfer the control to beginning of the loop. The loop does not
terminate once the continue statement is encountered. It can be used with in a while or
a do while or for loop. It applies only to loops and not for switch case statements. In
while and do while loop a continue statement causes the control to go directly to a test
condition.
The goto statement:
Syntax: goto label;
When this statement executed, the control will be transferred to the labeled
location. The label name should be starts with character.
Eg:

Output 1

void main()
{

Enter a number: 5

int n;
cout<<Enter a number:;

given number is less than 10

cin>>n;
if(n<10)
{
goto lab;

Output 2

Enter a number: 11
28

else

given number is greater than 10

{
Cout<<given number is greater than 10;
exit(0);
}
lab:
cout<<given number is less than 10;
}
Decision Making
In the monolithic program the sequences of instructions are executed in the dale
order as they appear in the program. In practical applications, one has to change the
order of execution of statements based on the conditions. It can be achieved by
Decision making statements.
C language supports the following control statements.
1) The if statement
2) The if-else statement
3) The if..else..if ladder statement.
4) The switch() case statement.
The decision statement decides the statement to be executed after the success or
failure of a given condition.
1) The if statement:
The general form of an if statement is,
if(condition)
{
Statements x;
}
Statements- y;
The condition used in the if statement should be specified with in parenthesis. If the
condition is true, then the Statements-x placed between { } will be executed. If the
condition is false, then the control transferred to the outside of the if statement.
29

Eg:

Output 1
void main()
{

Enter two numbers:

int a,b;

15

cout<<Enter two numbers:;

hai

cin>>a>>b;

hello

10

if(a>b)

Output 2

Enter two numbers:

Cout<<hai;

10

hello

15

Cout<<hello;
}
2) The if-else statement:
The general form of an if statement is
if(condition)
{
Statements x;
}
else
{
Statements- y;
}
The condition used in the if statement should be specified with in parenthesis. If
the condition is true, then the Statements-x placed between { } will be executed. If the
condition is false, then the control transferred to the else block and the Statements-y
placed between { } will be executed. No multiple else blocks are allowed for single if
statement.
Eg:

Output 1
void main()
30

Enter two numbers:

int a,b;

15

10

cout<<Enter two numbers:;

a is big

cin>>a>>b;
if(a>b)

Output 2

Enter two numbers:

cout<<a is big;

10

b is big

else
{
cout<<b is big;
}
}
3) The if..else..if ladder statement:
The General form is
if(condition1)
{
Statements x;
}
else if(condition2)
{
Statements- y;
}
else if(condition3)
{
Statements z;
}
.
else
{
31

15

Statements-w;
}
The following rules can be described for applying nested if..else..if

Nested if..else..if statements can be chained with one another.

If the condition is false, then control passes to else block where condition is again
checked with the if statement. This process continues if there is no if statement in
the last else block.

If one of the if

statement satisfies the condition, other else..if will not be

executed.
Eg:

Output 1

void main()
{

Enter three numbers:

int a,b,c;

15

cout<<Enter three numbers:;

10

11

a is big

cin>>a>>b>>c;
if(a>b&&a>c)

Output 2

Enter three numbers:

Cout<<a is big;

10

15

11

b is big

else if(b>c)
{
Cout<<b is big;

Output 3

Enter three numbers:

else

10

11

15

c is big

Cout<<c is big;
}

4) switch() case Statement:


This statement allows us to make a decision from a number of choices.
The general form
32

switch(expression)
{
case constant 1:
statements;
break;
case constant 2:
statements;
break;
..
..
case constant N:
statements;
break;
default:
statements;
}

Rules for writing switch() statement:

The expression in switch statement must be an integer value or a character


constant.

No real numbers are used in expression.

Each case block must end with break statements.

Case keyword must terminate with colon ( : ).

No two case constants are identical.

Eg:
void main()
{
int a,b,choice;
cout<<Enter two numbers:;
cin>>a>>b;
33

Output
cout<<1.Add<<\n;

Enter two numbers:

cout<<2.Sub<<\n;

10

cout<<3.Mul<<\n;

1. Add

cout<<4.Div<<\n;

2. Sub

cout<<Enter choice:<<\n;

3. Mul

cin>>choice;

4. Div

switch(choice)

Enter choice: 1

Add value is: 25

15

case 1:
cout<<Add value is<<a+b;
break;
case 2:
cout<<Sub value is<<a-b;
break;
case 3:
cout<<Mul value is <<a*b;
break;
case 4:
cout<<Div value is <<a/b;
break;
default:
cout<<Enter Correct Choice;
}

4. Explain about pointers with an example.[M/J2016] [7] [OR] What are pointers?
What are the advantages of using pointers in programming? Explain the
addressing mode required to access memory locations using pointers. (16m)
[M/J2014] (4m) [N/D2014] (4m)[M/J2013] (6m)[A/M2011]
Pointers
34

A pointer is a variable that holds a memory address of another object (typically, a


variable) in memory. That is, if one variable contains the address of another variable,
the first variable is said to point to the second. A pointer declaration consists of a base
type, an *, and the variable name. The general form of declaring a pointer variable is:
Syntax: type *pointer_name;
type is the base type of the pointer and may be any valid type.
pointer_name is the name of pointer variable.
The base type of the pointer defines what type of variables the pointer can point to.

Two special pointer operators are: * and &. The & is unary operator that returns the
memory address of its operand. It is the address of operand. The * is complement of
&. It is also a unary operator and returns the value located at the address that follows.
int i *p;
i = 5;
p = &i;

//places the memory address of i into p

The expression *p will return the value of variable pointed to by p.


C++ Null Pointers
A pointer that is assigned NULL is called a null pointer. The NULL pointer is a constant
with a value of zero defined in several standard libraries, including iostream.
int main ()
{
int *ptr = NULL;
cout << "The value of ptr is " << ptr ;
return 0;
}
35

On most of the operating systems, programs are not permitted to access memory at
address 0 because that memory is reserved by the operating system.
C++ pointer arithmetic
Incrementing a Pointer:
The variable pointer can be incremented, unlike the array name which cannot be
incremented because it is a constant pointer. The following program increments the
variable pointer to access each succeeding element of the array:
#include <iostream.h>
const int MAX = 3;
int main ()
{
int var[MAX] = {10, 100, 200};
int *ptr;
// let us have array address in pointer.
ptr = var;
for (int i = 0; i < MAX; i++)
{
cout << "Address of var[" << i << "] = ";
cout << ptr << endl;
cout << "Value of var[" << i << "] = ";
cout << *ptr << endl;
// point to the next location
ptr++;
}
return 0;
}
When the above code is compiled and executed, it produces result something as
follows:
Address of var[0] = 0xbfa088b0
Value of var[0] = 10
Address of var[1] = 0xbfa088b4
36

Value of var[1] = 100


Address of var[2] = 0xbfa088b8
Value of var[2] = 200
C++ pointer to pointer
A pointer to a pointer is a form of multiple indirection or a chain of pointers. Normally, a
pointer contains the address of a variable. While defining a pointer to a pointer, the first
pointer contains the address of the second pointer, which points to the location that
contains the actual value as shown below.

int main ()
{
int var;
int *ptr;
int **pptr;
var = 3000;
// take the address of var
ptr = &var;
// take the address of ptr using address of operator &
pptr = &ptr;
// take the value using pptr
cout << "Value of var :" << var << endl;
cout << "Value available at *ptr :" << *ptr << endl;
cout << "Value available at **pptr :" << **pptr << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Value of var :3000
Value available at *ptr :3000

37

Value available at **pptr :3000


The This Pointer

Every object has a special pointer "this" which points to the object itself.

This pointer is accessible to all members of the class but not to any static
members of the class.

Can be used to find the address of the object in which the function is a member.

Presence of this pointer is not included in the sizeof calculations.

Program:
#include <iostream>
class MyClass
{

int data;
public:
MyClass()

{
data=100;
}
void Print1();
void Print2();
};
// Not using this pointer
void MyClass::Print1()
{
cout << data << endl;
}
// Using this pointer
void MyClass::Print2()
{
cout << "My address = " << this << endl;
cout << this->data << endl;
38

}
int main()
{
MyClass a;
a.Print1();
a.Print2();
// Size of doesn't include this pointer
cout << sizeof(a) << endl;
}
Output:
100
My address = 0012FF88
100
4

5. Explain about Functions and Data types in C++. (8m) [N/D2014]


Functions
A function is a self contained program, which is used to do some particular task.
Every programs start with user defined function main(). The main() function must be
defined and it calls another function to share the work.
C language supports two types of functions
1) Library Functions
2) User defined Functions
The Library functions are pre-defined set of functions. Their task is limited and
the users cannot understand the internal logic of the functions. The user can allow using
these functions but not to modify or change them. Eg: strcat() strcmp() sqrt() ceil()

39

The user defined functions are defined by the user according to his/her
requirements. The user can modify the function. The source code of every function is
visible. User exactly knows what the functions working internally.
Definition
A function is a self contained block or sub program of one or more statements
that performs a special task when called.
Use of function
If we want to perform a task repetitively then it is not necessary to re-write the particular
block again and again. The function defined can be used for any number of times to
perform the task. Using functions, large function can be reduced to smaller ones. It is
easy to debug and find out the errors. It also increases the readability.
How function works
Once the function is defined and called, it takes some data to the calling function
form the called function. Once the function is called, control passes to the called
function and working of the calling function is stopped, when the execution of the called
function is completed, then the control returns back to the calling function and executes
the next statement.
The values of actual arguments passed by the calling function are received by
the formal arguments in called function. The actual and formal arguments are same in
number. Any mismatch in data type will produce an unexpected result. The called
function operates on formal arguments and sends back to the calling function with the
help of return() statement.
A function definition consists of two parts

Argument declaration

Body of the Function

The general form for syntax is


Return type function_name (Argument list)
{
local variable declarations;
statement1;
statement n;
40

return (Expression);
}
returntype: it specifies the type of value that function returns.
function_name: its an user-defined name followed by argument list, each argument is
preceded by its type declaration. An empty pair of parenthesis must follow the function
name, if the function definition does not include any arguments.
Return: a function may return values with the help of return statement. The return value
should match with the return type.
The return Statement
The return statement is a flow of control statement. When a return statement is
executed, the current function terminates, and program control is immediately passed
back to the place where the function was invoked. In addition, if an expression follows
the keyword return, the value of the expression is returned to the calling point as well.
This value must be assignment-convertible to the return type of the function definition
header.
A return statement has one of the following two forms:
return;
return expression;
Some examples are
return;
return (a + b);
Using parentheses in the return expression is optional, a stylistic device that some
programmers use to enhance readability.
Function prototyping:
It is one of the major improvements added to C++ functions. The prototype
describes the function interface to the compiler by giving details such as the number
and type of arguments and the type of return values. Any violation in matching the
arguments or the return types will be caught by the compiler at the time of the

41

compilation itself. Function prototype is a declaration statement in the calling program


and is of the following form:
type function-name(argument list);
In function declaration, the names of the arguments are dummy variables and
therefore they are optional. That is the form,
Eg: int add(int,int,int);
a) Actual arguments: the arguments of calling functions are actual arguments.
b) Formal arguments: the arguments of called functions(function definition) are formal
arguments.
c) Argument list: it means variables enclosed within the parenthesis, they must be
separated with comma (,) operator.
d) Function call: A compiler executes the function when a semicolon (;) is followed by
function name.
Function Invocation (Calling Function)
A C++ program is made up of one or more functions, one of which is main().
Program execution always begins with main(). When program control encounters a
function name, the function is called, or invoked. This means that program control
passes to the function. The place at which a function is called is known as its calling
environment. After the function does its work, program control is passed back to the
calling environment, which continues execution from that point.
The following function illustrates the concept of function definition :
//function definition add()
void add()
{
int a,b,sum;
cout<<Enter two integers<<endl;
cin>>a>>b;
sum=a+b;
42

cout<<\nThe sum of two numbers is <<sum<<endl;


}
The above function add ( ) can also be coded with the help of arguments of parameters
as shown below:
//function definition add()
void add(int a, int b) //variable names are must in definition
{
int sum;
sum=a+b;
cout<<\nThe sum of two numbers is <<sum<<endl;
}
Passing arguments to a function
It is not always necessary for a function to have arguments or parameters. The following
example illustrates the concept of passing arguments to function SUMFUN ( ):
// demonstration of passing arguments to a function
#include<iostream.h>
void main ()
{
float x,result; //local variables
int N;

43

NATIVE TYPES IN C++


A native type is one provided by the language directly. In C++, this includes the
simple types such as character, integer, and floating-point types; the boolean type; and
derived types such as array, pointer, and structure types, which are aggregates of the
simple types.
The simple native types in C++ are bool, int, double, char, and wchar_t. These
types have a set of values and representation that is tied to the underlying machine
architecture on which the compiler is running. Both the bool and the wchar_t types are
new to C++ and are not in C and early C++ systems. The bool type provides a native
Boolean type, and wchar_t provides a wide character type, used for representing
character sets requiring more than the standard 255 characters. C++ integral simple
types can often be modified by the keywords short, long, signed, and unsigned, to yield
further simple types. The floating-point types are float, double, and long double. Table
2.11 lists these types, shortest to longest. Length here refers to the number of bytes
used to store the type.

44

Datatypes
Built-in data types
The following table lists all combinations of the basic data types and modifiers
along with their size and range for a 16-bit word machine.
Type
Char
Unsigned char
Signed char
Int
Unsigned int
Signed int
Short int
Unsigned short int
Signed short int
Long int
Signed long int
Unsigned long int
Float
Double
Long double

Bytes
1
1
1
2
2
2
2
2
2
4
4
4
4
8
10

45

Range
-128 to 127
0 to 255
-128 to 127
-32768 to 32767
0 to 65535
-32768 to 32767
-32768 to 32767
0 to 65535
-32768 to 32767
-2147483648 to 2147483647
-2147483648 to 2147483647
0 to 4294967295
3.4E-38 to 3.4E+38
1.7E-308 to 1.7E+308
3.4E-4932 to 1.1E+4932

User-Defined Data Types


i) Structure:
A structure is a collection of one or more variables of different data types grouped
together under a single name. A structure may contain integer elements, float elements
and character elements etc. the individual elements are called members.
Features of Structure:
In array, all the elements cannot copy to another array at a same time. One by
one we can copy the value. But in case of Structure, it is possible to copy the contents
of all structure elements of different data types to another structure at a same time using
(=) operator. This is possible because the structure elements are stored in successive
memory locations. Can create structure within a structure. It is possible to pass
structure elements to a function. Can pass individual structure elements or entire
structure. It is also possible to create structure pointers.
Declaration of Structure
The general format to declare a Structure is
struct struct_type
{
46

type variable1;
type variable2;
};
ii) Union
Union is a variable which is similar to structure. It contains a number of members
like structure but it holds only one object at a time.

In structure each member has its

own memory location, whereas members of unions have same memory locations. For
Eg, if the union contains char, long, and integer then the number of bytes reserved in
the memory for the union is 4 bytes.
Syntax:
union union_name
{
member1;
member2;
};
union union_varaiable;
iii) Enumerated Data type
The enum is a keyword used for declaring enumeration types. The programmer
can create his/her own data type and define what values the variables of these data
types can hold.
Eg,
enum month { jan, feb ,mar};
jan hold 0, feb hold 1 and mar hold 2.
Can initizlize values to the variable by
enum month { jan=10, feb ,mar};
now, jan hold 10, feb hold 11 and mar hold 12.

47

Derived Data Types


Arrays
An array is defined as a collection of same data type values under the same
name. Arrays are structured type of variable.
Purpose of Array
Ordinary variable are capable of storing one value at a time. This fact is same for
all the data types. But in many case, the variables must be assigned to more than value.
This can be obtained with the help of array.
Declaration of Array
Data_type variable_name[size];
Eg:
int a[5];

it is an integer array variable which can hold 5 values.

Array initialization
int a[5]={1,2,3,4,5};
Calling array elements
a[0] refers to 1st element 1
a[1] refers to 2nd element 2
a[2] refers to 3rd element 3
a[3] refers to 4th element 4
a[4] refers to 5th element 5
Characteristics of Array
All the elements of an array share the same name, and they are distinguished from one
another with the help of an element number. The element number plays a major role in
array. Any particular element of an array can be modified separately without disturbing
other elements. Any element of an array can be assigned to another variable or an array
variable of its type.
One dimensional Array
This type of array has only one dimension. For eg, the elements of an integer
array a[5] are stored in continuous memory location. The memory is allocated depend
on the data types.
48

Eg: int a[3]


a[0] address is 65522
a[1] address is 65524
a[2] address is 65526
Program:
void main()
{
int a[5],i;
for(i=0;i<5;i++)
cin>>a[i];
for(i=0;i<5;i++)
cout<<a[i];
}
Pointers
A pointer is a variable that is used to store the address of a data item, such as a
variable or an array element.
Syntax: datatype *variablename;
The Symbol * is called indirection operator, which indicates the variable is a pointer
variable.
Accessing the address of a variable
The address of the variable is accessed with the help of & operator. The &
operator is called address operator. The & operator preceding a variable returns the
address of that variable.
Eg,
void main()
{
int a;
int *b;

output

a=10;

address of a is 56565

b=&a;

/* address of a is stored in b */

cout<<address of a is<<b;
49

the value that b holds 10

cout<<the value that b holds<<*p;


}
Initialization of pointers
A pointer can also be initialized.
Eg:
int a,*b;
b=&a;

,after execution of this statement the address of a is stored in b.

If we print b, then it displays the address that it hold (address of a), if we want the
value that the address holds means by print *b then it displays the value which is stored
in that address.
6. Discuss about i) const function ii) friend function iii) inline function iv) Volatile
function with suitable illustrations. (12m) [M/J2013] (16m)[M/J2012]
Friend function
A friend function is used for accessing the non-public members of a class. A class
can allow non-member functions and other classes to access its own private data, by
making them friends. Thus, a friend function is an ordinary function or a member of
another class.
How to define and use Friend Function in C++:
The friend function is written as any other normal function, except the function
declaration of these functions is preceded with the keyword friend. The friend function
must have the class to which it is declared as friend passed to it in argument.
Some important points to note while using friend functions in C++:

The keyword friend is placed only in the function declaration of the friend function
and not in the function definition. It is possible to declare a function as friend in
any number of classes. When a class is declared as a friend, the friend class has
access to the private data of the class that made this a friend. A friend function,
even though it is not a member function, would have the rights to access the
private members of the class.

50

It is possible to declare the friend function as either private or public. The function
can be invoked without the use of an object. The friend function has its argument
as objects, seen in example below.

Example:
class exforsys
{
private:
int a,b;
public:
void test()
{
a=100;
b=200;
}
friend int compute(exforsys e1)
//Friend Function Declaration with keyword friend and with the object of class exforsys
to which it is friend passed to it
};
int compute(exforsys e1)
{
//Friend Function Definition which has access to private data
return int (e1.a+e2.b)-5;
}
main()
{
exforsys e;
e.test();
cout<<"The result is:"<<COMPUTE(E);
//Calling of Friend Function with object as argument.
}
51

The output of the above program is


The result is:295
The function compute() is a non-member function of the class exforsys. In order to
make this function have access to the private data a and b of class exforsys , it is
created as a friend function for the class exforsys. As a first step, the function compute()
is declared as friend in the class exforsys as:
friend int compute (exforsys e1)
The keyword friend is placed before the function. The function definition is written
as a normal function and thus, the function has access to the private data a and b of the
class exforsys. It is declared as friend inside the class, the private data values a and b
are added, 5 is subtracted from the result, giving 295 as the result.
Inline function
If a function is inline, the compiler places a copy of the code of that function at
each point where the function is called at compile time. Any change to an inline function
could require all clients of the function to be recompiled because compiler would need
to replace all the code once again otherwise it will continue with old functionality.
To inline a function, place the keyword inline before the function name and define
the function before any calls are made to the function. The compiler can ignore the
inline qualifier in case defined function is more than a line. A function definition in a class
definition is an inline function definition, even without the use of the inline specifier.
Following is an example, which makes use of inline function to return max of two
numbers:
inline int Max(int x, int y)
{
return (x > y)? x : y;
}
// Main function for the program
int m ain( )
{
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
52

cout << "Max (100,1010): " << Max(100,1010) << endl;


return 0;
}
When the above code is compiled and executed, it produces the following result:
Max (20,10): 20
Max (0,200): 200
Max (100,1010): 1010
Const Functions
If you declare a class method const, you are promising that the method won't
change the value of any of the members of the class. To declare a class method
constant, put the keyword const after the parentheses but before the semicolon. The
declaration of the constant member function SomeFunction() takes no arguments and
returns void. It looks like this:
void SomeFunction() const;
Access or functions are often declared as constant functions by using the const
modifier Declare member functions to be const whenever they should not change the
object
Volatile Functions
The volatile keyword is a type qualifier used to declare that an object can be
modified in the program by something such as the operating system, the hardware, or a
concurrently executing thread. If your objects are used in a multithreaded environment
or they can be accessed asynchronously (say by a signal handler), they should be
declared volatile.
A volatile object can call only volatile member functions safely. If the program
calls a member function that isn't volatile, its behavior is undefined. Most compilers
issue a warning if a non-volatile member function is called by a volatile object:
struct S
{
int f1();
int f2() volatile;
}
53

7.Difference Between Procedure Oriented Programming (POP) & Object Oriented


Programming (OOP) [M/J2016][9]
Procedure Oriented
Programming
In POP, program is divided into
Divided Into
small parts called functions.
Importance
Approach
Access
Specifiers
Data Moving
Expansion

Data Access

Data Hiding
Overloading
Examples

Object Oriented Programming

In OOP, program is divided into


parts called objects.
In OOP, Importance is given to the
In POP,Importance is not given to
data rather than procedures or
data but to functions as well as
functions because it works as a real
sequence of actions to be done.
world.
POP follows Top Down approach. OOP follows Bottom Up approach.
POP does not have any access
OOP has access specifiers named
specifier.
Public, Private, Protected, etc.
In OOP, objects can move and
In POP, Data can move freely from
communicate with each other
function to function in the system.
through member functions.
To add new data and function in
OOP provides an easy way to add
POP is not so easy.
new data and function.
In POP, Most function uses Global In OOP, data can not move easily
data for sharing that can be
from function to function,it can be
accessed freely from function to
kept public or private so we can
function in the system.
control the access of data.
POP does not have any proper way OOP provides Data Hiding so
for hiding data so it is less secure. provides more security.
In OOP, overloading is possible in
In POP, Overloading is not possible. the form of Function Overloading
and Operator Overloading.
Example of POP are : C, VB,
Example of OOP are : C++, JAVA,
FORTRAN, Pascal.
VB.NET, C#.NET.

8. Write a C++ program to list out prime numbers between the given two limits.
[M/J2016][8]
Example #1: Display Prime Numbers Between two Intervals
#include <iostream>
using namespace std;
int main()
{
int low, high, i, flag;

54

cout << "Enter two numbers(intervals): ";


cin >> low >> high;
cout << "Prime numbers between " << low << " and " << high << " are: ";
while (low < high)
{
flag = 0;
for(i = 2; i <= low/2; ++i)
{
if(low % i == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
cout << low << " ";
++low;
}
return 0;
}

OUTPUT:
Enter two numbers(intervals): 20 50 Prime numbers between 20 and 50 are: 23 29 31
37 41 43 47
In this program, the while loop is iterated (high - low - 1) times.
In each iteration, whether low is a prime number or not is checked and the value of low
is incremented by 1 until low is equal to high.
If the user enters larger number first, this program doesn't work as intended. You can
solve this issue by swapping the numbers if the user enters larger number first.

Example #2: Display Prime Numbers When Larger Number is Entered first
#include <iostream>
55

using namespace std;


int main()
{
int low, high, flag, temp;
cout << "Enter two numbers(intevals): ";
cin >> low >> high;
//swapping numbers if low is greater than high
if (low > high) {
temp = low;
low = high;
high = temp;
}
cout << "Prime numbers between " << low << " and " << high << " are: ";
while (low < high)
{
flag = 0;
for(int i = 2; i <= low/2; ++i)
{
if(low % i == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
cout << low << " ";
++low;
}
return 0;
}

9. Explain the various C++ programming elements.


Comments

56

C++ introduces a new comment symbol //(double slash). Comments starts with a
double slash symbol and terminate at the end of the line. A comment may start
anywhere in the program.
Single line comment: // double slash is basically a single line comment
Eg: // this a sample c++ program
Multiline comment: it starts with /* and ends with */
Eg: /* This is a sample
C++ program to illustrate
Some of the basic features */
Header files
In C and C++, applications are divided into smaller parts through the use of
header files. Any function prototypes, and type definitions that can be exported from a
source code file are put in a header file. The header file iostream should be included at
the beginning of all programs that use input/output statements.
Some of the header files are
Assert.h, ctype.h, float.h, limits.h, math.h, stdio.h, stdlib.h, string.h
I/O operators
Input operator
The statement,
cin>>variable; is an input statement and causes the program to wait for the user to
give input. The operator >> is an extraction or get from operator. It extracts the value
from the keyboard and assigns it to the variable on its right.
Output operator
The statement,
cout<<C++ program; causes the string in quotation marks to be displayed on the
screen. The operator << is called the insertion or put to operator. It inserts the contents
of the variable on its right to the object on its left.
Cascading of I/O operators
57

The statement,
cout<<Sum=<<sum<<\n; first sends the string sum= to cout and then sends the
value of sum. Finally, it sends the newline character. The multiple use of << in one
statement is called cascading.
We can also cascade Input operator >>
cin>>a>>b; the values are assigned from left to right. That is if we key in two values,
say 10 and 20. The value 10 is assigned to a and 20 is assigned to b.
Variables
In C++, a variable is a data name used for storing a data value. Its value may be
changed during the program execution. Variables can be of different data types. These
data types are integers, real or character constants. The data values are stored on the
memory and at the time of execution the different operations are performed on them.
Rules for defining variables:

Must be begin with character without spaces but underscore is permitted and
should not start with digit.

It should not be keyword.

It may be a combination of upper and lower characters. Add and ADD is not the
same variables.

Length of variables differs from a compiler to another. The ANSI standard


recognizes the maximum length of a variable up to 31 characters.

Declaring the variables:


It should be done at the declaration part of the program. The variables must be declared
before use. Declaration provides two things:

Compiler obtains the variable name.

Tells the compiler the data type of the variable being declared and helps in
allocating the memory.

Syntax:
Data_type variable_name;
Eg:
int age;
58

char na;
Initializing the values:
Value can be initialized to the variable using = operator. Declaration and
initialization can also be done at the same time.
Syntax
Variable_name=constant;
Or
Datatype variablename= constant;
Eg:
a=10; or int b=10;
Tokens
The smallest individual units in a program are known as tokens. C++ has the
following tokens:

Keywords

Identifiers

Constants

Strings

Operators

Keywords
They are explicitly reserved identifiers and cannot be used as names for the
program variables or other user defined program elements.
Identifiers and Constants:
Identifiers refer to the names of variables, functions, arrays, classes, etc. they are
the fundamental requirement of any language. Each language has its own rules for
naming these identifiers. The following are some of the rules:

Only alphabetic characters, digits and underscores are permitted.

The name cannot start with a digit.

Uppercase and lowercase letters are distinct.


59

A declared keyword cannot be used as a variable name.

Operators
Type of Operator
Arithmetic Operators
Relational Operators
Logical Operators
Increment and Decrement Operators
Assignment Operator
Bitwise Operators
Comma Operator
Conditional Operator

Symbolic Representation
+, -, *, / and %
>, <, <=, >=, == and !=
&&, || and !
++, -=
&, |, ^, >>, << and ~
,
?:

Additional operators in C++


Type of Operator
Scope resolution operator
Pointer-to-member declaratory
Pointer-to-member operator
Pointer-to-member operator
Memory release operator
Line feed operator
Memory allocation operator
Field width operator

Symbolic Representation
::
::*
->*
.*
delete
endl
new
setw

10. Why is type conversion? How does it help programmers [N/D2007] [or] Explain in
detail about Type Conversion.
There are two types of conversion take place,

Automatic Arithmetic Expression Conversions(implicit conversions)

Type casting(explicit conversions)

Automatic Arithmetic Expression Conversions


Any bool, char, short, or enum is promoted to int. Integral values that cannot be
represented as int are promoted to unsigned. If, after the first step, the expression is of
mixed type, the following applies, according to the hierarchy of types:
60

int < unsigned < long < unsigned long< float < double < long double
The operand of the lower type is promoted to that of the higher type, and the
value of the expression has that type. To illustrate implicit conversion, we make some
declarations and list a variety of mixed expressions along with their corresponding types
in table,

Automatic Type Conversion (implicit conversion)


As an example, consider the MIXED program:
// mixed.cpp
// shows mixed expressions
#include <iostream.h>
int main()
{
int count = 7;
float avgWeight = 155.5F;
double totalWeight ;
double totalWeight= count * avgWeight;
cout << totalWeight= << totalWeight << endl;
return 0;
}
Here a variable of type int is multiplied by a variable of type float to yield a result of type
double.
Type Casting (Explicit conversions)
61

In C++ the term applies to data conversions specified by the programmer, as


opposed to the automatic data conversions we just described. Casts are also called
type casts a programmer needs to convert a value from one type to another in a
situation where the compiler will not do it automatically or without complaining. There
are several kinds of casts in Standard C++: static casts, dynamic casts, reinterpret
casts, and const casts. You can force an expression to be of a specific type by using a
cast.
The general form of a cast is
(type) expression
#include <iostream.h>
#include<conio.h>
int main(void) /* print i and i/2 with fractions */
{
int i;
clrscr();
for(i=1; i<=10; ++i)
{
cout<<(float)i<<endl<< ((float) i /2)<<endl;
}
getch();
return 0;
}
Without the cast (float), only an integer division would have been performed. The
cast ensures that the fractional part of the answer is displayed.Heres a statement that
uses a C++ static cast to change a variable of type int into a variable of type char:
aCharVar = static_cast<char>(anIntVar); Here the variable to be cast (anIntVar) is
placed in parentheses and the type its to be changed to (char) isplaced in angle
brackets. The result is that anIntVar is changed to type char before its assigned to
aCharVar. In this case the assignment statement would have carried out he cast itself,
but there are situations where the cast is essential.
62

9.Explain about narrowing and widenining in c++ [N/D2011]


An automatic conversion can occur with an assignment. For example, d = i
causes the value of i, which is an int, to be converted to a double and then assigned to
d; double is the type of the expression as a whole. A promotion, or widening, such as d
= i, is usually reliable,
// . A promotion, or widening
#include<iostream.h>
#include<conio.h>
void main()
{
int i=2;
double d;
clrscr();
d=i;
cout<<d;//prints with fractional part
getch();
}
but a demotion, or narrowing, such as i = d, can lose information.
Here, the fractional part of d is discarded.
#include <iostream.h>
#include<conio.h>
void main()
{
int i;
double d=3.1454;
clrscr();
i=d;
cout<<i; //prints without fractional part
getch();
63

}
In addition to implicit conversions, which can occur across assignments and in mixed
expressions, there are explicit conversions, called casts.
10. Write a C++ program that inputs two numbers and outputs the largest number using
class (8m) [N/D2009]
Program
Class large
{
Int a,b;
Public:
Void get_data(void);
Void compare(void);
};
Void get_data(void)
{
Cout<<Input number1:
Cin>>a;
Cout<<Input number2:
Cin>>b;
}
Void compare(void)
{
If (a>b)
{
Cout<<a<<is greater;
}
else
{
Cout<<b<<is greater;
}
}
Int main()
{
Large c;
c. get_data();
c.compare();
return 0;
}

11. C++ Program to Check Whether a Number is Prime or Not

64

Example: Check Prime Number


#include <iostream>
using namespace std;
int main()
{
int n, i;
bool isPrime = true;
cout << "Enter a positive integer: ";
cin >> n;
for(i = 2; i <= n / 2; ++i)
{
if(n % i == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
cout << "This is a prime number";
else
cout << "This is not a prime number";
return 0;
}
Output
Enter a positive integer: 29
This is a prime number.
Enter a positive integer: 12
This is not a prime number.
This program takes a positive integer from user and stores it in variable n.
Then, for loop is executed which checks whether the number entered by user is
perfectly divisible by i or not.
The foor loop initiates with an initial value of i equals to 2 and increasing the value of i in
each iteration.
If the number entered by user is perfectly divisible by i then, isPrime is set to false and
the number will not be a prime number.
65

But, if the number is not perfectly divisible by i until test condition i <= n/2 is true means,
it is only divisible by 1 and that number itself.
So, the given number is a prime number.

66

You might also like