0% found this document useful (0 votes)
74 views

Unit 1

The document discusses the development of C++ and provides an example "Hello World" program to demonstrate basic C++ syntax. It was created to add object-oriented programming features to C by providing mechanisms like classes to support data abstraction. C++ is a versatile language suitable for large complex applications and builds on C for low-level machine interactions. The example program prints "Hello World" and is broken down to explain features like headers, namespaces, functions, and output streams.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views

Unit 1

The document discusses the development of C++ and provides an example "Hello World" program to demonstrate basic C++ syntax. It was created to add object-oriented programming features to C by providing mechanisms like classes to support data abstraction. C++ is a versatile language suitable for large complex applications and builds on C for low-level machine interactions. The example program prints "Hello World" and is broken down to explain features like headers, namespaces, functions, and output streams.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

C++ Unit I

Introduction

The main pitfall with standard C has been identified as the lack of facilities for data
abstraction. With the emergence of more abstract and modular languages like Modula-2 and
Ada and Object-oriented languages like Small-Talk, BJARNE STROUSRUP at Bells Lab
was motivated to develop C++ by upgrading C with appropriate mechanisms to create object
like abstract data structures. The introduction of the class mechanism in C++ mainly
provides the base for implementing abstract data types to suit object-oriented programming.
The C++ language is thus considered as the superset of the standard C.

BJARNE STROUSRUP, The Father of C++

Applications of C++
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 applications systems.
• Since C++ allow 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 closed 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.

First/Sample/Example C++ program

Our first C++ program is a “Hello World!” program that prints the text “Hello World!” as
the output on the screen.

#include<iostream>
using namespace std;
int main()
{
cout<<"Hello World!";
return0;
}

The above code is divided into six major parts:

1 #include <iostream>
2 using namespace std
3 ;
1
4 int main() { }
5 cout<< “Hello World!”;
6 return 0;

1. What is #include <iostream>?

This statement includes the header file into the application so that we are able to use the
operations included in them.

What is iostream?

iostream is the header file. It is a standard C++ input/output library file.


It comes packaged with the compiler/IDE and contains mechanisms to get the
information from the user and print same or added information to a file, screen or any
other media.

What is #include?

The #include includesiostream file into the program. This ensures that now we are
able to use the operations, iostream operations (like: taking input from user,
displaying output on the screen), in the program.

2. What is using namespace std;”?

The statement tells that we are “using” the “namespace” “std” in our program.
We use the namespace std to make it easier to reference operations included in that
namespace.
If we hadn’t used the namespace, we’d have to write std::cout instead of cout. This tells the
compiler that every cout is actually std::cout.

What’s a namespace?

It’s a region where our code resides. It limits or expands the scope of our code to one or
more files.

Why do you use namespace?

Like two persons can have the same name, variables and functions in C++ can have same
names as well. The use of namespace is to avoid the confusion of which variables/functions
we are referencing to.

What is std?

std is a standard namespace used in C++.


3. Semicolon ”;”

The semicolon is a terminal. It terminates a statement. When missed or incorrectly used, it


will cause a lot of issues.
4. int main() { }

It is the main function of the program. The code inside { } is called the body and is executed
first when we run our C++ program.

It is one thing that is mandatory in a C++ program.


5. cout<< “Hello World!”;

2
This statement prints “Hello World!” onto the output screen.

The cout is an object of standard output stream. It outputs/prints the data after << , i.e.
Hello World!into a stream (in this case, the output screen).

What is a stream?

Stream is basically a sequence of objects, usually bytes. It can describe files, input/output
terminal, sockets, etc.

What is <<?

<< is the insertion operator used to write formatted data into the stream.

6. What is return 0;?

This statement returns 0 ‘zero’.

This is called a “return” statement. It isn’t mandatory to return anything from the main()
function but is rather a convention. If not return, the compiler returns a status
automatically.

Why zero in return statement?

It denotes Exit status of the application that basically tells system “The program worked
fine.”

TOKENS:

Tokens are the basic lexical building blocks of source code. In other words, tokens
are one or more symbols understood by the compiler that help it interpret the
program code.

Characters are combined into tokens according to the rules of the programming
language.

The compiler checks the tokens so that they can be formed into legal strings
according to the syntax of the language.

There are five classes of tokens:


1. Identifiers,
2. Reserved words(keywords),
3. Operators,
4. Separators, and
5. Constants.

1. Identifiers:
It is a sequence of characters invented by the programmer to identify or name a
specific object, and the name is formed by a sequence of letters, digits, and
underscores.

2. Keywords:
3
These are explicitly reserved words that have a strict meaning as individual tokens to
the compiler. They cannot be redefined or used in other contexts. Use of variable
names with the same name as any of the keywords will cause a compiler error.

3. Operators:
These are tokens used to indicate an action to be taken (usually arithmetic
operations, logical operations, bit operations, and assignment operations). Operators
can be simple operators (a single character token) or compound operators (two or
more character tokens).

4. Separators:
These are tokens used to separate other tokens. Two common kinds of separators
are indicators of an end of an instruction and separators used for grouping.

5. Constants:
It is an entity that does not change.

Consider the following piece of code

Here, the tokens that will be generated are


Keywords : if , else
Identifier : x
Constants : 2, 10,5
Operators : +,=
Separator : ;

Identifiers:
Identifier or name is a sequence of characters created by the programmer to identify
or name a specific object.
In C++, variables, arrays, functions, and labels are named. Describing them may
help to learn something about the character of the language since they are elements
that C++ permits the programmer to define and manipulate.

Some rules must be kept in mind when naming identifiers.


These are stated as follows:
1. The first character must be an alphabetic character (lower-case or capital letters)
or an underscore ‘_’.
2. All characters must be alphabetic characters, digits, or underscores.
3. The first 31 characters of the identifier are significant. Identifiers that share the
same first 31 characters may be indistinguishable from each other.
4. A keyword cannot be duplicated by an identifier. A keyword is word which has
special meaning in C++.

Some examples of proper identifiers are


employee_number,
box_4_weight,
monthly_pay,
interest_per_annum,

4
job_number,
and tool_4.

Some examples of incorrect identifiers are


230_item,
#pulse_rate,
total~amount,
/profit margin, and
~cost_per_ item

Special characters :

All characters other than listed as alphabets, numerals and underscore, are special
characters.

Keywords
Keywords are also identifiers but cannot be user defined since they are reserved
words.

Keywords in C++

asm Else operator template


auto Enum private this
break Extern protected throw
case Float public try
catch For register typedef
char Friend return union
class Goto short unsigned
const If signed virtual
continue Inline sizeof void
default Int static volatile
delete Long struct while
double New switch -

Variables:
As you probably know, a variable is a named location in memory that is used to hold
a value that may be modified by the program. All variables must be declared before
they can be used. The general form of a declaration is

typevariable_list;

Here, type must be a valid data type plus any modifiers, and variable_listmay consist
of one or more identifier names separated by commas. Here are some declarations:
inti, j, l;
shortintsi;
unsignedintui;
doublebalance, profit, loss;

Remember, in C/C++ the name of a variable has nothing to do with its type.

5
Where Variables Are Declared:
Variables are declared in three basic places: inside functions, in the definition of
function parameters, and outside of all functions. These are local variables,
formal parameters, and global variables.

Rules for defining variable name:


 A variable name can have one or more letters or digits or underscore for
example character _
 White space, punctuation symbols or other characters are not permitted to
denote variable name.
 A variable name must begin with a letter.
 Variable names cannot be keywords or any reserved words of the C++
programming language.
 C++ is a case-sensitive language. Variable names written in capital letters
differ from variable names with the same name but written in small letters. For
example, the variable name EXFORSYS differs from the variable name
exforsys.

Q) Explain about constants, variables in c++( for variables take above content
briefly)

Constants
Constants refer to fixed values that the program may not alter. Constants can be of
any of the basic data types. The way each constant is represented depends upon its
type. Constants are also called literals. Character constants are enclosed between
single quotes.
For example 'a' and '%' are both character constants.

Integer constants are specified as numbers without fractional components. For


example, 10 and –100 are integer constants.

Floating-point constants require the decimal point followed by the number's fractional
component. For example, 11.123 is a floating-point constant.

C/C++ also allows you to use scientific notation for floating-point numbers.

Here are some examples:


Data type Constant examples
int 1, 123, 21000 , −234
long int 35000L, 34L
unsigned int 10000U , 987U, 40000U
float 123.23F, 4.34e 3F
double 123.23, 1.0, 0.9876324
long double 1001.2L

Hexadecimal and Octal Constants


It is sometimes easier to use a number system based on 8 or 16 rather than 10 (our
standard decimal system).
int hex = 0x80; /* 128 in decimal */
int oct = 012; /* 10 in decimal */

String Constants

6
C/C++ supports one other type of constant: the string.
A string is a set of characters enclosed in double quotes.
For example, "this is a test" is a string.

Backslash Character Constants:


Enclosing character constants in single quotes works for most printing characters. A
few, however, such as the carriage return, are impossible to enter into a string from
the keyboard. For this reason, C/C++ include the special backslash character
constants. These are also referred to as escape sequences. You should use the
backslash codes instead of their ASCII equivalents to help ensure portability.

Code Meaning
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\" Double quote
\' Single quote
\0 Null
\\ Backslash
\v Vertical tab
\a Alert
\? Question mark
\N Octal constant (where N is an octal constant)
\xN Hexadecimal constant (where N is a hexadecimal constant)

Data Types
What is a data type?
When we wish to store data in a C++ program, such as a whole number or a
character, we have to tell the compiler which type of data we want to store. The data
type will have characteristics such as the range of values that can be stored and the
operations that can be performed on variables of that type.

Q). Write about data types in c++. (in this case, cover total topic briefly)
Data types in C++ can be classified under various categories as shown in Fig.

7
Basic Data Types (Built-in Data Types) or Primary data types:
The Six Basic Data Types:
There are six atomic data types in C++: character, integer, floating-point, double
floating-point, boolean, and novalue (char, int, float, double, bool, and void,
respectively).

Modifiers(signed, unsigned, long, and short):


With the exception of void, the basic data types may have several modifiers
preceding them to serve the needs of various situations. The modifiers signed,
unsigned, long, and short may be applied to character and integer basic data
types. However, the modifier long may also be applied to double.

8
bool data type :
bool data type can store two value only 0 or 1. 0 for false& 1 for true. Any nonzero value is
also considered as true value. If we declare bool variable az = 1212313; it storesaz = 1 or az
= true; It shows 0 when it is false or value is 0.

Q) What are the derived data-types in C++? Explain.

Derived Data types are:


 Arrays
 Functions
 Pointers and
 Reference
Arrays:
 An arrayis a collection of variables of the same type that are referred to
through a common name.
 A specific element in an array is accessed by an index.
 In C/C++, all arrays consist of contiguous memory locations.
 The lowest address corresponds to the first element and the highest address
to the last element.
 Arrays may have from one to several dimensions.
 The most common array is the null-terminated string, which is simply an array
of characters terminated by a null.
 Arrays and pointers are closely related; a discussion of one usually refers to
the other.

Functions:
Functions are the building blocks of C and C++ and the place where all program
activity occurs.

A function is a group of statements that is executed when it is called from some point
of the program. The following is its format:

type name ( parameter1, parameter2, ...)


{
statements
}

where:
• type is the data type specifier of the data returned by the function.
• name is the identifier by which it will be possible to call the function.
• parameters (as many as needed): Each parameter consists of a data type
specifier followed by an identifier, like any regular variable declaration (for example:
int x) and which acts within the function as a regular local variable. They allow to
pass arguments to the function when it is called. The different parameters are
separated by commas.
• statements is the function's body. It is a block of statements surrounded by
braces { }.
9
Pointers:
A pointeris a variable that holds a memory address. This address is the location of
another object (typically another variable) in memory.

For example, if one variable contains the address of another variable, the first
variable is said to point to the second.

Reference variables
The '&'operator is used to reference an object. When using this operator on an
object, you are provided with a pointer to that object. This new pointer can be used
as a parameter or be assigned to a variable.

programming.

10
OPERATORS IN C++
An operator is a symbol that tells the compiler to perform specific mathematical or
logicalmanipulations.
C++ is rich in built-in operators and provides the following types of operators:
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc 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 Example


+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiplies both operands A * B will give 200
/ Divides numerator by de-numerator B / A will give 2
% Modulus Operator and remainder of after an integer division. B % A will give 0
++ Increment operator, increases integervalue by one A++ will give 11
-- Decrement operator, decreases integervalue by one A-- will give 9

Relational Operators:
There are following relational operators supported by C++ language

11
Assume variable A holds 10 and variable B holds 20, then:

Operator Description Example


== Checks if the values of two operands are A == B is not true.
equal or not, if yes then conditionbecomes true.

!= Checks if the values of two operands are A ! = B is true.


equal or not, if values are not equal then
condition becomes true.

> Checks if the value of left operand isgreater thanA >B is not true.
the value of right operand, ifyes then condition
becomes true.

< Checks if the value of left operand is lessthan A <B is true.


the value of right operand, if yesthen condition
becomes true.

>= Checks if the value of left operand isgreater than A >= B is not true.
or equal to the value of rightoperand, if yes then
condition becomestrue.

<= Checks if the value of left operand is lessthan A <= B is true.


or equal to the value of rightoperand, if yes then
condition becomestrue.

Logical Operators:
There are following logical operators supported by C++ language

Assume variable A holds 1 and variable B holds 0, then:

Operator Description Example


&& Called Logical AND operator. If both theoperands A && B is false.
are non-zero, then conditionbecomes true.

|| Called Logical OR Operator. If any of thetwo A | | B is true.


operands is non-zero, then conditionbecomes true.

! Called Logical NOT Operator. Use toreverses the ! A && B is true.


logical state of its operand. Ifa condition is true,
then Logical NOToperator will make false.

Bitwise Operators:
Bitwise operator works on bits and perform bit-by-bit operation.

The truth tables for &, |, and ^ areas follows:

p q p&q p|q p^q


0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1

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
12
A|B =0011 1101
A^B = 0011 0001
~A = 1100 0011

The Bitwise operators supported by C++ language are listed in the following table.
Assumevariable A holds 60 and variable B holds 13, then:
Operator Description Example
& Binary AND Operator copies a bit A & B will give 12 which is 0000 1100
to theresult if it exists in both operands.

| Binary OR Operator copies a bit A | B will give 61 which is 0011 1101


if it existsin either operand.

^ Binary XOR Operator copies the bit ABwill give 49 which is 0011 0001
if it isset in one operand but not both.

~ Binary Ones Complement Operator is A will give -61 which is 1100 0011 in
unary and has the effect of 'flipping' bits. 2's complement form due to a signed
binary number.

<< Binary Left Shift Operator. A << 2 will give 240 which is 1111 0000
The leftoperands value is moved left
by thenumber of bits specified by
the rightoperand.

>> Binary Right Shift Operator. The left A>> 2 will give 15 which is 0000 1111
operands value is moved right by the
number of bits specified by the right
operand.

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

Operator Description Example


= Simple assignment operator, C = A + B will assign value of A + B into C
Assigns values from right side
operands to leftside operand

+= Add AND assignment operator, C += A is equivalent to C = C + A


It addsright operand to the left
operand andassign the result
to left operand

-= Subtract AND assignment operator, It C-= A is equivalent to C = C - A


subtracts right operand from the left
operand and assign the result to leftoperand

*= Multiply AND assignment operator, It C *= A is equivalent to C = C * A


multiplies right operand with the left
operand and assign the result to left
operand

/= Divide AND assignment operator, It C /= A is equivalent to C = C / A


divides left operand with the rightoperand
and assign the result to leftoperand

%= Modulus AND assignment operator, It C %= A is equivalent to C = C %A


takes modulus using two operands and
assign the result to left operand

<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2


>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
13
^= bitwise exclusive OR and assignmentoperator C ^= 2 is same as C = C ^ 2
|= bitwise inclusive OR and assignmentoperator C |= 2 is same as C = C | 2

Misc Operators (Special Operators)


There are few other operators supported by C++ Language.

Operator Description
sizeof sizeof operator returns the size of a variable. For example,
sizeofa,where a is integer, will return 4.

Condition ?X : Y Conditional operator. If Condition is true ?then it returns value X


:otherwise value Y

, Comma operator causes a sequence of operations to


beperformed. The value of the entire comma expression is the
valueof the last expression of the comma-separated list.

.dotand -> arrowMember operators are used to reference individual


members ofclasses, structures, and unions.

cast Casting operators convert one data type to another. For


example,int2.2000 would return 2.

& Reference Operator or Pointer operator & returns the address


of a variable. For example, &a; will give actual address of the
variable.

* Pointer operator * is pointer to a variable. For example *var;


will point to a variable var.

Operator Precedence in C++:

Operator precedence determines the grouping of terms in an expression. This


affects how anexpression is evaluated. Certain operators have higher precedence
than others; for example, themultiplication operator has higher precedence than the
addition operator:

For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has


higherprecedence than +, so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those
with the lowestappear at the bottom. Within an expression, higher precedence
operators will be evaluated first.

Category Operator Associativity


Postfix ::[] -> . ++ - - Left to right
Unary + - ! ~ ++ - - type* &sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift <<>> Left to right
Relational <<= >>= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
14
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>=<<=&= ^= |= Right to left
Comma , Left to right

EXPRESSIONS IN C++
"Expression in C++ is a form when we combine operands (variables and constant)
and C++ OPERATORS."

Expression can also be defined as:


"Expression in C++ is a combination of Operands and Operators."

OPERANDS IN C++ PROGRAM are those values on which we want to perform


operation.

There are four types of expressions:


1. Constant Expressions:
2. Arithmetic expression
3. Relational expression
4. Logical expression

1 Constant Expressions:
Constant Expressions consist of only constant values, Examples:
15
20+15/2.0
‘X’

2. Arithmetic Expressions:
"An expression in which arithmetic operators are used is called arithmetic
expression".
For example an arithmetic expression is look just like that a+b=5

Modes of Arithmetic Expressions


1. Mixed arithmetic
2. Real arithmetic
3. Integer arithmetic

Integer arithmetic mode


In this mode when arithmetic operation perform by using integer values it always
result an integer value.

for example:
a=5 , b=5
a*b=25 ,
a/b=1 ,
a+b=10 ,
a-b=0

Real arithmetic mode


In this mode when a arithmetic operation is performed by usingfloating point
numbers it always result an floating value.

15
a=10.0 , b=5.0
a*b=50.0
a/b=2.0
a+b=15.0
a-b=5.0

Mixed arithmetic mode


In this mode when an arithmetic operation performed on float and integer values it
always result a float value.

For example:
a=10 , b=5.0
a*b=50.0,
a/b=2.0,
a+b=15.0,
a-b=5.0

3. Relational expressions
"A relational operator with constants and variables makes relational expression or An
expressions in which relational operators are use is called relational expression."

Operator Relational Expression Example


== A == B
!= A!=B
> A >B
< A <B
>= A >= B
<= A <= B

4Logical Expression
"A Logical operator with constants and variables makes logical expression or An
expressions in which logical operators are use is called logical expression."
Examples using logical operators
(i< 10) && (j > 0)
((x + y) <= 15) || (i == 5)
!((i >= 10) || (j <= 0))
(i< 10) && 0

Writing a C++ program: return 0;


Skeleton/Structure of typical C++ Program
Program heading
Begin
Type or variable declaration
Statements of operation
Results
End

//include this file for cout


#include <iostream>
using namespace std;
16
int main()
{
//print out the text string, "Hello, World!"
cout<< "Hello, World!" <<endl;

return 0;
}

C++ Basic Input/Output

C++ I/O occurs in streams, which are sequences of bytes.


If bytes flow from a device likes a keyboard, a disk drive, or a network connection
etc. to main memory, this is called input operation and if bytes flow from main
memory to a device likes a display screen, a printer, a disk drive, or a network
connection, etc, this is called output operation.

The header file iostream must be included to make use of the input/output (cin/cout)
operators.

Standard Output (cout)


By default, the standard output of a program points at the screen. So with the
coutoperator and the “insertion” operator (<<) you can print a message onto the
screen. Let’s take a look at an example:

#include<iostream>
using namespace std;
int main()
{
cout<< "Hello World!";
return 0;
}
Note:the double quotes around Hello World (because it is a constant string of
characters.)

Standard input (cin)


In most cases the standard input device is the keyboard. With the cin and >>
operators it is possible to read input from the keyboard.

Take a look at an example:


cout<< "Hello World!";

#include<iostream>
using namespace std;

int main()
{
char MY_CHAR;
cout<< "Press a character and press return: ";
cin>> MY_CHAR;
cout<< MY_CHAR;
return 0;
}

17
Control Structures(Decision Making):

Q) What are various control structures in C++ (or) write about control flow
statements.
There are three types of control structures:
1) Sequence Structure (straight line)
2) Selection Structure (branching)
3) Loop structure (iteration or repetition)

The following figure shows how these structures are implemented using one-entry,
one-exit concept.

2 Selection Structure (branching) (or) Branching statements


1) Simple if Statement
2) if – else Statement
3) Nested if-else statement
4) else – if Ladder
5) switchstatement
6) Conditional Expression Operator
7) gotoStatement (also belongs jump statements)

18
Loop structure (iteration or repetition) (or) Loop control statements
1) forLoop
2) whileLoop
3) do-while Loop

Jumping statements:
1) gotoStatement
2) breakStatement
3) continueStatement

(1) Simple “if” statement:


The “if‟ statement is a powerful decision making statement and is used to control the
flow of execution of statements.

Syntax:
if (Condition or test expression)
Statement;
Rest of the program;

OR
if (Condition or test expression)
{
Statements;
}
Rest of the program

o It is basically a “Two-way” decision statement (one for TRUE and other


for FALSE)
o It has only one option.
o The statement as executed only when the condition is true.
o In case the condition is false the compiler skips the lines within the “if
Block”.
o The condition is always enclosed within a pair of parenthesis ie ( ) .
o The conditional statement should not the terminated with Semi-colons
(ie ;)
o The Statements following the “if”-statement are normally enclosed in
Curly Braces ie { }.
o The Curly Braces indicates the scope of “if” statement.
o The default scope is one statement. But it is good practice to use curly
braces even with a single statement.
o The statement block may be a single statement or a group of
statements.
o If the Test Expression / Conditions is TRUE, the Statement Block will
be executed and executes rest of the program.
If the Test Expression / Condition is FALSE, the Statement Block will be skipped and
rest of the program executes next..
Example 1:
# include<iostream>
using namespace std;
int main( )
{
int m,n;
cout<<“\n Enter two numbers:”;
cin>>m>>n;

19
if((m-n)= =0)
cout<<“\n two numbers are equal”;
return 0;
}

Example 2:
#include <iostream>
using namespace std;
int main ()
{
int a = 10; / / local variable definition
if( a < 20 ) // check the boolean condition using if statement
{
cout<<"a is less than 20\n"; // if condition is true then print the following
}
cout<<"value of a is ”<<a;
return 0;
}

(2) “if-else” Statement:


o It is observed that the ifstatement executes only when the condition
following if is true.
o It does nothing when the condition is false.
o In if-else either True-Block or False – Block will be executed and not
both.
o The “else” Statement cannot be used without “if”.

Syntax:
if ( Test Expression or Condition )
{
/*true block (or) if block */
Statements;
}
else
{
/* false block (or) else block */
Statements;
}

Example: Write a program to print the given number is even or odd.


# include<iostream>
using namespace std;
int main( )
{
int n;
cout<<“Enter a number:”<<endl;
cin>>n;
if( (n%2)==0 )
cout<<”\n The given number is EVEN ”;
else
cout<<“\n The given number is ODD ”;
return 0;
}

20
Output:
Run 1:
Enter a number: 24
The given number is EVEN

Run 2:
/* that means one more time we run the program */
Enter a number: 17
The given number is ODD

(3) Nested “if–else” Statement:


- Using of one if-else statement in another if-else statement is called as nested
if-else control statement.
- When a series of decisions are involved, we may have to use more than one
if-else statement in nested form.

Syntax:
if ( Test Condition1)
{
if ( Test Condition2)
{
Statement -1;
}
else
{
Statement -2;
}
}
else
{
if ( Test Condition3)
{
Statement -3;
}
else
{
Statement -4;
}
} /* end of outer if-else */

- If Test Condition-1 is true then enter into outer if block, and it checks Test
Condition-2 if it is true then Statement-1 executed if it is false then else block
executed i.e Statement-2.

- If Test Condition -1 is false then it skips the outer if block and it goes to else
block and Test Condition-3 checks if it is true then Statement-3 executed, else
Statement-4 executed.

Example: Program to select and print the largest of the three float numbers using
nested “if-else” statements.
# include<iostream>
using namespace std;
int main( )
{

21
float a,b,c;
cout<<“Enter Three Values:”;
cin>>a>>b>>c;

cout<<“\n finding greatest number:” ;


if(a>b)
{
if(a>c)
cout<<“ Greatest number is “<<a;
else
cout<<“ Greatest number is “<<c;
}
else
{
if (b>c)
cout<<“ Greatest number is “<<b;
else
cout<<“ Greatest number is “<<c;
}
return 0;
}

Output:
Run 1:
Enter three values: 9.12 5.34 3.87
Largest Value is: 9.12

Run 2:
Enter three values: 45.781 78.34 145.86
Largest Value is: 145.86

(4) The “else – if” Ladder:


o This is another way of putting if 's together when multiple decisions are
involved.
o A multipath decision is a chain of if s in which the statement associated
with each else is an if.
o Hence it forms a ladder called else–if ladder.

Syntax:
if (Test Condition -1)
Statement -1;
else if ( Test Condition -2)
Statement -2;
else if ( Test Condition -3)
Statement -3;
:
:
:
: else if ( Test Condition –n)
Statement –n;
else
default statement;

Rest of the Program Statements-X;

22
- The above construction is known as else if ladders.
- The conditions are evaluated from top to bottom.
- As soon as a true condition is found, the statement associated with it is
executed and the control is transferred to the Rest of the Program
Statement–X (skipping rest of the ladder).
- When all the "n conditions become false, then the final else containing the
default statement will be executed.

Write a program to read three numbers and find the largest one by using “else-if”
ladder.
# include<iostream>
using namespace std;
int main( )
{
int a, b, c;
cout<<“Enter 1st number: \n”;
cin>>a;
cout<<“Enter 2nd number: \n”;
cin>>b;
cout<<“Enter 3rd number: \n”;
cin>>c;

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


cout<<“Highest Number is:”<<a;
else if ((b>a) && (b>c))
cout<<“Highest Number is: ”<< b;
else
cout<<“Highest Numbers is: ”<< c;
return 0;
}

Output:
Enter 1st number: 52
Enter 2nd number: 74
Enter 3rd number: 90
Highest Numbers is: 90

23
(5) The “switch-case” Statement:
- The switch statement causes a particular group of statements to be chosen
from several available groups.
- The selection is based upon the current value of an expression which is
included within the switch statement.
- The switch statement is a multi-way branch statement.
- In a program if there is a possibility to make a choice from a number of
options, this structured selected is useful.
- The switch statement requires only one argument of intorchar data type,
which is checked with number of case options.
- The switch statement evaluates expression and then looks for its value
among the case constants.
- If the value matches with case constant, then that particular case statement is
executed. If no one case constant not matched then default is executed.
- Here switch, case and default are reserved words or keywords.
- Every case statement terminates with colon “:”.
- In switch each case block should end with break statement, i.e.

Syntax:
switch(variable or expression)
{
case Constantvalue-1: Block -1;
(or)
Statement-1;
break;
case Constantvalue-2: Block -2;
(or)
Statement-2;
break;
________
________

24
case Constantvalue-n: Block -n;
(or)
Statement-n;
break;

default: default – block; (or) Statement;


}

(i) The switch( ) Organization:


o The entire case structure following switch( ) should be enclosed with
pair of curly braces { }.
o In the block the variable or expression can be a character or an integer.
o Each case statement must contain different constant values.
o Any number of case statements can be provided.
o If the case structure contains multiple statements, they need not be
enclosed within pair of curly braces.

(ii) The switch( ) Execution:


o When one of the cases satisfies, the statements following it are
executed.
o In case there is no match, the default case is executed.

Flow Chart:

Write a program to provide multiple functions such as 1. Addition 2.Subtraction


3.Multiplication 4.Division 5.Remainder 6.Larger out of two 7. Exit using “switch”
statement.

# include<iostream>
using namespace std;
int main( )
{
int a, b, c, ch;
cout<<“\t = = = = = = = = = = = = = =”;
cout<<“\n\t MENU”;
cout<<“\n\t= = = = = = = = = = =”;

cout<<“\n \t [1] ADDITION” ;


cout<<“\n \t [2] SUBTRACTION” ;

25
cout<<“\n \t [3] MULTIPLICATION” ;
cout<<“\n \t [4] DIVISION” ;
cout<<“\n \t [5] REMAINDER” ;
cout<<“\n \t [6] LARGER OUT OF TWO” ;
cout<<“\n \t [7] EXIT” ;
cout<<“\n \t = = = = = = = = = =”;

cout<<(“ \n\n\t ENTER YOUR CHOICE:”);


cin>>ch;

if(ch< = 6 &&ch>=1)
{
cout<<(“ENTER TWO NUMBERS:”);
cin>>a>>b;
}

switch(ch)
{
case 1:
c = a+b ;
cout<<“ \n Addition: “<< c;
break;
case 2:
c=a-b;
cout<<“\n Subtraction:”<< c;
break;
case 3:
c = a* b ;
cout<<“\n Multiplication: “<< c;
break;
case 4:
c = a / b;
cout<<“\n Division: << c;
break;
case 5:
c = a % b;
cout<<“ \n Remainder: << c;
break;
case 6:
if (a > b)
cout<<“\n \t <<a <<”is larger than << b;
else if (b > a)
cout<<“ \n \t <<b<<” is larger than <<a;
else
cout<<“\n \t <<a<<”and “<<b<<”are same”;
break;
case 7:
cout<< “ \ n Terminated by choice”;
exit();
break;
default:
cout<<“ \ n invalid choice”;
}

26
return 0;
}

Output:
=========
MENU
=========
[1] ADDITION
[2] SUBTRACTION
[3] MULTIPLICATION
[4] DIVISION
[5] REMAINDER
[6] LARGER OUT OF TWO
[7] EXIT
===============
Enter your choice: 6
Enter two numbers: 8 9
9 is larger than 8

6. Conditional Operator [?:] : (or) Ternary Operator in C++

1. Conditional operators are also called as Ternary Operator.


2. They are represented by ?:
3. Ternary Operator takes on 3 Arguments.

Syntax of Ternary Operator:

Expression_1?Expression_2 : Expression_3

Where,
Expression_1 is Condition
Expression_2 is statement followed if Condition is True
Expression_3 is statement followed if Condition is False

Explanation of syntax:
1. Expression_1 is a condition so it will return the result either True or False.
2. If result of expression_1 is True that is NON-ZERO, then Expression_2 is
Executed.
3. If result of expression_1 is False that is ZERO, then Expression_3 is
Executed.

Let us take the simple example of finding greater number from two given numbers
using Conditional Operator.

#include<iostream>
using namespace std;
int main()
{
int num1=10;
int num2=20;

num1>num2 ?cout<< "num1 is greater than num2" : cout<< "num2 is greater


than num1" ;

27
return 0;
}

Output:
num2 is greater than num1

7. The “ goto” Statement:


 C++ supports the “goto‟ statement to branch unconditionally from one point to
another in the program.
 The goto requires a label in order to identify the place where the branch is to
be made.
 A label is any valid variable name and must be followed by a colon( : ).
 The label is placed immediately before the statement where the control is to
be transferred.
 The label can be anywhere in the program either before or after the goto label
statement.

 During running of a program, when a statement like “goto begin;” is met, the
flow of control will jump to the statement immediately following the label
“begin:” this happens unconditionally.
 “goto‟ breaks the normal sequential execution of the program.
 If the “label:” is before the statement “goto label;” a loop will be formed and
some statements will be executed repeatedly. Such a jump is known as a
“backward jump‟.
 If the “label:” is placed after the “goto label;” some statements will be skipped
and the jump is known as a “forward jump”.

* Write a program to detect the entered number as to whether it is even or odd. Use
goto statement.
# include<iostream>
using namespace std;

int main( )
{
int x;
cout<<“Enter a Number:”;
cin>>x;
if(x % 2 = = 0)
goto even;
else
goto odd;
28
even:
cout<<x<<” is Even Number”;
return;

odd:
cout<<x<<” is Odd Number”);
return 0;
}

Output:
Enter a Number : 5
5 is Odd Number.

Loop Control Statements:

Loop: A loop is defined as a block of statements which are repeatedly executed for
certain number of times.

1) The “for” loop:

The forloop statement comprises of 3 actions.


The 3 actions are
“initialize expression”, “Test Condition expression” and “updation
expression” ”

- The expressions are separated by Semi-Colons (;).


- The loop variable should be assigned with a starting and final value.
- Each time the updated value is checked by the loop itself. Increment /
Decrement is the numerical value added or subtracted to the variable in each
round of the loop.

Syntax:
for(initialize expression; test condition; updation )
{
Statement-1;
Statement-2;
}

(i) The initialization sets a loop to an initial value. This statement is executed only
once.

(ii) The test condition is a relational expression that determines the number of
iterations desired or it determines when to exit from the loop.
- The forloop continues to execute as long as conditional test is satisfied.
- When the condition becomes false the control of the program exits from the
body of for loop and executes next statements after the body of the loop.

(iii) The updation(increment or decrement operations) decides how to make


changes in the loop.

- The body of the loop may contain either a single statement or multiple
statements

29
#include <iostream>
using namespace std;
int main ()
{

for(int i = 0; i < 10; i = i + 1 ) // for loop execution


{
cout<< "value of i : " << i <<endl;
}
return 0;
}

Output:
value of i : 0
value of i : 1
value of i : 2
value of i : 3
value of i : 4
value of i : 5
value of i : 6
value of i : 7
value of i : 8
value of i : 9

(2) The “ while ” loop:

The simplest of all the looping structures in C++.

30
Syntax:

Initialization Expression;
while( Test Condition)
{
Body of the loop
Updation Expression
}
o The whileis an entry – controlled loop statement.
o The test condition is evaluated and if the condition is true, then the
body of the loop is executed.
o The execution process is repeated until the test condition becomes
false and the control is transferred out of the loop.
o On exit, the program continues with the statement immediately after
the body of the loop.
o The body of the loop may have one or more statements.
o The braces are needed only if the body contains two or more
statements.
Its a good practice to use braces even if the body has only one statement.

#include <iostream>
using namespace std;
int main ()
{
intnum = 5; // Local variable declaration
while(num< 10 ) // while loop execution
{
cout<< "Number : " <<num<<endl;
num++;
}
return 0;
}
Output:
Number : 5
Number : 6
Number : 7
Number : 8
Number : 9

(3) The “ do-while “ loop:


 In do-while, the condition is checked at the end of the loop.
 The do-while loop will execute at least one time even if the condition is false
initially.
31
 The do-while loop executes until the condition becomes false.

Syntax:
Initialization Expression;
do
{
Body of the loop
Updation Expression;
} while ( Test Condition);

#include <iostream>
using namespace std;
int main ()
{
int i = 0; // Local variable declaration:

do // do loop execution
{
cout<< "value of i : " << i <<endl;
i++;
}while( i < 10 );

return 0;
}

Output:
value of i : 0
value of i : 1
value of i : 2
value of i : 3
value of i : 4
value of i : 5
value of i : 6
value of i : 7
value of i : 8
value of i : 9

32
Difference between do..while and while loop :
do-while while

It is exit controlled loop It is entry controlled loop

The loop executes the loop executes the statement


statement at least once only after testing condition

The condition is tested The loop terminates if the


before execution. condition becomes false.

Unconditional Control Statements

(1) The “ break ” Statement:


 A break statement terminates the execution of the loop and the control is
transferred to the statement immediately following the loop.
 i.e., the break statement is used to terminate loops or to exit from a switch.
 It can be used within a for, while, do-while, or switch statement.
 The break statement is written simply as break;

Syntax:
break;

Example:
switch (choice = = toupper(getchar( ))
{
case ‘R : cout<<“Red”;
break;
case ‘W : cout<<”White”;
break;
case ‘B : cout<<”Blue”;
break;
default: cout<<”Error”;
}

 Notice that each group of statements ends with a break statement, (in order)
to transfer control out of the switch statement.
 The last group does not require a break statement; since control will
automatically be transferred out of the switch statement after the last group
has been executed.

(2) The “ continue “ Statement:


 The continue statement is used to bypass the remainder of the current pass
through a loop.
 The loop does not terminate when a continue statement is encountered.
 Instead, the remaining loop statements are skipped and the computation
proceeds directly to the next pass through the loop.
 The continue statement can be included within a while, a do-while, a for
statement.
 It is simply written as “continue”.
 The continue statement tells the compiler “Skip the following Statements and
continue with the next Iteration”.
33
 In “while‟ and “do‟ loops continue causes the control to go directly to the test
– condition and then to continue the iteration process.
 In the case of “for‟ loop, the updation section of the loop is executed before
test-condition, is evaluated.
while (Test condition)
{ do for(initialization; test increment)
-------- {
if ( - - - - - - -) { ----------
continue; if( - - - - - - -)
----------------- -------------------- continue;
--- -------------------- -----------------
} if ( - - - - - - ) -- -------------------
}
continue; -
------------------
-------------------
} while(test – condition);

Break and Continue: (Program) * Create an infinite for loop.


Check each value of the for loop. If the value is even, display it otherwise continue
the iterations. Print “Even” numbers from 1 to 21. Use break statement to terminate
the program.

# include<iostream>
using namespace std;
int main( )
{
int i = 1;
cout<<” \n \t \t Table of Even numbers from 1 to 20”;
cout<<“ \n \t \t = = = = = = = = = = = = = = = = = = = \n”;
for ( ; ; ) /*=> Infinite loop (No Arguments).*/
{
if( i = = 21)
break;
else
if( i % 2 = = 0)
{
cout<<”\t”<< i;
i++ ;
continue;
}
else
{
i++ ;
continue;
}
}
return 0;
}
Output:
Table of Even numbers from 1 to 20
2 4 6 8 10 12 14 16 18

Arrays:
34
Q) Define Array

An array is a collection of variables of the same type that are referred to througha
common name.
A specific element in an array is accessed by an index. InC++, all arrays consist of
contiguous memory locations. The lowest addresscorresponds to the first element
and the highest address to the last element.
Arrays may have from one to several dimensions. The most common array is
thenull-terminated string, which is simply an array of characters terminated by a null.

(or)
An array consists of a set of objects (called its elements), all of which are ofthe
same type and are arranged contiguously in memory.

In general, only the arrayitself has a symbolic name, not its elements. Each element
is identified by an indexwhich denotes the position of the element in the array. The
number of elements inan array is called its dimension. The dimension of an array is
fixed andpredetermined; it cannot be changed during program execution.

Arrays are suitable for representing composite data which consist of manysimilar,
individual items.

Examples include: a list of names, a table of world citiesand their current


temperatures, or the monthly transactions for a bank account.

Q) One dimensional array (or) single dimensional array initialization

An array variable is defined by specifying its dimension and the type of its elements.

For example, an array representing 10 height measurements (each being an


integerquantity) may be defined as:

int heights[10];

The individual elements of the array are accessed by indexing the array. The
firstarray element always has the index 0. Therefore, heights[0] and
heights[9]denote, respectively, the first and last element of heights. Each of
heightselements can be treated as an integer variable. So, for example, to set the
thirdelement to 177, we may write:

heights[2] = 177;

Attempting to access a nonexistent array element (e.g., heights[-1] orheights[10])


leads to a serious runtime error (called ‘index out of bounds’error).

Processing of an array usually involves a loop which goes through the arrayelement
by element. Example illustrates this using a function which takes anarray of integers
and returns the average of its elements.

const int size = 3;

35
double Average (intnums[size])
{
double average = 0;
for (register i = 0; i< size; ++i)
average += nums[i];
return average/size;
}

Like other variables, an array may have an initializer. Braces are used tospecify a list
of comma-separated initial values for array elements. For example,

int nums[3] = {5, 10, 15};

initializes the three elements of nums to 5, 10, and 15, respectively. When the
number of values in the initializer is less than the number of elements, the remaining
elements are initialized to zero:

int nums[3] = {5, 10}; // nums[2] initializes to 0

Q) Write about initialization of two dimensional array at the point of definition.


(or) What are multi dimensional arrays? Give an example.

An array may have more than one dimension (i.e., two, three, or higher). The
organization of the array in memory is still the same (a contiguous sequence of
elements), but the programmer’s perceived organization of the elements is different.

For example, suppose we wish to represent the average seasonal temperature for
three major Australian capital cities (see Example Table).
Example Table:

Average seasonal temperature.


Spring Summer Autumn Winter
Sydney 26 34 22 17
Melbourne 24 32 19 13
Brisbane 28 38 25 20

This may be represented by a two-dimensional array of integers:

int seasonTemp[3][4];

The organization of this array in memory is as 12 consecutive integer elements. The


programmer, however, can imagine it as three rows of four integer entries each (see
Figure).

As before, elements are accessed by indexing the array. A separate index isneeded
for each dimension. For example, Sydney’s average summer temperature(first row,
second column) is given by

36
seasonTemp[0][1].

The array may be initialized using a nested initializer:

int seasonTemp[3][4] = {
{26, 34, 22, 17},
{24, 32, 19, 13},
{28, 38, 25, 20}
};
Because this is mapped to a one-dimensional array of 12 elements in memory, it is
equivalent to:

int seasonTemp[3][4] = {
26, 34, 22, 17, 24, 32, 19, 13, 28, 38, 25, 20
};
The nested initializer is preferred because as well as being more informative, it is
more versatile.
For example, it makes it possible to initialize only the first element of each row and
have the rest default to zero:

int seasonTemp[3][4] = {{26}, {24}, {28}};

We can also omit the first dimension (but not subsequent dimensions) and let it be
derived from the initializer:

int seasonTemp[][4] = {
{26, 34, 22, 17},
{24, 32, 19, 13},
{28, 38, 25, 20}
};
Processing a multidimensional array is similar to a one-dimensional array, butuses
nested loops instead of a single loop. Example, illustrates this by showing afunction
for finding the highest temperature in seasonTemp.

const int rows = 3;


const int columns = 4;

int seasonTemp[rows][columns] = {
{26, 34, 22, 17},
{24, 32, 19, 13},
{28, 38, 25, 20}
};

int HighestTemp (int temp[rows][columns])


{
int highest = 0;
for (int i = 0; i< rows; ++i)
for (int j = 0; j < columns; ++j)
if (temp[i][j] > highest)
highest = temp[i][j];
return highest;
}

37
the same logic in the program form:
#include<iostream>
using namespace std;
int HighestTemp (int temp[][4], int rows, int columns)
{
int highest = 0;
for (inti = 0; i< rows; ++i)
for (int j = 0; j < columns; ++j)
if (temp[i][j] > highest)
highest = temp[i][j];
return highest;
}

int main()
{
const int rows = 3;
const int columns = 4;

int seasonTemp[rows][columns] = {
{26, 34, 22, 17},
{24, 32, 19, 13},
{28, 38, 25, 20}
};
HighestTemp (seasonTemp, rows, columns);
return 0;
}

C++ Program to Add two matrices


#include<iostream>
#include<process.h>
using namespace std;
int main()
{
int A[10][10],B[10][10],c[10][10];
int i,j,m,n,p,q;
cout<<"Enter no. of rows and cloumns of Matrix A:";
cin>>m>>n;
cout<<"\nEnter no. of rows and columns of Matrix B:";
cin>>p>>q;
if(m==p&&n==q)
cout<<"\nMatrices can be Added";
else
{
cout<<"\nMatricescan not Added";
exit(0);
}

cout<<"\nEnter matrix A row wise:";


for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
cin>>A[i][j];
}

38
cout<<"\nMatrix A:\n";
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
cout<<A[i][j]<<" ";
cout<<"\n";
}
cout<<"\nEnter Matrix B row wise:";
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
cin>>B[i][j];
}
cout<<"\n\nMatrix B:\n";
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
cout<<B[i][j]<<" ";
cout<<"\n";
}

for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
c[i][j]=A[i][j]+B[i][j];
}

cout<<"\nSum of Matrices A and B:\n";


for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
cout<<c[i][j]<<" ";
cout<<"\n";
}
return 0;
}

//C++ program to multiply two matrices


#include<iostream>
using namespace std;
int main()
{
int a[5][5],b[5][5],c[5][5],m,n,p,q,i,j,k;
cout<<"Enter rows and columns of first matrix:";
cin>>m>>n;
cout<<"Enter rows and columns of second matrix:";
cin>>p>>q;

if(n==p)
{
cout<<"\nEnter first matrix:\n";
for(i=0;i<m;++i)
for(j=0;j<n;++j)
cin>>a[i][j];

39
cout<<"\nEnter second matrix:\n";
for(i=0;i<p;++i)
for(j=0;j<q;++j)
cin>>b[i][j];

cout<<"\nThe new matrix is:\n";


for(i=0;i<m;++i)
{
for(j=0;j<q;++j)
{
c[i][j]=0;
for(k=0;k<n;++k)
c[i][j]=c[i][j]+(a[i][k]*b[k][j]);
cout<<c[i][j]<<" ";
}
cout<<"\n";
}
}
else
cout<<"\nSorry!!!! Matrix multiplication can't be done";
return 0;
}

//C++ program to Generate Transpose of a given 3x3 Matrix


#include<iostream>
using namespace std;
int main()
{
int mat[3][3], trans_mat[3][3], i, j;

/* reading mat */
for (i = 0; i< 3; i++)
{
for (j = 0; j < 3; j++)
{
cin>> mat[i][j];
}
}

/* Transposing elements of the matrix */

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


{
for (j = 0; j < 3; j++)
{
trans_mat[j][i] = mat[i][j];
}
}

cout<< "Transpose of the Given 3x3 Matrix : " <<endl;

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


{

40
for (j = 0; j < 3; j++)
{
cout<<trans_mat[i][j] << "\t";
}
cout<<endl;
}
return 0;
}

Strings:

Null-Terminated Strings

By far the most common use of the one-dimensional array is as a character string.
C++ supports two types of strings. The first is the null-terminated string, which is a
null-terminated character array. (A null is zero.)
Thus a null-terminated string contains the characters that comprise the string
followed by a null.

When declaring a character array that will hold a null-terminated string, you need to
declare it to be one character longer than the largest string that it is to hold. For
example, to declare an array strthat can hold a 10-character string, you would write

charstr[11];

This makes room for the null at the end of the string.

When you use a quoted string constant in your program, you are also creating anull-
terminated string. A string constant is a list of characters enclosed in double
quotes.For example,

"hello there"

You do not need to add the null to the end of string constants manually—the
compilerdoes this for you automatically.

#include <iostream>
using namespace std;
int main()
{
char MyName[20];
cout<< "Please enter your name" <<endl;
cin.getline(MyName,20);
cout<< "your name is " <<MyName<<endl;
return 0;
}

#include<iostream>
using namespace std;
int main()
{
char str[3][20] = {
"I",
"like",

41
"C++" };
for(int i=0;i<3; i++)
{
cout<<str[i];
cout<<endl;
}
return 0;
}

Q) State and explain any five built-in functions which are used for string
manipulation in a program.

C/C++ supports a wide range of functions that manipulate null-terminated strings.


The most common are

Name Function
strcpy(s1, s2) Copies s2 into s1.
strcat(s1, s2) Concatenates s2 onto the end of s1.
strlen(s1) Returns the length of s1.
strcmp(s1, s2) Returns 0 if s1 and s2 are the same; less than 0 if s1<s2;greater
than 0 if s1>s2.
strchr(s1, ch) Returns a pointer to the first occurrence of chin s1.
strstr(s1, s2) Returns a pointer to the first occurrence of s2 in s1.

These functions use the standard header file string.h. The following program
illustrates the use of these stringfunctions:

#include<iostream>
#include<string>
using namespace std;

const int LEN =15;

int main()
{
int i, n;
char person[10][LEN];
cout<<"How many persons ? ";
cin>>n;
for(i=0; i<n; i++)
{
cout<<"Enter person"<<i+1<<" name: ";
cin>> person[i];
}

cout<< " ________________________________________\n";


cout<<" P# Person Name Length In lower case In UPPER case \n";

cout<< " ________________________________________\n";


for (i=0; i<n; i++)
{
cout.width(2);
cout<<i+1;
cout.width(LEN);

42
cout<<person[i]<<" ";
cout.width(2);
cout<<strlen(person[i])<<" ";
cout.width(LEN);
cout<<strlwr(person[i]);
cout.width(LEN);
cout<<strupr(person[i])<<endl;
}
cout<<"----------------------------------------------\n";
return 0;
}

POINTERS

A pointer is a variable which holds the memory address of another variable.

Pointer operator
A pointer operator can be represented by a combination of *(asterisk) with a variable.

For eg.
int *ptr;
float *fp;

The general format of pointer declaration is…

data_type *pointer_variable;

Address operator
An address operator can be represented by a combination of & (ambersand) with a
pointer variable.

For eg.

k = &ptr;

Pointer Expressions

Pointer assignment : A pointer is a variable data type and hence the general rule to
assign its value to the pointer is same as that of any other variable data type.

Eg.
int x,y;
int *ptr1, *ptr2;
ptr1 = &x;
The memory address of variable x is assigned to the pointer variable ptr1.

y = *ptr1;

The contents of the pointer variable ptr1 is assigned to the variable y, not the
memory address.

ptr1 = &x;
ptr2 = ptr1;

43
The address of the ptr1 is assigned to the pointer variable ptr2. The contents of both
prt1 and ptr2 will be the same as these two pointer variables hold the same address.

A program to assign a character variable to the pointer and to display the contents of
the pointer.

#include <iostream>
using namespace std;

int main()
{
char x,y;
char *pt;
x = ‘k’; // assign character
pt = &x;
y = *pt;
cout<< “Value of x = “ << x <<endl;
cout<< “Pointer value = “ << y <<endl;
}

Functions:
Functions allow to structure programs in segments of code to perform individual
tasks.

In C++, a function is a group of statements that is given a name, and which can be
called from some point of the program. The most common syntax to define a function
is:

type function-name ( parameter1, parameter2, ...)


{
statements
}

Where:
- type is the type of the value returned by the function.
- function-name is the identifier by which the function can be called.
- parameters (as many as needed): Each parameter consists of a type followed by
an identifier, with each parameter being separated from the next by a comma. Each
parameter looks very much like a regular variable declaration (for example: int x),
and in fact acts within the function as a regular variable which is local to the function.
The purpose of parameters is to allow passing arguments to the function from the
location where it is called from.
- statements is the function's body. It is a block of statements surrounded by braces
{ } that specify what the function actually does.

Let's have a look at an example:


#include <iostream>
using namespace std;

int addition (int a, int b)


{
int r;
r=a+b;
return r;
}

44
int main ()
{
int z;
z = addition (5,3);
cout<<"The result is "<< z;
return 0;
}
Output:
The result is 8

This program is divided in two functions: addition and main.


Remember that no matter the order in which they are defined, a C++ program
always starts by calling main. In fact, main is the only function called automatically,
and the code in any other function is only executed if its function is called
from main (directly or indirectly).

In the example above, main begins by declaring the variable z of type int, and right
after that, it performs the first function call: it calls addition. The call to a function
follows a structure very similar to its declaration. In the example above, the call
to addition can be compared to its definition just a few lines earlier:

The parameters in the function declaration have a clear correspondence to the


arguments passed in the function call. The call passes two values, 5 and 3, to the
function; these correspond to the parameters a and b, declared for function addition.

At the point at which the function is called from within main, the control is passed to
function addition: here, execution of main is stopped, and will only resume once
the addition function ends. At the moment of the function call, the value of both
arguments (5 and 3) are copied to the local variables inta and int b within the
function.

Then, inside addition, another local variable is declared (int r), and by means of the
expression r=a+b, the result of aplus b is assigned to r; which, for this case,
where a is 5 and b is 3, means that 8 is assigned to r.

The final statement within the function:


return r;

Ends function addition, and returns the control back to the point where the function
was called; in this case: to function main. At this precise moment, the program
resumes its course on main returning exactly at the same point at which it was
interrupted by the call to addition. But additionally, because addition has a return
type, the call is evaluated as having a value, and this value is the value specified in
the return statement that ended addition: in this particular case, the value of the local
variable r, which at the moment of the return statement had a value of 8.

Therefore, the call to addition is an expression with the value returned by the

45
function, and in this case, that value, 8, is assigned to z. It is as if the entire function
call (addition(5,3)) was replaced by the value it returns (i.e., 8).

Then main simply prints this value by calling:


cout<< "The result is " << z;

Call by value and Call by reference:


In the functions seen earlier, arguments have always been passed by value. This
means that, when calling a function, what is passed to the function are the values of
these arguments on the moment of the call, which are copied into the variables
represented by the function parameters. For example, take:

1 int x=5, y=3, z;


2 z = addition ( x, y );

In this case, function addition is passed 5 and 3, which are copies of the values
of x and y, respectively. These values (5 and 3) are used to initialize the variables
set as parameters in the function's definition, but any modification of these variables
within the function has no effect on the values of the variables x and y outside it,
because x and y were themselves not passed to the function on the call, but only
copies of their values at that moment.

In certain cases, though, it may be useful to access an external variable from within
a function. To do that, arguments can be passed by reference, instead of by value.
For example, the function duplicate in this code duplicates the value of its three
arguments, causing the variables used as arguments to actually be modified by the
call:

// passing parameters by reference


#include <iostream>
using namespace std;

void duplicate (int& a, int& b, int& c)


{
a*=2;
b*=2;
c*=2;
}

int main ()
{
int x=1, y=3, z=7;
duplicate (x, y, z);
cout<< "x=" << x << ", y=" << y << ", z=" << z;
return 0;
}
Output:
x=2, y=6, z=14

46
To gain access to its arguments, the function declares its parameters as references.
In C++, references are indicated with an ampersand (&) following the parameter
type, as in the parameters taken by duplicate in the example above.

When a variable is passed by reference, what is passed is no longer a copy, but the
variable itself, the variable identified by the function parameter, becomes somehow
associated with the argument passed to the function, and any modification on their
corresponding local variables within the function are reflected in the variables passed
as arguments in the call.

In fact, a, b, and c become aliases of the arguments passed on the function call (x, y,
and z) and any change on a within the function is actually modifying
variable x outside the function. Any change on b modifies y, and any change
on cmodifies z. That is why when, in the example, function duplicate modifies the
values of variables a, b, and c, the values of x, y, and z are affected.

If instead of defining duplicate as:

void duplicate (int& a, int& b, int& c)

Was it to be defined without the ampersand signs as:

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

The variables would not be passed by reference, but by value, creating instead
copies of their values. In this case, the output of the program would have been the
values of x, y, and z without being modified (i.e., 1, 3, and 7).

Inline functions:
Calling a function generally causes a certain overhead (stacking arguments, jumps,
etc...), and thus for very short functions, it may be more efficient to simply insert the
code of the function where it is called, instead of performing the process of formally
calling a function.

Preceding a function declaration with the inline specifier informs the compiler
that inline expansion is preferred over the usual function call mechanism for a
specific function. This does not change at all the behavior of a function, but is just
used to suggest the compiler that the code generated by the function body shall be
inserted at each point the function is called, instead of being invoked with a regular
function call.

For example, the add() function may be declared inline as:

1 inline int add (int & a, int & b)


2{
3 return a+b;
4}

47
#include <iostream>
using namespace std;

inline int add (int & a, int & b)


{
return a+b;
}
int main ()
{
cout<< add(12,13) << '\n';
cout<< add(20,4) << '\n';
return 0;
}
Output:
25
24

This informs the compiler that when add() is called, the program prefers the function
to be expanded inline, instead of performing a regular call. inline is only specified in
the function declaration, not when it is called.

Note that most compilers already optimize code to generate inline functions when
they see an opportunity to improve efficiency, even if not explicitly marked with
the inline specifier. Therefore, this specifier merely indicates the compiler that inline
is preferred for this function, although the compiler is free to not inline it, and
optimize otherwise.

Default Arguments / Default values in parameters:


In C++, functions can also have optional parameters, for which no arguments are
required in the call, in such a way that, for example, a function with three parameters
may be called with only two. For this, the function shall include a default value for its
last parameter, which is used by the function when called with fewer arguments. For
example:

// default values in functions


#include <iostream>
using namespace std;

int divide (int a, int b=2)


{
int r;
r=a/b;
return (r);
}

int main ()
{
cout<< divide (12) << '\n';
cout<< divide (20,4) << '\n';
return 0;
}
Output:
6
5

48
In this example, there are two calls to function divide(). In the first one:

divide (12)
The call only passes one argument to the function, even though the function has two
parameters. In this case, the function assumes the second parameter to be 2 (notice
the function definition, which declares its second parameter as int b=2). Therefore,
the result is 6.

In the second call:

divide (20,4)

The call passes two arguments to the function. Therefore, the default value for b (int
b=2) is ignored, and b takes the value passed as argument, that is 4, yielding a result
of 5.

Function Prototype (Declaring function):


In C++, identifiers can only be used in expressions once they have been declared.
For example, some variable x cannot be used before being declared with a
statement, such as:

int x;
The same applies to functions. Functions cannot be called before they are declared.
That is why, in all the previous examples of functions, the functions were always
defined before the main function, which is the function from where the other
functions were called. If main were defined before the other functions, this would
break the rule that functions shall be declared before being used, and thus would not
compile.

The prototype of a function can be declared without actually defining the


function completely, giving just enough details to allow the types involved in a
function call to be known. Naturally, the function shall be defined somewhere
else, like later in the code. But at least, once declared like this, it can already
be called.
The declaration shall include all types involved (the return type and the type of its
arguments), using the same syntax as used in the definition of the function, but
replacing the body of the function (the block of statements) with an ending
semicolon.

The parameter list does not need to include the parameter names, but only their
types. Parameter names can nevertheless be specified, but they are optional, and do
not need to necessarily match those in the function definition. For example, a
function called protofunction with two int parameters can be declared with either of
these statements:

1 int protofunction (int first, int second);


2 int protofunction (int, int);

Anyway, including a name for each parameter always improves legibility of the
declaration.

// declaring functions prototypes


49
#include <iostream>
using namespace std;

void odd (int x);


void even (int x);

int main()
{
int i;
do {
cout<< "Please, enter number (0 to exit): ";
cin>> i;
odd (i);
} while (i!=0);
return 0;
}

void odd (int x)


{
if ((x%2)!=0)
cout<< "It is odd.\n";
else
even (x);
}

void even (int x)


{
if ((x%2)==0)
cout<< "It is even.\n";
else
odd (x);
}
Output:
Please, enter number (0 to exit): 9
It is odd.
Please, enter number (0 to exit): 6
It is even.
Please, enter number (0 to exit): 1030
It is even.
Please, enter number (0 to exit): 0
It is even.

This example is indeed not an example of efficiency. You can probably write yourself
a version of this program with half the lines of code. Anyway, this example illustrates
how functions can be declared before its definition:

The following lines:

void odd (int a);


void even (int a);

Declare the prototype of the functions. They already contain all what is necessary to
call them, their name, the types of their argument, and their return type (void in this
case). With these prototype declarations in place, they can be called before they are

50
entirely defined, allowing for example, to place the function from where they are
called (main) before the actual definition of these functions.

But declaring functions before being defined is not only useful to reorganize the
order of functions within the code. In some cases, such as in this particular case, at
least one of the declarations is required, because odd and even are mutually called;
there is a call to even in odd and a call to odd in even. And, therefore, there is no
way to structure the code so that odd is defined before even, and even before odd.

Functions Recursivity / Recursive Functions:


Recursivity is the property that functions have to be called by themselves. It is useful
for some tasks, such as sorting elements, or calculating the factorial of numbers. For
example, in order to obtain the factorial of a number (n!) the mathematical formula
would be:

n! = n * (n-1) * (n-2) * (n-3) ... * 1


More concretely, 5! (factorial of 5) would be:

5! = 5 * 4 * 3 * 2 * 1 = 120
And a recursive function to calculate this in C++ could be:

// factorial calculator
#include <iostream>
using namespace std;

long factorial (long a)


{
if (a > 1)
return (a * factorial (a-1));
else
return 1;
}

int main ()
{
long number = 9;
cout<< number << "! = " << factorial (number);
return 0;
}
Output:
9! = 362880

Notice how in function factorial we included a call to itself, but only if the argument
passed was greater than 1, since, otherwise, the function would perform an infinite
recursive loop, in which once it arrived to 0, it would continue multiplying by all the
negative numbers (probably provoking a stack overflow at some point during
runtime).

Overloaded functions:
In C++, two different functions can have the same name if their parameters are
different; either because they have a different number of parameters, or because any
of their parameters are of a different type. For example:

51
// overloading functions
#include <iostream>
using namespace std;

int operate (int a, int b)


{
return (a*b);
}

double operate (double a, double b)


{
return (a/b);
}

int main ()
{
int x=5,y=2;
double n=5.0,m=2.0;
cout<< operate (x,y) << '\n';
cout<< operate (n,m) << '\n';
return 0;
}
Output:
10
2.5

In this example, there are two functions called operate, but one of them has two
parameters of type int, while the other has them of type double. The compiler knows
which one to call in each case by examining the types passed as arguments when
the function is called. If it is called with two int arguments, it calls to the function that
has two int parameters, and if it is called with two doubles, it calls the one with
two doubles.
In this example, both functions have quite different behaviors, the int version
multiplies its arguments, while the double version divides them. This is generally not
a good idea. Two functions with the same name are generally expected to have -at
least- a similar behavior, but this example demonstrates that is entirely possible for
them not to. Two overloaded functions (i.e., two functions with the same name) have
entirely different definitions; they are, for all purposes, different functions, that only
happen to have the same name.

Note that a function cannot be overloaded only by its return type. At least one of its
parameters must have a different type.

Passing Arrays to Functions:

Arrays can be passed to a function as an argument. Consider this example to pass


one-dimensional array to a function:

Example 1: Passing One-dimensional Array to a Function


C++ Program to display marks of 5 students by passing one-dimensional array
to a function.
#include <iostream>
using namespace std;

52
void display(int marks[5]);

int main()
{
int marks[5] = {88, 76, 90, 61, 69};
display(marks);
return 0;
}

void display(int m[5])


{
cout<< "Displaying marks: "<<endl;
for (int i = 0; i < 5; ++i)
{
cout<< "Student "<< i + 1 <<": "<< m[i] <<endl;
}
}

Output:
Displaying marks:
Student 1: 88
Student 2: 76
Student 3: 90
Student 4: 61
Student 5: 69

When an array is passed as an argument to a function, only the name of an array is


used as argument.

display(marks);

Also notice the difference while passing array as an argument rather than a variable.

void display(int m[5]);

The argument marks in the above code represents the memory address of first
element of array marks[5].

And the formal argument intm[5] in function declaration converts to int* m;. This
pointer points to the same address pointed by the array marks.That's the reason,
although the function is manipulated in the user-defined function with different array
name m[5], the original array marks is manipulated.

Multidimensional array can be passed in similar way as one-dimensional array.


Consider this example to pass two dimensional array to a function:

Example 2: Passing Multidimensional Array to a Function


C++ Program to display the elements of two dimensional array by passing it to
a function.
#include <iostream>
using namespace std;

53
void display(int n[3][2]);

int main()
{
int num[3][2] = {
{3, 4},
{9, 5},
{7, 1}
};
display(num);
return 0;
}

void display(int n[3][2])


{
cout<< "Displaying Values: " <<endl;
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 2; ++j)
{
cout<< n[i][j] << " ";
}
}
}
Output
Displaying Values:
349571

In the above program, the multi-dimensional array num is passed to the


function display().
Inside, display() function, the array n (num) is traversed using a nested for loop.
The program uses 2 for loops to iterate over the elements inside a 2-dimensional
array. If it were a 3-dimensional array, you should use 3 for loops.
Finally, all elements are printed onto the screen.

Object Oriented Programming:


Q) Explain procedure oriented programming and object oriented programming.
Compare them.
:For this question explain briefly POOP and OOP.
Q) Write about procedural oriented programming and mention their demerits.

Procedure-Oriented Programming:
Conventional programming, using high level languages such as COBOL,
FORTRAN and C, is commonly known as procedure-oriented programming (POP).
In the procedure oriented approach, the problem is viewed as a sequence of things to
be done such as reading, calculating and printing. A number of functions are written to
accomplish these tasks. The primary focus is on functions. A typical program structure
for procedural programming is shown in Pig. 1.4. The technique of
hierarchical decomposition has been used to specify the tasks to be completed for
solving a problem.

54
Procedure-oriented programming basically consists of writing a list of instructions (or
actions) for the computer to follow, and organizing these instructions into groups
known as functions. We normally use a flowchart to organize these actions and
represent the flow of control from one action to another.

While we concentrate on the development of functions, very little attention is given to


the data that are being used by various functions. What happens to the data? How
are they affected by the functions that work on them?

many important data items are placed as global so that In a multi-function program,
they may be accessed by all the functions. Each function may have its own local
data. Figure 1.5 shows the relationship of data and functions in a procedure-oriented
program.

Global data are more vulnerable to an inadvertent change by a function. In a large


program it is very difficult to identify what data is used by which function. In case we
need to revise an external data structure, we also need to revise all functions that
access the data. This provides an opportunity for bugs to creep in.

Another serious drawback with the procedural approach is that it does not model real
world problems very well. This is because functions are action-oriented and do not
really correspond to the elements of the problem.

55
Some characteristics exhibited by procedure-oriented programming are:

• Emphasis is on doing things (algorithms).


• Larger programs are divided into smaller programs known as functions.
• Data move openly around the system from function to function
• Functions transform data from one form to another.
• Employs lop-down approach in program design.

Object-Oriented Programming Paradigm

The major motivating factor in the invention of object-oriented approach is to remove


some of the flaws encountered in the procedural approach.

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 functions that
operate on it, and protects it from accidental modification from outside functions.

OOP allows decomposition of a problem into a number of entities called objects and
then builds data and functions around these objects. The organization of data and
functions in object-oriented programs is shown in Fig. 1.6.

The data of an object can be accessed only by the functions associated with that
object. However, functions of one object can access the functions of other objects.

Some of the striking features of object-oriented programming are:

• 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.
• Follows bottom-up approach in program design.

56
Object-oriented programming is the most recent concept among programming
paradigms and still means different things to different people.

It is therefore important to have a working definition of object-oriented programming


before we proceed further.

We define "object oriented programming as 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."

Thus, an object is considered to be a partitioned area of computer memory that


stores data and set of operations that can access that data. Since the memory
partitions are independent, the objects can be used in a variety of different programs
without modifications.

(or) we can take this answer for


Q) Explain about object oriented programming.

Object-oriented programming took the best ideas of structured programming and


combined them with several new concepts. The result was a different way of
organizing a program.

In the most general sense, a program can be organized in one of two ways: around
its code (what is happening) or around its data (who is being affected).

Using only structured programming techniques, programs are typically organized


around code. This approach can be thought of as "code acting on data." For
example, a program written in a structured language such as C is defined by its
functions, any of which may operate on any type of data used by the program.

Object-oriented programs work the other way around. They are organized around
data, with the key principle being "data controlling access to code." In an object-
oriented language, you define the data and the routines(functions) that are permitted
to act on that data. Thus, a data type defines precisely what sort of operations can
be applied to that data.

To support the principles of object-oriented programming, all OOP languages have


three traits(characters) in common: encapsulation, polymorphism, and inheritance.

Q) State the features of object oriented program (or) Write about the basic
concepts of object oriented programming in detail.
Before starting to learn C++ it is essential that one must have a basic knowledge of
the concepts of Object Oriented Programming.

Some of the important object oriented features are namely:

1. Objects
2. Classes
3. Data Abstraction and Data Encapsulation
4. Inheritance
5. Polymorphism
6. Dynamic Binding
7. Message Passing.

57
1. 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 problem is
analysed in terms of objects and the nature of communication between them.

Program objects should be chosen such that they match closely with the real-world
objects. Objects take up space in the memory and have an associated address like a
record in Pascal, or a structure in C.

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. Although different authors represent them differently, Fig. 1.7 shows
two notations that are popularly used in object oriented analysis and design.

(or) you can write about object as:

Object is the basic unit of object-oriented programming. Objects are identified by its
unique name. An object represents a particular instance of a class. There can be
more than one instance of an object. Each instance of an object can hold its own
relevant data.

58
An Object is a collection of data members and associated member functions also
known as methods.

2. Classes

We just mentioned that objects contain data, and code to manipulate that data. The entire
set of data and code of an object can be made a user-defined data type with the help of a
class. In fact, objects are variables of the type 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 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.

The syntax used to create an object is no different than the syntax used to create an integer
object in C. If fruit has been defined as a class, then the statement

fruit mango;

will create an object mango belonging to the class fruit.

3. Data Abstraction and Encapsulation

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.

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.

59
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 (ADD).

Inheritance
Inheritance is the process by which objects of one class acquire the properties of objects
of another class.
It supports the concept of hierarchical classification. For example, the bird 'robin' is a part
of the class flying bird' which is again a part of the class bird'.

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 in Fig. 1.8.

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 features of both the classes.
The real appeal and power of the inheritance mechanism is that it allows the
programmer to reuse a class that is almost, but not exactly, what he wants, and to tailor the
class in such a way that it does not introduce any undesirable side-effects into the rest of the
classes.

Polymorphism :
Polymorphism is another important OOP concept. Polymorphism, a Greek term, means the
ability to take more than one form. An operation may exhibit different behaviours in different
instances. The behaviour 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 behaviours in
different instances is known as operator overloading.

Figure 1.9 illustrates that a single function name can be used to handle different number and
different types of arguments.

60
This is something similar to a particular word having several different meanings depending
on the context- Using a single function name to perform different types of tasks is known
as function overloading.

Polymorphism plays an important role in allowing objects having different internal structures
to share the same external interface. This means that a general class of operations

Dynamic Binding:

Binding refers to the linking of a procedure call to the code to be executed in response to the
call. Dynamic binding (also known as late 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 Pig. 1.9. 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, therefore, involves the


following basic steps:

1. Creating classes that define objects and their behaviour,


2. Creating objects from class definitions, and
3. Establishing communication among objects.

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.

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

Objects have a life cycle. They can be created and destroyed.Communication with an object
is feasible as long as it is alive.

Applications and Benefits of using OOP


Applications of using OOP:
Main application areas of OOP are
User interface design such as windows, menu ,…
Real Time Systems
Simulation and Modeling
Object oriented databases
AI and Expert System
Neural Networks and parallel programming
Decision support and office automation system etc.

Benefits of OOP
The main advantages are
 It is easy to model a real system as real objects are represented by programming
objects in OOP. The objects are processed by their member data and functions. It is
easy to analyze the user requirements.
 With the help of inheritance, we can reuse the existing class to derive a new class
such that the redundant code is eliminated and the use of existing class is extended.
This saves time and cost of program.
 In OOP, data can be made private to a class such that only member functions of the
class can access the data. This principle of data hiding helps the programmer to build
a secure program that can not be invaded by code in other part of the program.
 With the help of polymorphism, the same function or same operator can be used for
different purposes. This helps to manage software complexity easily.
 Large problems can be reduced to smaller and more manageable problems. It is
easy to partition the work in a project based on objects.
 It is possible to have multiple instances of an object to co-exist without any
interference i.e. each object has its own separate member data and function

62

You might also like