Unit 1 Notes
Unit 1 Notes
UNIT I
Introduction to OOPS
======================================================================
Page No: 1
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
• Analyze the objects with which we are working - both the attributes of those objects and
the tasks that need to be performed on those objects.
• Messages can be passed to objects, requesting the objects to take action.
• The same message works differently when applied to the various objects.
• A method can work appropriately with different types of data it receives, without the need
for separate method names.
• Objects can inherit features of previously created objects, thereby reducing the time it
takes to create new objects.
• Information hiding is more complete than in procedural programs.
============================================================================
OBJECT ORIENTED PROGRAMMING CONCEPTS
The basic principles behind using object-oriented programming techniques are as follows:
• Objects
• Classes
• Data Encapsulation
• Data Abstraction
• Inheritance
• Polymorphism
• 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 two objects in a program, then the customer
object may send a message to the account object requesting for the bank balance. Each object
contains data, and code to manipulate the data. Objects can interact without having to know details
of each other's data or code. It is sufficient to know the type of message accepted, and the type of
response returned by the objects.
Classes:
A class is thus a collection of objects of similar type. For example, mango, apple and orange
are members of the class fruit. Classes are user-defined data types and behave like the built-in
types of a programming language. If fruit has been defined as a class, then the statement: Fruit
mango; will create an object mango belonging to the class Fruit.
Data Encapsulation:
Page No: 2
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
The wrapping up of data and functions into a single unit (called class) is known as
encapsulation. 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 object's data and the program. This insulation of the
data from direct access by the program is called data hiding or information hiding.
Data Abstraction
Abstraction refers to the act of representing essential features without including the
background details or explanations. Classes use the concept of abstraction and are defined as a list
of abstract attributes such as size, weight and cost, and functions to operate on these attributes.
They encapsulate all the essential properties of the objects that are to be created. The attributes
are sometimes called data members because they hold information. The functions that operate on
these data are sometimes called methods or member functions. Since the classes use the concept of
data abstraction, they are known as Abstract Data Types (ADT). The technique of creating new
data types that are well suited to an application to be programmed is known as data abstraction.
The class is a construct in C++ for creating user-defined data types called ADT’s.
Inheritance:
Inheritance is the process of deriving one class into another class by inheriting all the
properties of the base class. In OOP, the concept of inheritance provides the idea of reusability and
supports the concept of hierarchical classification. This means that we can add additional features
to an existing class without modifying it.
Example, the class ‘Square’ is a part of the class '2DimensionalShapes' which is again a part
of the class 'Shape'. The principle behind this sort of division is that each derived class shares
common characteristics with the class from which it is derived as illustrated below,
Polymorphism:
• In that “Poly” means many and “Morphism” means taking more than one form. Basically it
is an Greek word.
Page No: 3
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
• An operation may exhibit different behaviors in 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.
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, therefore, involves the following basic
steps:
Objects communicate with one another by sending and receiving information much the
same way as people pass messages to one another. The concept of message passing makes it easier
to talk about building systems that directly model or simulate their real-world counterparts. 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 result. Message passing involves
specifying the name of the object, the name of the function (message) and the information to be
sent. Example:
Objects have a life cycle. They can be created and destroyed. Communication with an object
is feasible as long as it is alive.
============================================================================
INTRODUCTION TO C++
The most important facilities that C++ adds on to C are classes, inheritance, and function
overloading, and operator overloading. The object-oriented features in C++ allow programmers to
build large programs with clarity, extensibility and ease of maintenance, incorporating the spirit
and efficiency of C.
Applications of C++:
Page No: 4
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
C++ is a versatile language for handling very large programs. It is suitable for virtually any
programming task including development of editors, compilers, databases, communication
systems and any complex real-life application systems.
• Since C++ allows us to create hierarchy-related objects, we can build special object oriented
libraries which can be used later by many programmers.
• While C++ is able to map the real-world problem properly, the C part of C++ gives the
language the ability to get close to the machine-level details.
• C++ programs are easily maintainable and expandable. When a new feature needs to be
implemented, it is very easy to add to the existing structure of an object.
• It is expected that C++ will replace C as a general-purpose language in the near future.
Comments
C++ introduces a new comment symbol // (double slash). Comments start with a double
slash symbol and terminate at the end of the line. A comment may start anywhere in the line, and
whatever follows till the end of the line is ignored. Note that there is no closing symbol. The double
slash comment is basically a single line comment.
The C comment symbols /*, */are still valid and are more suitable for multiline comments.
The operator << is known as “insertion” or “put to” operator. It inserts (or puts) the
value to the output screen. This corresponds to the familiar printf( ) operation in C.
is an input statement and causes the program to wait for the user to type in a number. The number
keyed in is placed in the variable number l. The identifier cin (pronounced 'C in') is a predefined
object in C++ that corresponds to the standard input stream. Here, this stream represents the
keyboard.
The operator >> is known as extraction or get from operator. It extracts (or takes) the
value from the keyboard and assigns it to the variable on its right. This corresponds to the familiar
scanf( ) operation in C.
============================================================================
Page No: 5
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
Data types are used to indicate a specific value. When programming, we store the variables
in our computer's memory, but the computer has to know what kind of data we want to store in
them, since it is not going to occupy the same amount of memory to store a simple number than to
store a single letter or a large number, and they are not going to be interpreted the same way.
The memory in our computers is organized in bytes. A byte is the minimum amount of
memory that we can manage in C++. A byte can store a relatively small amount of data: one single
character or a small integer (generally an integer between 0 and 255). In addition, the computer
can manipulate more complex data types that come from grouping several bytes, such as long
numbers or non-integer numbers. Data types in c++ can be of seven basic C++ data types.
Type Keyword
Boolean bool
Character char
Integer int
Floating point float
Double floating point double
Valueless void
Wide character wchar_t
Several of the basic types can be modified using one or more of these type modifiers:
• signed
• unsigned
• short
• long
The following table shows the variable type, how much memory it takes to store the value
in memory, and what is maximum and minimum value which can be stored in such type of
variables.
Type Typical Bit Width Typical Range
char 1byte -127 to 127 or 0 to 255
unsigned char 1byte 0 to 255
signed char 1byte -127 to 127
int 4bytes -2147483648 to 2147483647
unsigned int 4bytes 0 to 4294967295
signed int 4bytes -2147483648 to 2147483647
short int 2bytes -32768 to 32767
unsigned short int Range 0 to 65,535
signed short int Range -32768 to 32767
Page No: 6
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
This example uses endl, which inserts a new-line character after every line and
sizeof() function to get size of various data types.
typedef Declarations:
New name for an existing type can be created using typedef. Following is the simple syntax
to define a new type using typedef:
typedef Datatype variableName;
For example, the following tells the compiler that feet is another name for int:
typedef int feet;
Now, the following declaration is perfectly legal and creates an integer variable called distance:
feet f1,f2;
Enumerated Types:
An enumerated type declares an optional type name and a set of zero or more identifiers
that can be used as values of the type. Each enumerator is a constant whose type is the
enumeration. To create an enumeration requires the use of the keyword enum. The general form
of an enumeration type is:
Page No: 7
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
Where,
• The enum is an Keyword.
• enum-name is the enumeration's type name.
• The list of names is comma separated.
For example, the following code defines an enumeration of colors called colors and the
variable c of type color. Finally, c is assigned the value "blue".
enum color { red, green, blue} c;
c=blue;
By default, the value of the first name is 0, the second name has the value 1, the third has
the value 2, and so on. But we can give a name a specific value by adding an initializer. For example,
in the following enumeration, green will have the value 5.
enum color { red, green=5, blue} c;
c=blue;
Here, blue will have a value of 6 because each name will be one greater than the one that precedes
it.
============================================================================
Tokens:
The smallest individual units in a program are known as tokens. C++ has the following
tokens:
• Keywords
• Identifiers
• Constants
• Operators
• Strings
(a) Keywords:
They are explicitly reserved identifiers and cannot be used as names for the program
variables or other user-defined program elements.
(b) Identifiers
Identifiers refer to the names of variables, functions, arrays, classes, etc. created by the
programmer. They are the fundamental requirement of any language. Each language has its own
rules for naming these identifiers. The rules for declaring an identifier are as follows:
• Identifier name must start with alphabetic characters, digits or underscore.
• Identifier name cannot start with a digit.
• Uppercase and lowercase letters are treated as different.
• Keywords should not be used as an identifier.
• No space must be present between the identifier name.
(c) Constants
Page No: 8
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
Constants are expressions with a fixed value. Constants can be divided into Integer
Constants, Floating-Point Constants, Character Constants, String Constants and Boolean Values.
(i) Integer Numerals are numerical constants that identify integer decimal values.
Example: 1776, 707, -273
In addition to decimal numbers C++ allows the use as Integer constants of octal numbers
(base 8) and hexadecimal numbers (base 16). If we want to express an octal number we have to
precede it with a 0 (zero character). And in order to express a hexadecimal number we have to
precede it with the characters 0x (zero, x). For example, the following literal constants are all
equivalent to each other:
75 // decimal
0113 // octal
0x4b // hexadecimal
(ii) Floating Point Constants are numbers with decimals and/or exponents. They can include
either a decimal point, an e character or both a decimal point and an e character.
Example:
3.14159 // 3.14159
6.02e23 // 6.02 x 10^23
1.6e-19 // 1.6 x 10^-19
3.0 // 3.0
(iii) Character Constants - Character Constants are enclosed within single quotes ( ‘ ‘ )
Example: 'z', ‘&’, ‘G’
(iv) String Constants - String Constants are enclosed within double quotes ( “ “ )
Example: “Hello”, “EEE Depart”
Escape codes/Escape Sequence - These are special characters that are difficult or impossible to
express otherwise in the source code of a program, like newline (\n) or tab (\t). All of them are
preceded by a backslash (\). Some of the escape codes:
\n newline
\r carriage return
\t Tab
\v vertical tab
\b backspace
\f form feed (page feed)
\a alert (beep)
\' single quote (')
\" double quote (")
\? question mark (?)
\\ backslash (\)
(v) Boolean literals - There are only two valid Boolean values: true and false. These can be
expressed in C++ as values of type bool by using the Boolean literals true and false.
Page No: 9
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
In order to store the value variable is needed. All variables must be declared before they
may be used in the program.
The following statement uses four variables numberl, number2, sum, and average. They are
declared with datatype float.
Scope of variables
A variable can be either of global or local scope. A global variable is a variable declared in
the main body of the source code, outside all functions, while a local variable is one declared within
the body of a function or a block. Global variables can be referred from anywhere in the code, even
inside functions, whenever it is after its declaration. The scope of local variables is limited to the
block enclosed in braces ({ }) where they are declared. For example, if they are declared at the
beginning of the body of a function their scope is between its declaration point and the end of that
function.
Initialization of variables
When declaring a regular local variable, its value is by default undetermined. But if we
want a variable to store a concrete value at the same moment that it is declared. We must initialize
the variable. There are two ways to do this in C++:
The first one, known as c-like, is done by appending an equal sign followed by the value to
which the variable will be initialized:
Syntax: Datatype VariableName = initial_value ;
Example: int a = 0
The other way to initialize variables, known as constructor initialization, is done by
enclosing the initial value between parentheses (()):
Syntax: Datatype VariableName (initial_value) ;
Example: int a(0);
Both ways of initializing variables are valid and equivalent in C++.
(d) Operators:
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:
Page No: 10
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
i. Arithmetic Operators
ii. Relational Operators
iii. Logical Operators
iv. Bitwise Operators
v. Assignment Operators
vi. Other Operators
Page No: 11
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
Bitwise operator works on bits and perform bit-by-bit operation. The Bitwise operators
supported by C++ language are listed in the following table.
Operator Description Example
Binary AND Operator copies a bit to (A & B) will give 12 which is 0000
&
the result if it exists in both operands. 1100
Binary OR Operator copies a bit if it (A | B) will give 61 which is 0011
|
exists in either operand. 1101
Binary XOR Operator copies the bit if (A ^ B) will give 49 which is 0011
^
it is set in one operand but not both. 0001
Binary Ones Complement Operator is (~A ) will give -61 which is 1100
~ unary and has the effect of 'flipping' 0011 in 2's complement form due to
bits. a signed binary number.
Binary Left Shift Operator. The left A << 2 will give 240 which is 1111
operands value is moved left by the 0000
<<
number of bits specified by the right
operand.
Binary Right Shift Operator. The left A >> 2 will give 15 which is 0000
operands value is moved right by the 1111
>>
number of bits specified by the right
operand.
Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-------------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
Page No: 12
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
Page No: 13
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
=======================================================================
CONTROL STATEMENTS:
Page No: 14
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
}
If the condition evaluates to true then the block of code inside the if statement will be
executed. If not the first set of code after the end of the if statement (after the closing curly brace)
will be executed.
Example:
using namespace std;
#include<iostream>
main( )
{
int x, y;
cout<<”Enter two values: “;
cin>>x>>y;
if( x > y )
{
cout<<x <<“ is Greater";
}
}
Output:
Enter two values: 25 15
25 is Greater
1.2. The if...else Statement:
An if statement can be followed by an optional else statement, which executes when the
Condition is false.
Syntax:
if(Condition)
{
//Executes when the Condition is true
}
else
{
//Executes when the Condition is false
}
Example:
using namespace std;
#include<iostream>
main( )
{
int x, y;
cout<<”Enter two values: “;
cin>>x>>y;
if( x > y )
{
cout<<x <<“ is Greater";
}
else
{
cout<<y<<” is Greater ";
}
}
Page No: 15
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
Output:
Enter two values: 25 50
50 is Greater
1.3. The if...else if...else Statement:
An if statement can be followed by an optional else if...else statement, which is very useful to
test various conditions using single if...else if statement. When using if , else if , else statements
there are few points to keep in mind.
• An if can have zero or one else's and it must come after any else if's.
• An if can have zero to many else if's and they must come before the else.
• Once an else if succeeds, none of the remaining else if's or else's will be tested.
Syntax:
if(Condition 1)
{
//Executes when the Condition 1 is true
}
else if(Condition 2)
{
//Executes when the Condition 2 is true
}
else if(Condition 3)
{
//Executes when the Condition 3 is true
}
else
{
//Executes when the none of the above condition is true.
}
Example:
using namespace std;
#include<iostream>
main( )
{
int x, y, z;
cout<<”Enter three values: “;
cin>>x>>y>>z;
if( (x>y) &&(x>z) )
{
cout<<x<<” is Greater”;
}
else if( y>z )
{
cout<<y<<” is Greater";
}
else
{
cout<<z<<” is Greater";
}
}
Page No: 16
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
Output:
Enter three values: 20 50 30
50 is Greater
1.4. Nested if...else Statement:
It is always legal to nest if-else statements which means you can use one if or else if
statement inside another if or else if statement.
Syntax:
if(Condition 1)
{
//Executes when the Condition 1 is true
if(Condition 2)
{
//Executes when the Condition 2 is true
}
}
Example:
using namespace std;
#include<iostream>
main( )
{
int x = 30;
int y = 10;
if( x == 30 )
{
if( y == 10 )
{
cout<<"X = 30 and Y = 10");
}
}
}
Output:
X = 30 and Y = 10
1.5. The switch Statement:
A switch statement allows a variable to be tested for equality against a list of values. Each
value is called a case, and the variable being switched on is checked for each case.
Syntax:
switch(expression)
{
case value1 :
//Statements
break;
case value2 :
//Statements
break;
.
.
.
//Can have any number of case statements.
default :
Page No: 17
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
//Statements
break; //Optional
}
Rules apply to a switch statement:
• The variable used in a switch statement can only be a byte, short, int, or char.
• We can have any number of case statements within a switch. Each case is followed by the
value to be compared to and a colon.
• The value for a case must be the same data type as the variable in the switch and it must be
a constant or a literal.
• When the variable being switched on is equal to a case, the statements following that case
will execute until a break statement is reached.
• When a break statement is reached, the switch terminates, and the flow of control jumps to
the next line following the switch statement.
• Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
• A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true.
No break is needed in the default case.
Example:
using namespace std;
#include<iostream>
main()
{
char input;
cout<<”Enter a Character: “;
cin>>input;
switch(input)
{
case 'A' :
cout<<"A is an Vowel";
break;
case 'E' :
cout<<"E is an Vowel ";
break;
case 'I' :
cout<<”I is an Vowel ";
break;
case 'O' :
cout<<”O is an Vowel ";
Break;
case 'U' :
cout<<"U is an Vowel ";
break;
default :
cout<<"Input Value is not an Vowel";
}
}
}
Output:
Enter a Character: U
Page No: 18
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
U is an Vowel
2. Loops:
When we need to execute a block of code several number of times referred to as a loop. C++
has three looping mechanisms. They are as follows:
• while Loop
• do...while Loop
• for Loop
2.1. The while Loop:
A while loop is a control structure that allows you to repeat a task a certain number of
times till the condition becomes false.
Syntax:
while(Condition)
{
//Statements
}
During execution, if the Condition result is true, then the statements inside the loop will be
executed. This will continue as long as the condition is true. The key point of the while loop is that
the loop will not get executed if the condition is false, the loop body will be skipped and the first
statement after the while loop will be executed.
Example:
using namespace std;
#include<iostream>
main( )
{
int x = 10;
while( x < 15 )
{
cout<<"value of x : "<< x ;
x++;
}
}
Output:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
2.2. The do...while Loop:
A do...while loop is similar to a while loop, except that a do...while loop will execute at least
one time whether the condition is true or false.
Syntax:
do
{
//Statements
}while(Condition);
Page No: 19
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
In do…while loop the Condition appears at the end of the loop, so the statements in the loop
execute once before the Condition is tested. If the Condition is true, the flow of control jumps back
up to do, and the statements in the loop execute again. This process repeats until the Condition is
false.
Example:
using namespace std;
#include<iostream>
main( )
{
int x = 10;
do
{
cout<<”value of x : " <<x;
x++;
}while( x < 15 );
}
Output:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
2.3. The for Loop:
A for loop is a repetition control structure that allows to write a loop efficiently that needs
to execute a specific number of times. A for loop is useful when we know how many times a task is
to be repeated.
Syntax:
for (initial condition; Ending Condition; increment/decrement)
{
//Statements
}
The flow of control in for loop:
• The initialization step is executed first, and only once. This step allows us to declare and
initialize any loop control variables.
• Next, the Condition is evaluated. If it is true, the body of the loop is executed. If it is false, the
body of the loop does not execute and flow of control jumps to the next statement of for
loop.
• After the body of the for loop executes, the flow of control jumps back up to the
increment/decrement statement. This statement allows us to update any loop control
variables. This statement can be left blank, as long as a semicolon appears after the
Condition.
• The Condition is now evaluated again. If it is true, the loop executes and the process repeats
itself (body of loop, then increment/decrement step, then Condition). After the Condition is
false, the for loop terminates.
Example:
using namespace std;
#include<iostream>
Page No: 20
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
main( )
{
for(int x = 10; x <=15; x++)
{
cout<<"value of x : "<<x;
}
}
Output:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
3. The break Keyword:
The break keyword is used to stop the entire loop. The break keyword must be used inside
any loop or a switch statement. The break keyword will stop the execution of the innermost loop
and start executing the next line of code after the block.
Syntax:
The syntax of a break statement is: break;
Example:
using namespace std;
#include<iostream>
main( )
{
for(int x = 0; x <5; x++)
{
if(x==3)
break;
cout<<"value of x : "<<x;
}
}
Output:
value of x : 0
value of x : 1
value of x : 2
4. The continue Keyword:
The continue keyword can be used in any of the loop control structures. It causes the loop
to immediately jump to the next iteration of the loop.
• In a for loop, the continue keyword causes flow of control to immediately jump to the
update statement.
• In a while loop or do/while loop, flow of control immediately jumps to the Condition.
Syntax:
The syntax of a continue is: continue;
Example:
using namespace std;
Page No: 21
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
#include<iostream>
main( )
{
for(int x = 0; x <5; x++)
{
if(x==3)
continue;
cout<<"value of x : "<<x;
}
}
Output:
value of x : 0
value of x : 1
value of x : 2
value of x : 4
value of x : 5
=======================================================================
ARRAYS
Declaring an Array:
Syntax of declaring an array is:
DataType ArrayName[dimension/order];
Examples:
int Age[12]; //declares an array of 12 values, each one being an integer.
float Grade[100]; //declares an array of 100 floating-point values.
Initializing an Array:
Syntax used for initializing array is:
DataType ArrayName[dimension] = { element1, element2, …, elementn};
Examples:
int number[12] = {18, 42, 25, 12, 34, 15, 63, 72, 92, 26, 26, 12};
double distance[5] = {44.14, 720.52, 96.08, 468.78, 6.28};
Page No: 22
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
#include <iostream>
using namespace std;
main( )
{
int arr[ ] = {44, 720, 96, 468, 6};
cout << "2nd member = " << arr[1] << endl;
cout << "5th member = " << arr[4] << endl;
}
Output:
2nd member = 720
5th member = 6
#include <iostream>
using namespace std;
main( )
{
int arr[ ] = {44, 720, 96, 468, 6};
for(int i=0;i<5;i++)
{
cout << "The array values are: " << arr[i] << “\t”;
}
}
Output:
The array values are: 44 720 96 468 6
Two-Dimensional Arrays:
The simplest form of the multidimensional array is the two-dimensional array. A two-
dimensional array is, a list of one-dimensional arrays. It is mainly used to perform operations on
Matrix.
Syntax of declaring an array is:
DataType ArrayName[dimension1] [dimension2];
Example:
int a[3] [4]; //declares an 3x4 2D Matrix named as “a” to store integer values..
A two-dimensional array can be think as a table, which will have x number of rows and y
number of columns. A 2-dimensional array a, which contains three rows and four columns can be
shown as below:
Page No: 23
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where
a is the name of the array, and i and j are the subscripts that uniquely identify each element in a.
Example:1
using namespace std;
#include<iostream>
main( )
{
int a[3][3],b[3][3],c[3][3];
int i,j;
cout<<"Enter the values for Matrix 1: ";
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
cin>>a[i][j];
}
}
cout<<"Enter the values for Matrix 2: ";
for(i=0;i<3;i++)
Page No: 24
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
{
for(j=0;j<3;j++)
{
cin>>b[i][j];
}
}
cout<<"The Resultant Matrix is....\n ";
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
cout<<c[i][j];
}
cout<<"\n";
}
}
Output:
Enter the values for Matrix 1:
2 2 2
2 2 2
2 2 2
Enter the values for Matrix 2:
6 6 6
6 6 6
6 6 6
Resultant Matrix is....
8 8 8
8 8 8
8 8 8
Example: 2
Passing Array as argument
using namespace std;
#include <iostream>
void printarray (int arg[ ], int length)
{
for (int n=0; n<length; ++n)
cout << arg[n] <<"\t";
cout <<"\n";
}
main( )
{
int arr1[ ] = {5, 10, 15};
int arr2[ ] = {2, 4, 6, 8, 10};
printarray (arr1,3);
printarray (arr2,5);
}
Output:
5 10 15
2 4 6 8 10
=======================================================================
Page No: 25
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
It is a common practice to organize a program into three separate files. The class
declarations are placed in a header file and the definitions of member functions go into another
file.
A SIMPLE C++ PROGRAM
FUNCTIONS:
A function is defined as a set of program statements that can be processed independently.
The process of splitting a large program into smaller tasks and designing them separately is
called modular programming or divide and conquer technology.
Advantages of Function:
• Modular Programming.
• Reduction in the amount of work and development time.
Page No: 26
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
Syntax:
Page No: 27
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
Calling Function (Or) Caller: A function that calls a defined function with arguments is called
Calling function.
Called Function (Or) Callee: The function that is called by another function is called a Callee.
PARAMETER PASSING:
❖ It is a method for communication between the calling function and the called function.
❖ There are three types of parameter passing techniques, they are
1. Call by Value (or) Pass by Value
2. Call by Address (or) Pass by Address
3. Call by Reference (or) Pass by Reference
Rules For Parameter Passing:
1. Number of arguments in function call and function declarator must be same.
2. Data type of arguments in function call and function declarator must be same.
1. Call By Value:
❖ It is the default mechanism of parameter passing.
❖ This process will not change the contents of arguments in the calling function [actual
arguments].
❖ In this process only a copy of the actual argument is passed to the formal argument.
❖ Even if the value is changed in the called function, the value will not be changed in the
calling function.
Example:
using namespace std;
#include<iostream>
void swap (int x, int y); //Function Declaration
main ( )
{
int a = 10, b = 20;
cout <<”Values Before Swapping: “<<a << b;
swap (a,b); //Function call
cout <<”Values After Swapping: “<<a << b;
}
void swap (int x, int y) //Function Definition
{
int t;
t = x;
x = y;
y = t;
}
2) Call By Address:
❖ In this process instead of passing the value of actual arguments the address of actual
arguments will be passed.
❖ The value of actual parameter will be referenced from memory.
❖ In this process the actual value will be changed.
Example:
using namespace std;
#include<iostream>
Page No: 28
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
Page No: 29
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
Output:
The Product is= 12
The Product is= 480
The Product is= 240
The Product is= 120
=========================================================================
inline Functions:
In case of very small functions inorder to avoid context switching, the entire function will
be loaded next to the function call. This function will be loaded in the main function itself.
This is called as inline function.
Syntax:
inline ReturnType FunctionName(arguments);
Example:
using namespace std;
#include<iostream>
inline void sum(int x, int y, int z); //inline function declaration
main( )
{
sum(12,5,15);
}
void sum(int x, int y, int z) //inline function definition
{
cout<<"\nThe Sum of three number is="<<(x+y+z);
}
Page No: 30
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
Output:
The Sum of three number is= 32
POINTERS:
A pointer is a variable used to store the address of another variable. Like any variable or
constant, pointer must be declared before work with it. The general form of a pointer variable
declaration is:
DataType *variableName;
Where,
• DataType is the pointer's base type; it must be a valid C++ type
• variableName is the name of the pointer variable.
• The asterisk is being used to indicate a variable as a pointer
Following are the valid pointer declaration:
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character
Using Pointers in C++:
Operations done with the pointers very frequently:
• First define a pointer variables
• Assign the address of a variable to a pointer
• Finally access the value at the address available in the pointer variable.
This is done by using unary operator * that returns the value of the variable located at the address
specified by its operand.
Example:
#include <iostream>
using namespace std;
main( )
{
int x = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &x; // store address of var in pointer variable
cout << "Value of variable x : "<<x;
cout << "Address stored in ip variable: ";
cout << ip; // print the address stored in ip pointer variable
cout << "Value of *ip variable: ";
cout << *ip; // access the value at the address available in pointer
}
Output:
Value of variable x : 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20
Page No: 31
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
A variable that is a pointer to a pointer must be declared as such. This is done by placing an
additional asterisk in front of its name. For example, following is the declaration to declare a
pointer to a pointer of type int: int **var;
When a target value is indirectly pointed to by a pointer to a pointer, accessing that value
requires that the asterisk operator be applied twice, as is shown below in the example:
#include <iostream>
using namespace std;
main ( )
{
int var; int *ptr; int **pptr;
var = 3000;
ptr = &var; // take the address of var
pptr = &ptr; // take the address of ptr using address of operator &
// 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;
}
Output:
Value of var :3000
Value available at *ptr :3000
Value available at **pptr :3000
=======================================================================
CLASSES:
• Class is a unit which contains both data and the functions that operate on the data.
• The internal data of the class is called as data member and the functions are called
member function.
• The variables of a class are called objects or instances of a class.
• A class is a way to bind the data and its associated functions together.
Class Declaration:
Syntax:
class ClassName
{
AccessSpecifier:
//Data members
//Member Functions
};
Where,
• class is a keyword.
Page No: 32
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
The variables declared inside the class are known as data members and functions are
known as member functions. Only the member functions can have access to the private data
members and member functions. However, the public members (both functions and data) can be
accessed from outside the class.
Page No: 33
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
}
};
void main( )
{
Example e1;
e1.get( );
e1.Square( );
e1.Cube( );
}
void main( )
Page No: 34
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
{
Example e1;
e1.get( ); e1.Square( ); e1.Cube( );
}
=======================================================================
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.
className objectName;
Example:
• Student S1; //object named S1 was created.
• More than one object can be created using a single statement: Student S1,S2,….Sn;
Pointer Objects:
• In C++ pointers can also have an address for an object. They are known as pointers to
objects.
• A pointer to an object contains an address of that object.
• Object pointers are useful in creating objects at run time.
• Syntax for creating Pointer Object:
ClassName *ptrObj;
• Using pointer objects member of a class can be accessed with the help of the following
syntax:
PtrObj →MemberFunction( );
Program:
using namespace std;
#include<iostream>
class student
{
public: int a, b, c, sum;
void getdetails( )
{
cin >> a >> b >> c;
}
void calculate( )
{
sum = a+b+c;
}
void printdetails( )
{
cout << sum;
Page No: 35
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
}
};
main( )
{
student *s1;
s1 -> a=10;
s1 -> b=15;
s1 -> c=25;
s1 -> calculate( );
s1 -> printdetails( );
}
CONSTANT OBJECTS:
• Constant objects are not modifiable.
• It is denoted by using the keyword “const”.
• Const object is not allowed to do operations which modify the object.
• Only the functions that are defined as const can be accessed by const objects. Even public
variables of the object are not modifiable.
• When we do not want any accidental change in the objects properties, we should define the
object as const object.
Example: const matrix X(m,n); //Object X is constant
X is a constant object of the class matrix, any attempt to modify the values of m and n will
generate compile-time error. A constant object can call only const member functions.
Program:
using namespace std;
#include<iostream>
class student
{
public:
int rno;
char name[10], char addr[10];
void printdetails ( ) const //const function
{
cout << “Roll No: “<<rno;
cout << “Name: “<<name;
cout << “Address: “<<addr;
}
};
void main( )
{
student s;
s1.rno = 1; s1.name = “anju”; s1.addr = “nagercoil”;
s1.printdetails( );
const student s2=s1; //constant object
s2.printdetails( );
s2.rno = 5; //Error: using constant object trying to
// modify a value of a member
cout << s4.rno;
}
=======================================================================
Page No: 36
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
Static Members:
• A data member of a class can be qualified as static.
• Properties of static member variables are,
• They are normally used to maintain values commonly to the entire class.
• It is initialized to zero when the first object of its class is created. No other initialization is
permitted.
• Only one copy of that member is created for the entire class and is shared by all the objects
of that class.
• It is visible only within the class, but its life time is the entire program.
• They cannot be declared either const or volatile.
Syntax:
static datatype datamember; and static datatype memberfunction( );
Example:
static int s;
static int add(s);
Example Program:
using namespace std;
#include<iostream>
class Flowers
{
public:
char n[10];
static int c;
void get( )
{
cout<<"\nEnter the Flower name: ";
cin>>n;
c++;
}
static void put( )
{
cout<<"\nThe total number of flowers are : "<<c;
}
};
int Flowers::c;
main( )
{
Flowers a1,a2,a3,a4;
a1.get( );
a2.get( );
a3.get( );
a4.get( );
a1.put( );
}
Output:
Enter the flower name: Rose
Enter the flower name: Lotus
Enter the flower name: Lilly
Enter the flower name: Jasmine
The total numbers of flowers are: 4
=======================================================================
Page No: 37
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
NESTED CLASS:
➢ A class declared as a member of another class is called as a nested class or a class within
another class.
➢ The name of the nested class is local to the enclosing class.
➢ Defining the nested class as “private” only nesting class can refer to it others cannot.
➢ Defining the nested class in the “public” part of the nesting class, it is available to those who
have access to the nesting class.
Syntax:
class outer class name
{
private:
// data of outer class
public:
class inner class name
{
private:
// data of inner class
public:
// data of inner class
};
};
===============================================
========================
LOCAL CLASS:
Classes can be defined and used inside a function or a block. Such classes are called local
classes.
• It cannot access the private variables of the class. One way to access private variables of the
class is to become a friend of it.
• Local classes can use global variables (declared above the function) and static variables
declared inside the function but cannot use automatic local variables. The global variables
should be used with the scope operator (::).
• There are some restrictions in constructing local classes. They cannot have static data
members and member functions must be defined inside the local classes.
• Enclosing function cannot access the private members of a local class. However, we can
achieve this by declaring the enclosing function as a friend.
Syntax:
ReturnType FunctionName(args)
{
class className
{
};
className obj;
}
Syntax Example:
void Display( )
{
class Local
{
};
Page No: 38
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
Local obj;
}
Program:
void display( )
{
class local
{
public:
int x, y, z;
void get( )
{
cout<<”Enter the values:”;
cin>>x>>y>>z;
}
void add( )
{
z=x+y;
cout<<”Sum of two numbers = ”<<z;
}
}; //end of local class
local obj;
obj.get( );
obj.add( );
} //end of function
void main( )
{
void display( );
display( ); //Function call
}
=======================================================================
QUESTIONS:
1) What are the Features of OOP’s & how are they implemented in C++? (or) Explain object-
oriented paradigm with all its essential elements. (or) Explain the following concepts of
object oriented programming in detail with an example.
(i) Data abstraction (ii) Inheritance
(iii) Polymorphism (iv) Objects.
2) Describe the advantages and applications of OOPs technology.
3) State the merits and demerits of object oriented methodology.
4) Mention about the Native/ Basic data types in C++.
5) List out the C++ operators and explain those operators with example.
6) Explain about different control statements in C++.
7) Define Array. Explain its types with an example for each type.
8) What are the different ways of argument passing and explain it with suitable example
programs?
9) Explain about Default argument function with an example to multiply six numbers in detail.
10) What is an inline function? With an example.
Page No: 39
2 1 CS C1 0 1 T – OBJ E CT O R IEN TE D DES IG N A N D P R O G RA MM IN G
11) What are the differences between pointers to constants and constant pointers?
12) Explain about class and object in detail with an example by defining the members inside and
outside the class.
13) Briefly explain the concept of static members with simple example programs.
14) Explain about Nested class with an example of nesting three classes.
15) Explain about Local class with an example.
16) Write a C++ program to extract the elements placed on the odd position of the array.
17) Write a C++ program to print the sum of all squares between 1 and N, where N is a number
accepted from the keyboard(i.e.) 1+4+…..+(N*N).
Page No: 40