Professional Documents
Culture Documents
COMPILED BY
M.KARTHIKEYAN, M.E., (AP/IT)
VERIFIED BY
HOD
PRINCIPAL
CORRESPONDENT
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
4.
EE6402
5.
EE6403
6.
EE6404
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
and
Member
Functions-
Object
9
Creation
and
Destruction-
ADVANCED PROGRAMMING
OVERVIEW OF JAVA
Data types, variables and arrays, operators, control statements, classes, objects,
methods - Inheritance
UNIT V
EXCEPTION HANDLING
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
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
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:
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)
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.
10
13. State the need for using the object oriented programming techniques.
public:
virtual void f() = 0;
};
17. Write the features of object oriented programming?
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.
Through, we can eliminate redundant code and extend the use of existing
classes.
The principle of data hiding helps the programmer to build secure programs
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
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
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:
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
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 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
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
*=
/=
%=
<<=
>>=
&=
^=
!=
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)
{
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.
Eg:
Output
25
void main()
{
int i,n;
i=0;
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.
Eg:
Output
void main()
int i,n;
i=0;
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)
{
When the condition becomes false, the control will be transferred to the next
statement of the for loop.
Eg:
Output
void main()
int i,n;
cin>>n;
for(i=1;i<=n;i++)
{
27
cout<<i;
}
Output 1
void main()
{
Enter a number: 5
int n;
cout<<Enter a number:;
cin>>n;
if(n<10)
{
goto lab;
Output 2
Enter a number: 11
28
else
{
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()
{
int a,b;
15
hai
cin>>a>>b;
hello
10
if(a>b)
Output 2
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
int a,b;
15
10
a is big
cin>>a>>b;
if(a>b)
Output 2
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
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
executed.
Eg:
Output 1
void main()
{
int a,b,c;
15
10
11
a is big
cin>>a>>b>>c;
if(a>b&&a>c)
Output 2
Cout<<a is big;
10
15
11
b is big
else if(b>c)
{
Cout<<b is big;
Output 3
else
10
11
15
c is big
Cout<<c is big;
}
switch(expression)
{
case constant 1:
statements;
break;
case constant 2:
statements;
break;
..
..
case constant N:
statements;
break;
default:
statements;
}
Eg:
void main()
{
int a,b,choice;
cout<<Enter two numbers:;
cin>>a>>b;
33
Output
cout<<1.Add<<\n;
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
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
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;
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
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
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.
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
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
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
43
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
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.
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
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
output
a=10;
address of a is 56565
b=&a;
/* address of a is stored in b */
cout<<address of a is<<b;
49
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
Data Access
Data Hiding
Overloading
Examples
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
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
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 may be a combination of upper and lower characters. Add and ADD is not the
same variables.
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:
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 ~
,
?:
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,
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,
}
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;
}
64
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