0% found this document useful (0 votes)
22 views200 pages

Chapter 3 BCPEdited

Uploaded by

Dej Ayn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views200 pages

Chapter 3 BCPEdited

Uploaded by

Dej Ayn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 200

Basics of C++ Programming

Languages
C++, an extension of C, was
developed by Bjarne Stroustrup in
the early 1980s at Bell
Laboratories.
C++ provides a number of features
that “spruce up” the C language,
but more importantly, it provides
capabilities for object-oriented
programming.
C++ systems generally consist of
1
• Program development environment,
The development environment is the set of
processes and programming tools used to
create the program or software product.
An integrated development
environment (IDE) is one in which the
processes and tools are coordinated to
provide an orderly interface and convenient
view of the development processes (writing
code, testing it, and packaging it for use).
The C++ Standard Library can be categorized
into two parts
The Standard Function Library − This
library consists of general-purpose, stand-
2
alone functions that are not part of any
Phases of C++ Programs
Program is created in
Editor Disk the editor and stored
on disk.
Six phases of C++ Programs: Preprocessor Preprocessor program
Disk
processes the code.
1. Edit Compiler creates
Compiler Disk object code and stores
2. Preprocess it on disk.
Linker links the object
3. Compile Linker Disk code with the libraries,
creates an executable
4. Link Primary file and stores it on disk
Memory
Loader
5. Load
Loader puts program
6. Execute in memory.
Disk ..
..
..

Primary
Memory
CPU
CPU takes each
instruction and
executes it, possibly
storing new data
..
.. values as the program
..
executes.
3
Phase 1 Creating a Program (Editing): consists of
editing a file with an editor.
We type a C++ program (source code) using the editor,
make any necessary corrections and save the program on
a secondary storage device.
C++ source code filenames end with the .cpp, or .cxx, .cc
which indicate that a file contains C++ source code.
Phase 2: Preprocessing
You give the command to compile the program.
In a C++ system, a preprocessor program executes
automatically before the compiler’s translation phase
begins .
The C++ preprocessor obeys commands called
preprocessor directives, which indicate that certain
manipulations are to be performed on the program before
compilation.
These manipulations usually include other text files to be
compiled, and perform various text replacements.
In a C++ system, a preprocessor program
executes automatically before the compiler's
translation phase begins (so we call
preprocessing phase 2 and compiling phase 3).
The C++ preprocessor obeys commands
called preprocessor directives, which
indicate that certain manipulations are to be
performed on the program before compilation.
These manipulations usually include other text
files to be compiled and perform various text
replacements.
Phase 3: Compilation:
The compiler translates the C++ program into
machine-language code (object code).
Phase 4: Linking: Linker links the object
code with the libraries, creates an executable
file and stores it on disk.
Phase 5: Loading: Before a program can be
executed, it must first be placed in memory.
This is done by the loader, which takes the
executable file from disk and transfers it to
memory.
Additional components from shared libraries
that support the program are also loaded.
Phase 6: Execution: Finally, the computer,
under the control of its CPU, executes the
program one instruction at a time or in
parallel.
First Program in C++
C++ uses notations that may appear
strange to nonprogrammers.
This program illustrates several
important features of the C++
language.
1 // Text-printing program.
2 #include <iostream> // allows program to output data to the screen
3 using namespace std;
4
5 int main() // function main begins program execution
6 {
7 std::cout << “Hello World!\n"; // display message
8 return 0; // indicate that program ended successfully
9 } // end function main
Output
Hello World!
Comments
Line 1 begin with // indicating that the
line is a comment.
Insert comments to document your
programs and to help other people read
and understand them.
Comments are ignored by the C++
compiler and do not cause any machine-
language object code to be generated.
A comment beginning with // is called a
single-line comment.
You also may containing many lines—
begins with /* and ends with */.
#include Preprocessor Directive
• Line 2 is a preprocessor directive, which is a
message to the C++ preprocessor.
• Lines that begin with # are processed by the
preprocessor before the program is compiled.
• This line notifies the preprocessor to include
in the program the contents of the
input/output stream header <iostream>.
• iostream: stands for standard input-output
stream. This header file contains definitions
of objects like cin, cout, cerr, etc.
• This header must be included for any
program that outputs data to the screen or
inputs data from the keyboard using C++’s
stream input/output.
using namespace std;
The line using namespace std; tells
the compiler to use the std
namespace.
Namespaces are a relatively recent
addition to C++.
A namespace is a declarative region
that provides a scope to the identifiers
(the names of types, functions,
variables, etc) inside it.
Namespaces are used to organize
code into logical groups and to prevent
name collisions that can occur
Blank Lines and White Space
Line 4 is simply a blank line.
You use blank lines, space
characters and tab characters (i.e.,
“tabs”) to make programs easier
to read.
Together, these characters are
known as white space.
White-space characters are
normally ignored by the compiler.
main() function: is the entry point of any C+
+ program.
It is the point at which execution of program is
started. When a C++ program is executed, the
execution control goes directly to the main()
function. Every C++ program have a main()
function.
The void main() indicates that the main()
function will not return any value, but the int
main() indicates that the main() can return
integer type data.
When our program is simple, and it is not
going to terminate before reaching the last line
of the code, or the code is error free, then we
can use the void main().
The keyword int to the left of main
indicates that main “returns” an
integer (whole number) value.
A keyword is a word in code that is
reserved by C++ for a specific use.
The left brace, {, must begin the
body of every function.
A corresponding right brace, },
must end each function’s body.
cout<<
It is used to produce output on the standard
output device which is usually the display
screen.
The data needed to be displayed on the
screen is inserted in the standard output
stream (cout) using the insertion
operator(<<).
The right operand’s characters normally
print exactly as they appear between the
double quotes.
cin>>
Usually the input device in a computer is the
keyboard.

The characters \n are not printed on the
screen.
The backslash (\) is called an escape
character.
It indicates that a “special” character is
to be output.
When a backslash is encountered in a
string of characters, the next character is
combined with the backslash to form an
escape sequence.
The escape sequence \n means newline.
It causes the cursor to move to the
beginning of the next line on the screen.
Escape Sequence Description
\n Newline. Position the screen cursor
to the beginning of
the next line.
\t Horizontal tab. Move the screen cursor to
the next tab stop.
\r Carriage return. Position the screen cursor
to the beginning of
the current line;
not advance to the next line.
\' Single quote. Use to print a single
quote character.
\"Double quote. Used to print a double
quote character.
Return Statement
Terminates the execution of a function
and returns control to the calling
function (or to the operating system if
you transfer control from
the main function).

17
Example 2:
/*write a c++ program that accept two numbers from the keyboard
and find the sum of the two number and display the result */.
#include<iostream>
Using namespace std;
int main( )
{
float x, y, sum ;
cout<< “Enter the value for x :”;
cin>>x;
cout<< “Enter the value for y :”;
cin>>y
sum=x+y;
cout<< “The sum of the two numbers is : “<<sum;
}
Give the input 34 for x and 56 for y.
18
Expected Output
Primitive Data types
In most all programming languages provide a
set of primitive data types.
When you define a variable in C++, you must
tell the compiler what kind of variable it is: an
integer, a character, or so forth.
This information tells the compiler how much
room to set aside and what kind of value you
want to store in your variable.
The memory in our computers is organized in
bytes.
A byte is the minimum amount of memory that
we can manage in C++.
19Next you have a summary of the basic
NAME DESCRIPTION SIZE RANGE
CHAR character or small integer 1 Byte signed -128 to 127
unsigned 0 to 255
Short int Short Integer 2 bytes signed -32768 to 32768
unsigned 0 to 65535
Int integer 4 bytes signed -2147483648 to
2147483647
unsigned 0 to 4294967295
Long int long integer 4 bytes signed -2147483648 to
2147483647
unsigned 0 to 4294967295
Bool Boolean value. It can 1 byte true and false
take one values
true or false.
Float floating point number 4 bytes +/- 3.4e +/-38(~7 digits)
Double Double precision 8 bytes +/- 1.7e +/-308(~15 digits)
floating point number
Long double Long double precision 8 bytes +/- 1.7e +/-308(~7 digits)
floating point number
Wchar_t wide character. 2 or 4 bytes 1 wide character
Declaration of variables
 C++ is a strongly-typed language, and requires every
variable to be declared with its type before its first
use.
 This informs the compiler the size to reserve in
memory for the variable and how to interpret its
value.
 The syntax to declare a new variable in C++ is
straightforward: we simply write the type followed by
the variable name (i.e., its identifier).
 For example:
int a;
float mynumber;
 These are two valid declarations of variables.
 If declaring more than one variable of the same type,
21
they can all be declared in a single statement by
Declare variables with name and data type
before use
int integer1;
int integer2;
int sum;
Can declare several variables of same type
in one declaration
Comma-separated list
int integer1, integer2, sum;
Declaration of variables

23
Identifiers
Each variable needs a name that identifies it and
distinguishes it from the others.
A valid identifier is a sequence of one or more
letters, digits, or underscore characters (_).
Spaces, punctuation marks, and symbols cannot
be part of an identifier.
In addition, identifiers shall always begin with a
letter.
They can also begin with an underline character
(_)
The C++ language is a "case sensitive"
language.
That means that an identifier written in capital
24 letters is not equivalent to another one with the
Memory Concepts
Variable names
Correspond to actual locations in computer's
memory
Every variable has name, type, size and value
When new value placed into variable, overwrites
previous value

std::cin >> integer1; integer1 45

Assume user entered 45


integer1 45
integer2 72
std::cin >> integer2;
Assume user entered 72
integer1 45
integer2 72
sum = integer1 + integer2;
sum 117
Initialization of variables
In C++, there are three ways to initialize
variables.
They are all equivalent and are reminiscent of
the evolution of the language over the years:
The first one, known as c-like initialization, consists
of appending an equal sign followed by the value
to which the variable is initialized:
type identifier = initial_value;
int x = 0;
A second method, known as constructor
initialization, encloses the initial value between
parentheses (()):
type identifier (initial_value);
For example: int x (0);
26 A third method, known as uniform initialization,
All three ways of initializing variables are valid
and equivalent in C++.

27
Basic Input/Output

28
cin and strings
The extraction operator can be used on cin to
get strings of characters in the same way as
with fundamental data types:
To get an entire line from cin, there exists a
function, called getline, that takes the stream
(cin) as first argument, and the string variable
as second. For example:

29
Strings
Variables of string type are able to store
sequences of characters, such as words or
sentence.
The program needs to include the header where
the type is defined within the standard library
(header <string>):
// my first string
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string mystring;
mystring = "This is a string";
30 cout << mystring;
return 0;
Constants
Constants are expressions with a
fixed value.
Literals are the most obvious kind
of constants.
They are used to express
particular values within the
source code of a program.
a = 5;
The 5 in this piece of code was

31
a literal constant.

Keywords
C++ keywords: Cannot be used as identifiers or
C ++ Keywords
variable names
auto break case char const
continue default do double else
enum extern float for goto
if int long register return
short signed sizeof static struct
switch typedef union unsigned void
volatile while
C++ only keywords
asm bool catch class const_cast
delete dynamic_cast explicit false friend
inline mutable namespace new operator
private protected public reinterpret_cast
static_cast template this throw true
try typeid typename using virtual
wchar_t
C++ Operators and Expressions
An operator is a symbol that tells the compiler
to perform specific mathematical or logical
manipulations.
An expression is a sequence of operators and
the operands.
It is a form when you combine operands and
operators.
C++ is rich in built-in operators and provides
following type of operators:
Arithmetic Operator
Assignment Operator
Relational and equality Operator
Logical Operators
33
Increments and Decrements Operator
Arithmetic Operator
The five arithmetical operations supported by the
C++ language are:
+ Addition
- Subtraction
* Multiplication
/ Division
% modulo
% - Modulo is the operation that gives the
remainder of a division of two values.
For example,
a = 17% 3;
The variable a will contain the value 2, since 2 is
the remainder from dividing 17 between 3.
34
 Note that use of the blanks has no effect on the evaluation
of the expression.
 The parentheses is used to improve the readability of the
program and also avoid user errors. The evaluation must
be carried out as per precedence rule.
 Arithmetic operators as per precedence:
( ) for grouping the variables.
- unary for negative number
* / multiplication and division
+- addition and subtraction
For example: if the following example is not proper grouped
using parentheses than the computer will evaluate as per
the precedence.
x + y * x - z where x=5,y=6 and z=8
5 +( 6 * 5) – 8
(5 + 30) – 8
35 (35 – 8)
Assignment Operator
OPERATOR MEANING
• =Assign RHS value to LHS
• += Value of LHS variable is added to the value of RHS
and assigned back to the variable in LHS
• -=Value of RHS variable is subtracted from the value of
the LHS and assigned back to the variable in LHS
• *=Value of LHS variable is multiplied by the value of the
RHS and assigned back to the variable in LHS
• /=Value of LHS variable is divided by the value of the
RHS and assigned back to the variable in LHS
• %=The remainder will be stored back to the LHS after
integer division is carried out between the LHS variable
and the RHS variable.
• &= Bitwise AND operation and assign to the LHS
• |=Bitwise OR operation and assign to the LHS
~=Bitwise complement and assign to the LHS
• 36
Example
#include <iostream>
using namespace std;
int main ()
{ int a, b;
a = 10;
b = 4;
a = b;
b = 7;
cout << "a:";
cout << a;
cout << " b:";
cout << b;
return 0; }
37
Output : a:4 b:7
When we want to modify the value of a variable by performing
an operation on the value currently stored in that variable we
can make use of compound assignment operators.
 a += b expression is equivalent to a = a + b
 a *= b expression is equivalent to a = a * b
 a /= b expression is equivalent to a = a / b and so on.
// compound assignment operators
#include <iostream>
using namespace std;
main ()
{
int a, b=3;
a = b;
a+=2; // equivalent to a=a+2
cout << a;
return 0;
}
38
Ouput : 5
Relational and equality
Operator
 In order to compare an expressions we can use the
relational and equality operators are used .
 The result of a relational operation is a boolean
value that can only be true or false.
 Let us go through the relational and equality
operators which are also called as comparison
operators :
operator specification
== Equal to
!= Not equal to
> Greater than
< less than
>= Greater than equal to
39
<= Less than equal to
Here are some examples:
(5== 2) //evaluates to false.
(9 > 7) // evaluates to true.
(2 != 1) // evaluates to true.
(4 >= 4) // evaluates to true.
(8 < 8) // evaluates to false.
 Instead of using only numeric constants, we can
use any valid expression, including variables.
Suppose that a=2, b=3 and c=6,
• (a == 5) // evaluates to false since a is not equal to 5.
• (a*b >= c) // evaluates to true since (2*3 >= 6) is
true.
• (b+4 > a*c) // evaluates to false since (3+4 > 2*6) is
false.
• 40 ((b=2) == a) // evaluates to true.
 The operator = (one equal sign) is not the
same as the operator == (two equal
signs), the first one is an assignment
operator (assigns the value at its right to
the variable at its left) and the other one
(==) is the equality operator that
compares whether both expressions on
two sides of it are equal to each other.
 Thus, in the last expression ((b=2) == a),
we first assigned the value 2 to b and
then we compared it to a, that also stores
the value 2, so the result of the operation
41is true.
Logical Operators:
OPERATORS MEANING
! NOT
&& LOGICAL AND
|| LOGICAL OR
• The Operator ! is the C++ operator to perform the Boolean
operation NOT, it has only one operand, located at its right,
and the only thing that it does is to inverse the value of it,
producing false if its operand is true and true if its operand
is false.
• Basically, it returns the opposite Boolean value of evaluating
its operand.
• For example:
!(5 == 5) // evaluates to false because the expression at its
right (5 == 5) is true.
!(6 <= 4) // evaluates to true because (6 <= 4) would be
false.
!true // evaluates to false
42
!false // evaluates to true.
Logical AND:
• The logical operators && and || are used when
evaluating two expressions to obtain a single relational
result.
• he operator && corresponds with Boolean logical
operation AND.
• This operation results true if both its two operands are
true, and false otherwise.
• The following panel shows the result of operator &&
evaluating the expression a &&b:

a b a&&b
true true true
false true false
true false false
false false false
43
Logical OR:
The operator || corresponds with Boolean logical
operation OR. This operation results true if either one
of its two operands is true, thus being false only when
both operands are false themselves. Here are the
possible results of a || b:
The following panel shows the result of operator ||
evaluating the expression a || b:
a b a||b
true true true
false true true
true false true
false false false
For example:
( (5 == 5) && (3 > 6) ) // evaluates to false ( true &&
false ).
( (5 == 5) || (3 > 6) ) // evaluates to true ( true || false ).
44
Conditional Operator:
Conditional operators acts on three expressions
and therefore is also called as ternary operator.
SYNTAX
condition ? result1 : result2
If condition is true the expression will return
result1, if it is not it will return result2.
Here are some examples of conditional operator
7==5 ? 4 : 3 // returns 3, since 7 is not equal to 5.
7==5+2 ? 4 : 3 // returns 4, since 7 is equal to 5+2.
5>3 ? a : b // returns the value of a, since 5 is
greater than 3.
a>b ? a : b // returns whichever is greater, a or b.

45
// conditional operator
#include <iostream>
using namespace std;
int main ()
{
int a,b,c;
a=2;
b=7;
c = (a>b) ? a : b;
cout << c;
return 0;
}
OUTPUT:
7
In this example a was 2 and b was 7, so the expression being
evaluated (a>b) was not true, thus the first value specified
after the question mark was discarded in favor of the second
46
value (the one after the colon) which was b,with a value of 7.
Unary Operators:
 There are some special operators used in C++
language to perform particular type of operation.
 The following Operators are considered as unary
operators in C++ language.
 Unary operators requires only a single expression
to produce a line.
 Unary Operators usually precede their Operands.
 Sometimes, some unary operators may be
followed by the operands such as incremented
and decremented.
The following are the unary operators:
Incrementer (++)
Decrementer (--)
47
Incrementer and decrementer:
• Two special Operators are used in c++ to control the loops in
an effective manner.
 Incrementer: The symbol ++ is used for incrementing the
variable by 1.
For example:
++i; is equal to i = i+1;
i++; is equal to i = i+1;
There are two types of increments Prefix incrementer (+
+i)and postfix incrementers (i++).
 In prefix incrementer, the variable is incremented first and
then the operation is performed and for Postfix the Operation
is performed and than the variable is incremented.
For example:
i=7;
X=++i;
48 X= --i;
 Decrementer: The symbol -- is used for decrementing the
variable by 1.
For example:
--i; is equal to i = i-1;
i--; is equal to i = i-1;
There are two types of decrements Prefix decrementer (--
i)and postfix decrementer(i--)
Shortening even more some expressions, the increment
operator (++) and the decrement operator (--) increases or
reduces the value stored in a variable by one.
• They are equivalent to +=1 and to -=1, respectively. c++;
is same as c=c+1;
B=3;
A=++B;
// A becomes 4, B becomes 4
B=3;
49
A=B++;
// A becomes 3, B becomes 4
Comma Operator(,):
 The comma operator (,) is used to separate
two or more expressions that are included
where only one expression is expected.
 When the set of expressions has to be
evaluated for a value, only the rightmost
expression is considered.
 For example, the following code:
 A = (b=3, b+2);
 Would first assign the value 3 to b,
and then assign b+2 to variable a. So, at
the end, variable a would contain the value
5 while variable b would contain value 3.
Sizeof:
The sizeof Operator is used to give the
direction to the c++ compiler to reserve the
memory size or block to the particular data
type which is defined in the structure type of
data in the linked list.
This operator accepts one parameter, which
can be either a type or a variable itself and
returns the size in bytes of that type or object:
The general syntax is:
a = sizeof (char);
This will assign the value 1 because char is a
one-byte long type. The value returned by
sizeof is a constant, so it is always determined
51
Statements
Statements are the instructions gives to
the computer to perform any kind of
action Most programs decide what to do
in response to changing circumstances.
A compound(Block Statement)
statement is a group of statements (each
of them terminated by its own
semicolon), but all grouped together in a
block, enclosed in curly braces: {}:
These programs not only store data but
they also manipulate data in terms of
consolidation, rearranging, modifying
52
 Every programming language provides:
Sequence
The sequence construct means the
statements are being executed
sequentially.
Selection
The selection construct means the
execution of statement(s) depending upon
a condition-test.
 if,
 if/else,
 switch

Iteration
The iteration construct means repetition of
53 a set-of-statements depending upon a
Selection statements
The selection (if, if-else, if-else-if, and switch)
statements allows to choose the set-of-
instructions for execution depending upon an
expression's truth value.
 C++ provides following two types of selection
statements:
if statement
switch statement
C++ if Statement
An if statement tests a particular condition; if the
condition evaluates to true, a course-of-action is
followed i.e., a statement or set-of-statements is
executed.
Otherwise (if the condition evaluates to false), the
54
course-of-action is ignored.
if Statement Flow chart

55
Example1
//* C++ Selection Statements - C++ if Statement
*/ #include<iostream>
#include<conio.h>
using namespace std;
int main()
{
char ch;
cout<<"Enter a character: ";
cin>>ch;
if(ch>='0' && ch<='9')
{
cout<<"You entered a digit.";
}
getch();
56
}
Example2
//Sorting two numbers.
int Value1;
int Value2;
cout << "Enter two integers: ";
cin >> Value1 >> Value2;
if (Value1 > Value2)
{
int RememberValue1 = Value1;
Value1 = Value2;
Value2 = RememberValue1;
}
cout << "The input in sorted order: "
<< Value1 << " " << Value2 << endl;
Output:
65
57
50
50 65
Else if statement:
If … else statement is also a decision
making statement.
This statement controls the flow of execution
of statements.
This statement informs the compiler of
performing certain instructions if a specified
condition is true or false.
Thus we need to provide statements which
should be executed when condition is true as
well as condition is false.
Syntax
If(condition)
Statement1;
Else
The if .. Else statement is a two way branching
statement.
On execution the condition is evaluated and if
the condition is true the set of statement before
the else is executed and if the condition is false
then the set of statements after the else part is
executed.
If the expression evaluates to true i.e., a nonzero value,
the statement 1 is executed, otherwise, statement 2 is
executed.
The statement 1 and statement 2 can be a single
statement, or a compound statement, or a null statement.
Example1:
/* C++ Selection Statements - C++ if-else
Statement */
#include<iostream>
#include<conio.h>
Using namespace std;
int main()
{
int num;
cout<<"Enter a number: ";
cin>>num;
if(num%2==0)
60 { cout<<"You entered an even number"; }
Example2:
cout << "Enter two integers: ";
int Value1;
int Value2;
cin >> Value1 >> Value2;
int Max;
if (Value1 < Value2)
{
Max = Value2;
}
else
{
Max = Value1;
}
cout << "Maximum of inputs is: " << Max << endl;

61
Nested Ifs Statement
A nested if is an if that has another if in its if's body
or in its else's body.
if(expression 1)
{
if(expression 2)
{ statement 1; }
else
{ statement 2; }
}
else
{ body-of-else; }

62
 Eample: /* C++ Selection Statements - C++ nested ifs
Statement */
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int num;
cout<<"Enter a number: ";
cin>>num;
if(num>100) {
if(num>500)
{
if(num>10000)
{ cout<<"Its too high..!!"; }
if(num<1000)
{ cout<<"Its medium..!!"; }
}
if(num<=500)
{ cout<<"Its low..!!"; }
} if(num<=100)
63
{ cout<<"Its too low..!!"; }
Selection statements
 C++ if-else-if Ladder
 A common programming construct in C++ is the if-
else-if ladder, which is often also called the if-else-if
staircase because of its appearance.
 It takes the following general form :
if(expression)
{ statement 1; }
else if(expression 2)
{ statement 2; }
else if(expression 3)
{ statement 3; } . . .
else
{ statement N; }
The expression are evaluated from the top downward.
As soon as an expression evaluates to true, the

64
statement associated with it is executed and the rest of
the ladder is bypassed.
65
* C++ Selection if(ch=='+')
Statements - C++ if-else- result=a+b;
if Ladder */
#include<iostream> else if(ch=='-')
#include<conio.h> result=a-b;
using namespace std; else if(ch=='*')
int main() result=a*b;
{ else if(ch=='/')
char ch; result=a/b;
float a, b, result;
cout<<"\n"<<"The
cout<<"Enter any two
calculated result is :
number: ";
"<<result<<"\n";
cin>>a>>b; cout<<"\
n"<<"Enter the getch();
66
operator(+, -, *, /) : "; }
cin>>ch;
switch Statement
 C++ provides a multiple-branch selection statement
known as switch.
 This selection statement successively tests the value of an
expression against a list of integer or character constants.
 When a match is found, the statements associated with that
constant are executed.
 The syntax of switch statement is as follows:
switch(expression)
{
case constant1 : statement sequence 1; break;
case constant2 : statement sequence 2; break;
...
case constant n-1 : statement sequence n-1; break;
default : statement sequence n;
}
 The default statement gets executed when no match is found.
 The default statement is optional and, if it is missing , no
67
action takes place if all matches fail.
68
Example :
 * C++ Selection Statement
- switch Statement */
#include<iostream> case 3 : cout<<"\nTuesday";
break;
#include<conio.h>
case 4 : cout<<"\
using namespace std; nWednesday"; break;
void main() case 5 : cout<<"\
nThursday"; break;
{
case 6 : cout<<"\nFriday";
int dow; break;
cout<<"Enter number of case 7 : cout<<"\nSaturday";
week's day (1-7): "; break;
default : cout<<"\nWrong number
cin>>dow; of day";
switch(dow) break;

{ }
case 1 : cout<<"\nSunday"; return 0;
69
break; }
C++ Loops
The iteration (for, while, and do-while loop)
statements allows a set of instruction to be
performed repeatedly until a certain condition is
fulfilled.
The iteration statements are also called loops or
looping statements. C++ provides three kinds of
loops :
for loop
while loop
do-while loop
All three loop constructs of C++ repeat a set of
statements as long as a specified condition
remains true.

70 This specified condition is generally referred to
Loop Parts
Every loops has its elements that control and
govern its execution. Generally, a loop has four
elements that have different purposes.
These elements are as :
 Initialization Expression(s)
 The initialization expression(s) give(s) the loop variable(s)
their first value(s).
 The initialization expression(s) is executed only once, in
the beginning of the loop.
 Test Expression
 The test expression is an expression whose truth value
decides whether the loop-body will be executed or not.
 Update Expression(s)
 The update expression(s) change the value(s) of loop
variable(s)
 Loop's Body
71  The statements that are executed repeatedly (as long as
the test-expression is nonzero) from the body of the loop
for Loop
 All its loop-control elements are gathered in one place (on the
top of the loop)
 The general form (syntax) of the for loop statement is :
 for(initialization expression(s); test-expression; update
expression(s))
{
body-of-the-loop ;
}
 /* C++ Iteration Statements - C++ for Loop */
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{ clrscr();
int i;
for(i=1; i<=10; i++)
{
cout<<i<<" ";
72 }
getch(); }
Initial-Action

false
Action-After- Continuation
Each-Iteration condition?

true

Statement(s)
(loop-body)

Next
Statement

73
Nesting of For loop:
 It is possible to insert a for loop within another for loop. This is
called as nesting of loops.
 The following program illustrates nesting of loops.
Example:
#include<iosteam>
#include<conio.h>
Using namespace std;
Void main()
{
int k;
for(i=1;i<=4;i++)
{
for(k=1;k<=i;k++)
{
cout << “*”;
}
cout << endl;
}
}
C++ while Loop
The second loop available in C++ is the
while loop. The while loop is an empty-
controlled loop.
Following is the syntax of the while loop :
while(expression)
{
loop-body ;
}
In a while loop, a loop control variable
should be initialized before the loop begins
as an uninitialized variable can be used in
the expression.
75
The loop variable should be updated inside
 true

 condition  statement

 false

76
C++ while Loop
/* C++ Iteration Statements - C++ while Loop */
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
clrscr();
unsigned long num, fact=1;
cout<<"Enter a number: ";
cin>>num;
while(num)
{
fact = fact*num;
num--;
}
cout<<"The factorial of the number is "<<fact;
return 0;
77
}
C++ Loops
C++ do-while Loop
Unlike the for and while loops, the do-while is an
exit-controlled loop i.e., it evaluates its test-
expression at the bottom of the loop after
executing its loop-body statements.
This means that a do-while loop always executes at
least once.
The syntax of the do-while loop is:
do statement

{
statement ;
}while(test-expression); true
condition
Example
char ch = 'A' ; false
do {
78 cout << "\n" << ch ;
ch++;
 //C++ Iteration Statements - C++ do-
while Loop switch(ch)
#include<iostream> {
#include<conio.h> case '1' : area = l * b ;
#include<math.h> cout<<"Area = "<<area; break ;
#include<process.h> case '2' : peri = 2 * (l + b);
using namespace std; cout<<"Perimeter = "<<peri;
break;
void main()
case '3' : diag = sqrt((l * l) + (b *
{
b));
char ch, ch1;
cout<<"Diagonal = "<<diag; break;
float l, b, peri, area, diag;
case '4' : cout<<"Breaking..Press a
cout<<"Rectangle Menu"; key..";
cout<<"\n 1. Area"; getch();
cout<<"\n 2. Perimeter"; exit(1);
cout<<"\n 3. Diagonal"; default : cout<<"Wrong choice !!!!";
cout<<"\n 4. Exit\n"; cout<<"\nEnter a valid one"; break;
cout<<"\nEnter your choice: "; } //end of switch
do { cout<<"\nWant to enter more
cin>>ch; (y/n) ? ";
if(ch == '1' || ch == '2' || ch == '3') cin>>ch1; if(ch1 == 'y' || ch1 ==
{
'Y')
cout<<"Enter length & breadth: ";
79 cout<<"Again enter choice (1-4):
cin>>l>>b;
";
C++ Nested Loops
A loop may contain another loop in its body.
This form of a loop is called nested loop.
But in a nested loop, the inner loop must terminate
before the outer loop.
/* C++ Iteration Statements - C++ Nested Loops */
#include<iostream>
#include<conio>
using space std;
void main()
{
int i, j;
for(i=0; i<15; i++)
{
for(j=0; j<=i; j++)
{
cout<<"* ";
}
cout<<"\n";
}
return 0; }
80
 C++ Nested Loops
/* C++ Loops Program */
#include<iostream>
#include<conio.h>
using namespace std;
void main()
{ clrscr();
int num, temp, i, j;
cout<<"Enter a number: ";
cin>>num;
for(i=0; i<10; i++)
{
num++;
temp=num;
for(j=0; j<=i; j++)
{
cout<<num<<" ";
num++;
}
cout<<"\n";
num=temp;
}
return 0; }

81
Jump Statement
The jump (break, continue, goto, and return)
statements unconditionally transfer program
control within a function.
 C++ has four statements that perform an
unconditional branch :
return
goto
break
continue
Of these, you may use return and goto anywhere
in the program whereas break and continue are
used inside smallest enclosings like loops etc.
The return statement is used to return from a
82 function.
Jump Statement
C++ goto Statement
The goto statement can transfer the program
control anywhere in the program.
The target destination of a goto statement is
marked by a label.
The target label and goto must appear in the
same function.
:
Here is the syntax of the goto statement in C+
{
+: goto last :
goto label; :
: last : ;}
label :
Example
83 a=0;
C++ break Statement
 The break statement enables a program to skip over part of
the code.
 A break statement terminates the smallest enclosing while,
do-while, for, or switch statement.
 Execution resumes at the statement immediately following
the body of the terminated statement.
 If a break statement appears in a nested-loop structure, then
it causes an exit from only the very loop it appears in.
int a, b, c, i;
for(i=0; i<20; i++)
{
cout << "Enter 2 numbers" ;
cin >> a >> b ;
if(b == 0) break;
else c = a/b ;
cout << "\n Quotient =" << c << "\n" ;
}
84
 C++ continue Statement
 The continue statement forces the next iteration of the loop to
take place, skipping any code between
 For the for loop, continue causes the next iteration by
updating the variable and then causing the test-expression's
evaluation.
 For the while and do-while loops, the program control passes
to the conditional tests.
int a, b, c, i;
for(i=0; i<20; i++)
{
cout << "\n Enter 2 numbers" ;
cin >> a >> b ;
if(b == 0)
{
cout << "\n The denominator cannot be zero" << "Enter again !";
continue;
}
else c = a/b ;
cout << "\n Quotient =" << c << "\n" ;
85
}
 C++ break and continue Statement
/* C++ Jump Statements - C++ break and continue Statement */
#include<iostream>
#include<conio.h>
using namespace std;
void main()
{
cout<<"The loop with \'break\' produces output as:\n";
for(int i=1; i<=10; i++)
{
if((i%3)==0) break;
else cout<<i<<endl;
}
cout<<"\nThe loop with \'continue\' produce output as:\n";
for(i=1; i<=10; i++)
{
if((i%3)==0)
continue;
else cout<<i<<endl;
}
getch(); }
86
Functions
A Function is a sub-program that acts on data
and often returns a value.
A large program is broken down into smaller
units known as functions.
A functions is a named unit of a group of
program statements.
Why to use Functions ?
The most important reason to use functions is to
make program handling easier as only a small part
of the program is dealt with at a time, thereby
avoiding ambiguity.
Another reason to use functions is to reduce
program size.
Functions make a program more readable and
87
understandable to a programmer thereby making
C++ Function Types
In C++, there are broadly two types
of functions :
1. Library (Built-in) functions and
2. User defined functions

Library (Built-in) functions


are predefined functions having their
special meaning
These functions are part of the
compiler package.
88
C++ Built-in Function
/* C++ Function Types - C++ Built-in Function */
#include<iostream.h>
#include<string.h>
#include<conio.h>
void main()
{
char str[80];
cout<<"Enter any string (line):\n";
cin.getline(str, 80);
int len = strlen(str);
cout<<"\nLength of the string is: "<<len;
getch();
}

89
User defined functions
are the functions defined by the
programmer/user
In C++, a function must be defined
before it is used anywhere in the
program
return_type
function_name(comma_separated_parameter_list)
{
function body
}
where return_type is any valid C++ data
type specifies the type of value that the
return statement of the function returns.
90 A function that doesn't return any value is
Now the function_name is any valid C++
identifier, which is the name of the function, and
then comma_separated_parameter_list is the
parameter list of the function separated by
comma.
Here is an example of a function definition in C+
+
int sum(int a, int b)
{
int add;
add = a+b;
return add;
}
Or
int sum(int a, int b)
{ return a+b; }
If a function doesn't return any value, then
91 specify return_type as void as shown in this
C++ Function  string getFatherName()

 #include<iostream> {

 #include<string.h> string Name;


 using namespace std; cout<<"\nenter your father
name :";
 string getFatherName();
cin>>Name;
 int main()
return Name;
{ }
char FName[25];
string LName;
cout<<"enter your first name: ";
cin>>FName;
LName=getFatherName();
cout<<"Your full name is : "<<FName<<"
"<<LName;
return 0;
}

92
C++ Function Prototype
A function prototype is a declaration of the function
that tells the program about the type of the value
returned by the function and the number and type
of arguments.
return_type function_name(parameter_list);
The prototype declaration looks just like a function
definition except that it has no body i.e., its code is
missing.
A declaration introduces a (function) name to the
program whereas a definition is a declaration that
also tells the program what the function is doing
and how it is doing.
Here is a function prototype example in C++:
int sum(int a, int b);

You can also declare above as
93
Accessing a Function in C++
A function is called or invoked or
executed, by providing the function
name, followed by the parameters
being sent enclosed in the
parentheses.
A function declaration can skip the
argument names but a function
definition, can not.
To invoke a function where prototype
looks like below
int sum(int, int);
94 The function call statement may look
A simple function
example
#include <iostream>
using namespace std;
/* This function adds two integer values and
returns the result */
int sum(int num1, int num2){
int num3 = num1+num2;
return num3;
}
int main(){
//Calling the function
cout<<sum(1,99);
return 0;
95 }
The same program can be
written like this:
#include <iostream>
using namespace std;
//Function declaration
int sum(int,int);
//Main function
int main(){
//Calling the function
cout<<sum(1,99);
return 0;
}
/* Function is defined after the main method */
int sum(int num1, int num2){
int num3 = num1+num2;
return num3;
96 }
C++ Function
 C++ Function Examples
/* C++ Functions - Example Program of C++ Functions */
#include<iostream.h>
#include<conio.h>
void greeting(void);
void main() {
char ch;
cout<<"Press y for greeting message: ";
cin>>ch;
if(ch=='y' || ch=='Y')
{
greeting();
}
cout<<"\n\nPress any key to exit..!!\n";
getch();
}
void greeting(void)
{
cout<<"\nHello, Programmer!";
cout<<"\nWelcome to codescracker.com";
97
}
C++ Function
 C++ Function Examples
/* C++ Functions - Example Program of C++ Functions */
#include<iostream>
#include<conio.h>
float cube(float);
using namespace std;
int main()
{
cout<<"Enter a number to calculate its cube: \n";
cin>>numpass;
numget = cube(numpass);
cout<<"\nThe cube of "<<numpass<<" is "<<numget;
numget = cube(9);
float numpass, numget;
cout<<"\nThe cube of 9 "<<" is "<<numget;
getch();
return 0;
}
float cube(float x)
{
float temp;
temp = x*x*x;
return temp;
98 }
C++ Function
Function call type
There are two types of function call:
Call by value
The call by value method copies the value of
the actual parameters into the formal
parameters, that is, the function creates its own
copy of argument values and then uses them.
In call by value method, the changes are not
reflected back to the original values.
Call by reference
Since, call by reference method, operates on
the address of the variables (argument passed),
the value changed inside the function also
affect the original value.
In call by reference method, the changes are
99
reflected back to the original values.
C++ Function
 C++ call by value Function void swap(int a, int b)
Examples {
/* C++ Functions - Example int temp;
Program of C++ Functions * This temp = a;
program demonstrates call by a = b;
value method */ b = temp;
cout<<"In:\n\t";
#include<iostream.h> cout<<"num1 = "<<a<<"\tnum2 =
#include<conio.h> "<<b<<"\n\n";
void swap(int, int); }
void main()
{
int num1, num2;
cout<<"Enter any two number: ";
cin>>num1>>num2;
cout<<"\nBefore:\n\t";
cout<<"num1 = "<<num1<<"\
tnum2 = "<<num2<<"\n\n";
swap(num1, num2); cout<<"After:\
n\t";
cout<<"num1 = "<<num1<<"\
tnum2 = "<<num2<<"\n\n";
10
0 getch();
C++ Function
 C++ call by reference Function void swap(int &a, int &b)
Examples {
/* C++ Functions - Functions * This int temp;
program demonstrates call by temp = a;
reference method */ a = b;
b = temp;
#include<iostream> cout<<"In:\n\t";
#include<conio.h> cout<<"num1 = "<<a<<"\tnum2 =
void swap(int &, int &); "<<b<<"\n\n";
using namespace std; }
int main()
{
int num1, num2;
cout<<"Enter any two number: ";
cin>>num1>>num2;
cout<<"\nBefore:\n\t";
cout<<"num1 = "<<num1<<"\
tnum2 = "<<num2<<"\n\n";
swap(num1, num2);
cout<<"After:\n\t";
cout<<"num1 = "<<num1<<"\
10 tnum2 = "<<num2<<"\n\n";
1 getch();
C++ Return from Function
A function terminates when either a
return statement is encountered or
the last statement in the function is
executed.
Generally, a return statement is used
to terminate a function whether or
not it returns a value.
The return statement is useful in two
ways.
First, an immediate exit from the function
is caused as soon as a return statement is
encountered and the control passes back
10
2 to the operating system which is main's
Default Arguments in C++ Functions
The default arguments are used when you provide
no arguments or only few arguments while calling
a function.
The default arguments are used during
compilation of program.
If you assign default value to an argument, the
subsequent arguments must int have default
sum(int a, intvalues
b, int c){
#include
assigned <iostream>
to them, else you will get compilation
int z;
using
error.namespace std; z = a+b+c;
int sum(int a, int b=10, int
return z;
c=20);
}
int main(){
cout<<sum(1)<<endl;
cout<<sum(1,
2)<<endl;
10 cout<<sum(1, 2,
3 3)<<endl;
C++ Scope Rules
Variable scope represents the scope of a
variable, that is, where they can be used in a
C++ program.
Basically there can be two scope of a variable
in a C++ program.
The first one is local variables and the
second one is global variables.
Local variables are those variables which are
declared inside a function/block.
Local variables are destroyed upon exit of the scope
where they are declared.
So they becomes unknown outside their block.

10
4
Global Variables
Global variables are those variables which are
defined outside of all the functions/block.
You can declare local and global variable with same
name.
But remember, the local variable will take higher
preference.
#include<iostream lvar2 = 200;
> gvar1 = lvar1 +
using namespace lvar2;
std; cout<<"lvar1(100)
#include<conio.h> + lvar2(200) =
int gvar1; gvar1("<<gvar1<
int main() <")";
{ Return 0;
10
5 int lvar1, lvar2; }
Function Recursion
 Recursion 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.
// 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 num;
cout<<"Enter a number: ";
cin>>num;
10 cout<<"Factorial of entered number: "<< factorial (num);
6
return 0;
Function Recursion
 Direct recursion: When function calls itself, it is
called direct recursion, the example we have seen
above is a direct recursion.
 Indirect recursion: When function calls another
function and that function calls the calling function,
then this<iostream>
#include is called indirect recursion. For example:
int fb(int n){
function A calls std;
using namespace function B and Function B calls
if(n<=1)
function
int fa(int);
A.
return 1;
int fb(int); else return n*fa(n-1);
int fa(int n){ }
if(n<=1) int main(){
return 1; int num=5;
else return n*fb(n-1); cout<<fa(num);
} return 0;
10 }
7
C++ Arrays
An array is simply a collection of variables of the
same data type that are referenced by a
common name.
In other words, when elements of linear
structures are represented in the memory by
means of contiguous memory locations, these
linear structures are called arrays.
An array stores a list of finite number (n) of
homogeneous data elements (i.e., data elements
of the same type).
The number n is called length or size or range of
an array.
In C++, all arrays consist of contiguous memory

10
locations.
8
The lowest address corresponds to the first
C++ Arrays
Types of Arrays in C++
There are basically two types of arrays:
 one-dimensional array and
 multi-dimensional arrays.

One dimensional array:


 A one-dimensional array is a group of elements
having the same data type and same name.
Individual elements are referred to using common
name and unique index of the elements.
In C++, an array is denoted as follows:
 array_name [array_size]
 where size specifies the number of elements in the array
and the subscript (also called index) value ranges from 0
through size-1.
Declare One Dimensional Array in C++
10 data_type array_name[array_size];
9 int arr[10];
C++ Arrays
Initialize One Dimensional Array in C++ :
 data_type array_name[array_size] =
{comma_separated_element_list};
Example : int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9,
10};
/* C++ One Dimensional Array */
#include<iostream.h>
#include<conio.h>
int main()
{
int arr[5] = {1, 2, 3, 4, 5};
int i;
for(i=0; i<5; i++)
{
cout<<"arr["<<i<<"] = "<<arr[i]<<"\n";
}
11
0 }
Array Questions
Write a C++ program ask to the user to
enter the array size and then array element
to find the largest number present in the
array, then display the result on the screen:
Write a C++ program that ask to the user to
enter the array size then it will ask to enter
the array elements, then it will finally ask to
enter a number to be search in the given
array to check whether it is present in the
array or not
Write a C++ program ask to the user to
enter array size and array elements to find
the smallest element present in the array,
11
then display the result on the screen
1 Write a C++ program ask to the user to
Array Questions
Sort the array using bubble sort
technique:
#include<iostream> for(i=0; i<(n-1); i++){
for(j=0; j<(n-i-1); j++){
#include<conio.h>
if(arr[j]>arr[j+1])
using namespace std;
{ temp=arr[j];
int main(){
int n, i, arr[50], j, temp; arr[j]=arr[j+1];
cout<<"Enter total number of arr[j+1]=temp;
elements :"; }
cin>>n; }
cout<<"Enter "<<n<<" }
numbers :“;
cout<<"Elements sorted
for(i=0; i<n; i++){
successfully..!!\n";
cout<<“Enter array element
cout<<"Sorted list in ascending
”<< i+1;
order :\n";
cin>>arr[i];
for(i=0; i<n; i++){
}
cout<<"Sorting array using cout<<arr[i]<<" ";
11 bubble sort technique...\n"; }
2
return 0; }
C++ Arrays
Two dimensional array:
 A two-dimensional array is an array in which each
element is itself a 1-D array.
Declare Two Dimensional Array in C++
data_type array_name[row_size][column_size];
Example : int arr[5][2];
Initialize Two Dimensional Array in C++
 data_type array_name[row_size][column_size] =
{ {comma_separated_value_list} };
 Example:
 int arr[5][2] = { {1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10} };

11
3
Example
/* C++ Two Dimensional Array */
cout<<"\nThe array elements
#include<iostream.h>
are: \n";
#include<conio.h>
for(i=0; i<5; i++)
int main()
{ {
int arr[5][2]; for(j=0; j<2; j++)
int i, j; {
int sum=0, avg=0;
cout<<arr[i][j]<<" ";
cout<<"Enter 5*2 array elements: ";
for(i=0; i<5; i++) }
{ cout<<"\n";
for(j=0; j<2; j++)
}
{
cin>>arr[i][j]; cout<<"\n\nSum of all elements
sum = sum + arr[i][j]; is: "<<sum;
} avg = sum/10;
} cout<<"\nAnd average is:
"<<avg;
11 return 0;
4
}
Example
/* C++ Program - Two for(i=0; i<row; i++)
Dimensional Array Program */ {
#include<iostream.h> for(j=0; j<col; j++)
#include<conio.h> {
cin>>arr[i][j];
void main() }
{ }
int arr[10][10], row, col, i, j; cout<<"The Array is :\n";
for(i=0; i<row; i++)
cout<<"Enter number of row {
for Array (max 10) : "; for(j=0; j<col; j++)
cin>>row; {
cout<<arr[i][j]<<" ";
cout<<"Enter number of column
}
for Array (max 10) : "; cout<<"\n";
cin>>col; }
cout<<"Now Enter getch();
"<<row<<"*"<<col<<" Array }
11
5 Elements : ";
Basic Matrix Operations
 A matrix is a rectangular or square grid of
numbers arranged into rows and columns.
Each number in the matrix is called an element,
and they are arranged in what is called an array.
 Matrices are often used in algebra to solve for
unknown values in linear equations, and in
geometry when solving for vectors and vector
operations.

 Matrix M

11
6
Matrix Addition
 We can add matrices together as long as
their dimensions are the same, i.e. both
matrices have the same number of rows
and columns.
 To add two matrices, we add the numbers
of each matrix that are in the same
element position.

11
7
Matrix Subtraction
 We can subtract matrices in a similar way
to addition.
Both matrices need to have the same
dimensions, and we subtract the numbers
of the second matrix from the first that are
in the same element position.

11
8
Multiplying a Matrix by a
Constant
 We can multiply a matrix by some value by
multiplying each element with that value.
The value can be positive or negative.

We can get the negative of a matrix by using


the above multiplication method:

11
9
Multiplying Matrices
 We can multiply a matrix (A) by another matrix
(B) if the number of columns in A is equal to the
number of rows in B (in bold).
 Multiplication of A by B is typically written as
A(B) or (A)B.

 A has 2 rows and 3 columns and B has 3 rows


and 1 column so we can multiply A by B.
 Notice that we can’t multiply B by A in this
particular case because the number of columns
in B is not equal to the number of rows in A (in
12
0 bold).
Multiplying Matrices
Multiplying matrices is not commutative:
A(B) ≠ B(A)
To multiply matrices, there’s a convention
that is followed.

Let’s look at the first row of A and the first


column of B.
Element a is multiplied by element e.
Element b is multiplied by element g.
12
1 The value of the element in the first row
Multiplying Matrices

Notice A(B) is now a .2 x 1. matrix.

12
2
Transposing a Matrix
To transpose a matrix, we swap the rows
for the columns.
To indicate that we are transposing a
matrix, we add a “T” to the top right-hand
corner of the matrix.

12
3
C++ String
Strings are the combination of characters.
In other words, you can think strings as an array of
characters.
Declaring Strings in C++
char string_name[string_size];
char str[20];
Initializing Strings in C++
char string_name[string_size] =
{comma_separated_character_list};
char str[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
To hold the null character ('\0') at the end of the
array, the size of the character array having the
string is one more than the number of characters in
the word "Hello.".

12
4
C++ String
C++ String Examples
/* C++ Strings - Example Program of C++ Strings
*/
#include<iostream>
using namespace std;
#include<conio.h>
int main()
{
char greet[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
cout<<greet<<endl;
getch();
}

12
5
C++ String
Find String Length in C++
Using function strlen() of string.h library and
display the length value of the string on the output
screen
Compare Two Strings in C++
To compare two string in C++ Programming, you
have to ask to the user to enter the two string and
start comparing using the function strcmp().
 If it will return 0, then both string will be equal and
if it will not return 0, then both string will not be
equal to each other
strcmp() function takes two argument
like strcmp(str1, str2)
Concatenate String in C++
To concatenate or to append one string to another
12
6
string in C++ Programming, you have to ask to the
C++ Data Structure
Sometimes, some logically related elements need
to be treated under one unit.
 For example, the elements storing a student's
information (e.g, rollno, name, class, marks, grade)
need to be processed together under one roof.
To handle and serve to such situations, C++ offers
structures.
C++ Structure Definition
To define structure in C++, follow this general
form:
struct tag
{
type variable-name ;
type variable-name ;
12 type variable-name ;
7
}structure-variables ;
The following code fragment shows how to define a
structure (say date).
The keyword struct tells the compiler that a
structure is being defined :
struct date
{
short day ;
short month ;
short year ;
};
In the above definition, the date is a structure tag and
it identifies this particular data structure and its type
specifier.
C++ Structure Variable Definition
To declare a structure variable having the data form
as defined by date, we will write :

8 date joining_date;
12
Thus, the complete structure definition is as
follows :
struct date
{
short day ;
short month ;
short year ;
}; date joining_date;
Now, the structure joining_date will be having its
elements as day, month and year.
The C++ compiler automatically allocates sufficient
memory to accommodate all of the element variables
that make up a structure variable.
Accessing Structure Members in C++
In C++, once a structure variable has been defined,
its member can be accessed through the use of dot (.)
12
9
operator.
#include <iostream>
// book 2 specification
#include <cstring>
strcpy( Book2.title, "Telecom Billing");
using namespace std;
strcpy( Book2.author, "Yakit Singha");
struct Books {
strcpy( Book2.subject, "Telecom");
char title[50]; Book2.book_id = 6495700;
char author[50]; // Print Book1 info
char subject[100]; cout << "Book 1 title : " << Book1.title
int book_id; <<endl;
cout << "Book 1 author : " <<
};
Book1.author <<endl;
int main() { cout << "Book 1 subject : " <<
struct Books Book1;// Declare Book1 Book1.subject <<endl;
of type Book cout << "Book 1 id : " << Book1.book_id
struct Books Book2; // Declare Book2 <<endl;
of type Book // Print Book2 info
// book 1 specification cout << "Book 2 title : " << Book2.title
<<endl;
strcpy( Book1.title, "Learn C++
cout << "Book 2 author : " <<
Programming");
Book2.author <<endl;
strcpy( Book1.author, "Chand cout << "Book 2 subject : " <<
Miyan"); Book2.subject <<endl;
13 strcpy( Book1.subject, "C++
0 cout << "Book 2 id : " << Book2.book_id
Programming");
/* C++ Data Structures */ cout<<"Enter marks obtained in
#include<iostream> 5 subjects:\n";
#include<conio.h> for(int i=0; i<5; i++)
{
#include<stdio.h> cout<<"Subject "<<i+1<<":
Using namespace std; ";
struct stud cin>>stud_var.marks[i];
{ sum = sum +
int rollno;
stud_var.marks[i];
char name[20];
}
char batch[2]; avg = sum / 5;
float marks[5]; if(avg<50)
char grade; { stud_var.grade = 'F'; }
else if(avg<60)
}stud_var; { stud_var.grade = 'C'; }
int main() else if(avg<80)
{float sum = 0, avg; { stud_var.grade = 'B'; }
else { stud_var.grade = 'A'; }
cout<<"Enter rollno: "; cout<<"\nStudent Result:\n";
cin>>stud_var.rollno; cout<<"\nRoll no:
cout<<"Enter name: "; "<<stud_var.rollno<<"\t\tName:
gets(stud_var.name); "<<stud_var.name;
13 cout<<"Enter batch: "; cout<<"\t\tBatch:
1 "<<stud_var.batch; cout<<"\
gets(stud_var.batch);
C++ Pointers
A pointer is a variable that holds the memory
address, usually the location of another variable in
the memory.
Why Pointers are so Important ?
Here are the reasons for the importance of pointers in
C++.
 Pointers provides the means by which the memory location of
a variable can be directly accessed and hence can be
manipulated in the way as required.
 Pointers supports C++'s dynamic allocation routines.
 Pointers can improve the efficiency of certain routines.

A variable storing a memory address is called a


pointer as it points to a specific memory location
whose address it is storing under its name.
C++ Pointer Declaration
13
2 Pointer variables are declared just like the normal
C++ Pointer Initialization
Two special operators are used with pointers that is, *
and &.
The & operator is a unary operator that returns the
memory address of its operand.
int num = 20; // declares an int variable named num
int *iptr; // declares an int pointer named
iptr iptr = &num; // this stores the memory address
of num into iptr
int val = *iptr; // the value present at the address num is
initialized to the variable val of type int
cout<<"Statements:\n";
cout<<"\tint num=20;\n\tint val;\n\tint *ptr;";
cout<<"\n\tiptr = &num;\n\tval = *iptr\n\n";
cout<<"Output:\n";
13 cout<<"\tnum = "<<num<<"\n\tval = "<<val;
3
/* C++ Pointers - Example Program of
C++ Pointers */
for(i=0; i<4; i++)
#include<iostream.h> {
#include<conio.h> (*ptr)*=3;
int main() --ptr;
}
{ for(i=0; i<4; i++)
int arr[] = {4, 6, 10, 12}; {
cout<<arr[i]<<" -> ";
int *ptr;
}
int i; getch();
ptr = arr; return 0;
}
for(i=0; i<3; i++)
{
cout<<*ptr<<" -> ";
ptr++;
}
cout<<"\n";

13
4
C++ File Handling
Sometime, it is important to store the information
entered by the user into the file for further use.
After storing the information into the file, later you
can retrieve those information from that file.
In C++, the file input/output operation are
performed through a component header file
fstream.h of C++ standard library.
In C++, a file
at its lowest level - is interpreted simply as a
sequence, or stream, of bytes.
at the user level - consists of a sequence of
intermixed data types such as characters, arithmetic
values, class objects

13The fstream.h library predefines a set of operations
5
* C++ File Handling - fout.open(fname, ios::out);
Store information into //cin.get(ch);
cout<<"Enter a word: ";
the file in C++ */ cin>>rec;
#include<iostream> //cin.getline(rec,80);
#include<conio.h> fout<<rec;
#include<fstream> cout<<"Data inserted
using namespace std; successfully..!!";
int main()
{ fout.close();
ofstream fout;
ifstream fin; cout<<"The file contains:\n";
char fname[20]; fin.open(fname, ios::in);
char rec[80],ch;
fin.get(rec, 80);
cout<<rec;
cout<<"Enter file name: ";
fin.close();
cin>>fname;
getch();
return 0;
}

13
6
C++ File Streams
A stream is a name given to a flow of data at the lowest
level.
At the lowest level, data is just the binary data without
any notion of data type.
Different streams are used to represent the different
kinds of data flow such as whether data is flowing into
the memory or out of the memory.
The stream that supplies data to the program is known
as the input stream.
 It reads the data from the file and hands it over to the program.
The stream that receives data from the program is
known as output stream.
 It writes the received data to the file.
The file I/O system of C++ contains a set of classes that
define the file handling methods.
These classes, designed to manage the disk files, are
13
7 declared in the header file named fstream.h.
The function of these classes have been
summarized in the following table

13
8
C++ File Streams cin.get(ch);
Example cout<<"Enter a line to store
/* C++ File Streams */
in the file:\n";
#include<conio.h> cin.get(inform, 80);
#include<fstream.h> fout<<inform<<"\n";
#include<stdlib.h>
cout<<"\nEntered
using namespace std;
int main()
informations successfully
{
stored..!!\n";
char inform[80]; fout.close();
char fname[20]; cout<<"Press any key to
char ch; exit...\n";
cout<<"Enter file name: ";
cin.get(fname, 20);
getch();
ofstream fout(fname, ios::out); return 0;
if(!fout) }
{ cout<<"Error in creating the file..!!\
n";
cout<<"Press any key to exit...\n";
getch();
13 exit(1);
9
}
(Copying Files)
# include<iostream> getch();
#include<conio.h> exit(1);
#include<fstream> }
cout<<"Enter target file
#include<stdio.h> name with extension (like
#include<stdlib.h> filet.txt) : ";
using namespace std; gets(fname2);
int main() ft.open(fname2);
{ if(!ft)
{
ifstream fs;
cout<<"Error in
ofstream ft; opening target file..!!";
char ch, fname1[20], fname2[20]; fs.close();
char inform[80]; getch();
exit(2);
}
cout<<"Enter source file name with
while(fs.eof()==0)
extension (like files.txt) : ";
{
gets(fname1); fs>>ch;
fs.open(fname1); ft<<ch;
if(!fs) }
{ cout<<"File copied
successfully..!!";
cout<<"Error in opening
fs.close();
14 source file..!!";
0 ft.close();
(Merging Files)
/* C++ Program - Merge Two cout<<"Enter name of file
Files */ ifiles1>>ch;
(with extension like file3.txt) ifilet<<ch;
#include<iostream> which will store the contents }
#include<conio.h> of the two files (fname1 and while(ifiles2.eof()==0)
#include<fstream> fname1) : "; {
gets(fname3); ifiles2>>ch;
#include<stdio.h>
ifiles1.open(fname1);
#include<stdlib.h> ifiles2.open(fname2); ifilet<<ch;
using namespace std; if(ifiles1==NULL || }
int main() ifiles2==NULL) cout<<"The
{ { two files were merged
perror("Error Message "); into "<<fname3<<" file
cout<<"Press any key to successfully..!!";
ifstream ifiles1, ifiles2,fin; exit...\n"; ifiles1.close();
ofstream ifilet; getch(); ifiles2.close();
char ch, fname1[20], exit(EXIT_FAILURE); ifilet.close();
fname2[20], } cout<<"\nThe
fname3[30],inform[100]; ifilet.open(fname3); merged file contains:\n";
cout<<"Enter first file name if(!ifilet) fin.open(fname3,
(with extension like {perror("Error ios::in);
file1.txt) : "; Message "); fin.get(inform, 100);
cout<<"Press any key to cout<<inform;
gets(fname1);
exit...\n“; fin.close();
cout<<"Enter second file getch();
14 getch();
1 name (with extension like exit(EXIT_FAILURE); return 0;
file2.txt) : ";
C++ File Handling
C++ File Streams
A stream is a name given to a flow of data at the lowest
level.
At the lowest level, data is just the binary data without
any notion of data type.
Different streams are used to represent the different
kinds of data flow such as whether data is flowing into
the memory or out of the memory.
The stream that supplies data to the program is known
as the input stream. It reads the data from the file and
hands it over to the program.
The stream that receives data from the program is
known as output stream.
It writes the received data to the file.
The file I/O system of C++ contains a set of classes that
14 define the file handling methods.
2

C++ Files
Files are required to store any information
permanently, for later use.
The data files can be stored in the following two
ways :
Text files
 A text file stores the information in ASCII characters.
 In text files, each line of text is terminated or delimited with a
special character named EOF known as End of Line character.
 In text files, some internal translations take place when this
EOF character is read or written.
Binary files
 A binary file is just a file that contains information in the same
format in which the information is held in memory.
 In binary file, there is no delimiter for a line.
 Also no translations occur in binary file.
 As a result, binary files are faster and easier for a program to
14
3 read and write than are text files.
C++ Files
C++ Opening and Closing Files
There are the following three types of file streams in
C++:
 Input
 To create an input stream, you must declare the stream to be
of class ifstream.
 Here is the syntax: ifstream fin;
 Output
 To create an output stream, you must declare it as class
ofstream. Here is an example:
 ofstream fout;
 input/output
 Streams that will be performing both input and output
operations must be declared as class fstream.
 fstream fio;

Opening a File in C++


14
4 
Opening of files can be achieved in the following two
C++ Files
Opening a File in C++
 Opening of files can be achieved in the following two ways :
 The first method is preferred when a single file is used with a
stream. However, for managing multiple files with the same
stream, the second method is preferred.
 Using the constructor function of the stream class.
 ifstream fin("myfile", ios::in) ;
 The above given statement creates an object, fin, of input
file stream.
char ch;
fin >> ch ; // read a character from the file
 when you want a program to write a file
o ofstream fout("secret" ios::out) ; // create ofstream object
named as fout
• This would create an output stream, object named as fout and
attach the file secret with it
• fout << code << "xyz" ; /* will write value of code and "xyz" to
14 fout's associated file namely "secret" here.
5

C++ Files
Opening a File in C++
Using the function open().
There may be situations requiring a program to
open more than one file.
 If the situation requires simultaneous processing
of two files, then you need to create a separate
stream for each file.
o ifstream fin; // create an input stream
o fin.open("Master.dat", ios::in); // associate fin
stream with file Master.dat :
o ….. // process Master.dat
o fin.close(); // terminate association with
Master.dat
o fin.open("Tran.dat", ios::in); // associate fin
14
stream with file Tran.dat :
6
o ….. // process Tran.dat
C++ Files
The Concept of File Modes
The file mode describes how a file is to be used : to
read from it, to write to it, to append it, and so on.
E.g stream_object.open("filename", (filemode) ) ;
 fout.open("Main", ios :: out | ios :: nocreate | ios :: binary);

14
7
C++ Files
C++ Change the Behavior of Streams
The default behaviour of an ofstream type stream
(ios::out file mode), upon opening a file, is that it
create the file if the file doesn't yet exist and it
truncates the file (i.e., deletes its previous contents) if
the file already exists.
 If you want to change this default behaviour, then
you can do it by specifying any of the following file
modes with open() function :

14
8
C++ Files
C++ Sequential I/O Operations with Files
The file stream classes support a number of member
functions for performing the input and output
operations
The functions get() and put() are capable of handling
a single character at a time.
The function getline() lets you handle multiple
characters at a time.
Another pair of functions i.e., read() and write() are
capable of reading and writing blocks of binary data.
The get(), getline() and put() Functions
That is, get() will read a byte of data and put() will
write a byte of data.
The get() function reads a single character from the
14 associated stream and puts that value in ch.
9  It returns a reference to the stream.
C++ Files
/* C++ Sequential Input/Output Operations fout.close();
with Files */ /* now display the contents of the file
#include<iostream.h> */
#include<fstream.h> ifstream fin;
#include<stdlib.h> fin.open("Aschars", ios::in);
#include<conio.h> fin.seekg(0);
void main() for(i=33; i<128; i++)
{
{
ofstream fout; // create output stream
fin.get(ch); // read a character
char ch;
cout<<i<<" = "; // display the
int line=0;
character
int i;
cout.put((char)(i));
clrscr();
cout<<"\t";
fout.open("Aschars", ios::app) ;
if(!fout) // if fout is zero if(!(i%8))
{ {
cout<<"The file cannot be opened..!!\n"; cout<<"\n"; line++;
cout<<"Press a key to exit...\n";
}
getch();
exit(1);
if(line>22)
} { system("PAUSE");
/* write the characters */ line = 0; }
for(i=33; i<128; i++) }
{ cout<<"\n\nPress a key to exit..\n";
15 fout.put((char)(i));
0 getch();
}
C++ Files
C++ EOF
You can detect when the end of the file is reached by
using the member function eof().
It returns non-zero when the end of file has been
reached, otherwise it returns zero.
For example, consider the following code fragment :
ifstream fin ;
fin.open("master", ios::in | ios::binary);
while(!find.eof()) //as long as eof() is zero
{
//that is, the file's end is not reached :
//process the file
}
if(fin.eof()) //if non-zero
cout << "End of file reached ! \n" ;
15
1
C++ Files
C++ Error Handling During File Operation
Sometimes during file operations, errors may also
creep in.
 For example, a file being opened for reading might not exist.
 Or a file name used for a new file may already exist.
 There might not be enough space in the disk for storing data.
The current state of the I/O system is held in an
integer, in which the following flags are encoded :

15
2
C++ Files
C++ Error Handling During File Operation
There are several error handling functions supported
by class ios that help you read and process the status
recorded in a file stream.
Following table lists these error handling functions and
their meaning :

15
3
LO2 Apply basic OOP principles in the
target language
Object Oriented Programming
The Object Oriented Programming ( OOPs ) can be
defined as a programming model or paradigm that
emphasizes or focus mainly on objects.
The object oriented programming considers data
important rather than actions (functions).
Object Oriented Programming is not a programming
language rather than it is a programming model that
the programming languages follow.
Basic Concepts of OOP
Object - An Object is an identifiable entity with some
characteristics and behavior.
Class - A Class is a group of objects that share
common properties and relationships.
15
4
Class
Fruit
Objects
Apple
Banana
Mang

15
5
The OOP approach is based on certain concepts that
help it attain its goal of overcoming the drawbacks
or shortcomings of conventional programming
approaches.
These general concepts of OOP are given below :
Abstraction
Encapsulation
Modularity
Inheritance
Polymorphism
Abstraction
Abstraction is the concept of simplifying a
real world concept into its essential
elements.
15
6
Abstraction refers to the act of
Encapsulation
Encapsulation is the most fundamental concept of
OOP, it is the way of combining both data and the
functions that operate on that data under a single
unit.
It is the process of grouping or wrapping up of data
and functions to perform actions on the data into
the single unit. The single unit is called a class.
Modularity
The act of partitioning a program into individual
components is called modularity.
The justification for partitioning a program is that
It reduces its complexity to some degree and
It creates a number of well-defined, documented
boundaries within the program.
15
Modularity is the property of a system that has been
7
decomposed into a set of cohesive and loosely
Inheritance
Inheritance is the properties of one class of things to
derive or properties from another class.
It is the process of acquiring the properties of the
base class into the sub class.
Polymorphism
Polymorphism is the key to the power of object
oriented programming, it is so important that
languages that don't support polymorphism cannot
advertise themselves as OO languages.
Polymorphism is the ability for a message or data to
be processed in more than one form.
The advantage offered by OOP are :
Re-use of code
Ease of comprehension
Ease of fabrication and maintenance
15
8 Easy redesign and extension
C++ Function Overloading
When a several function declarations are specified
for a single function name in the same scope, the
(function) name is said to be overloaded.
 C++ allows functions to have the same name if it
can distinguish them by their number and type of
arguments.
For example, following four functions are different in
C++
 float divide(int a, int b);
 float divide(int a, int b, int c);
 float divide(float x, float y);
 float divide(float x, float y, float z);
The key to function overloading is a function's
argument list which is also known as the function
signature.
15 It is the signature, not the function type that enables
9
When a functions name is declared more than once
in a program, the compiler will interpret the second
(and subsequent) declaration(s) as follows:
 if the signatures of subsequent functions match
the previous function's, then the second is treated
as a re-declaration of the first.
 if the signatures of the two functions match
exactly but the return types differ, and is flagged
at compile time as an error.
For example,
o float square(float f);
o double square(float x); // error!!
Functions with the same signature and same
name but different return types are not allowed
in C++.
o float square(float f); // difference signature,
16
0 hence
C++ Function Overloading
void amount(int ti, float ra)
/* C++ Function Overloading*/
{
#include<iostream.h> cout<<"\n\tPrincipal Amount = 2000";
#include<conio.h> cout<<"\t\tTime = "<<ti;
using namspace std; cout<<"\tRate = "<<ra;
void amount(float pr, int ti, float ra) cout<<"\n\tInterest Amount =
"<<(2000*ti*ra)<<"\n";
{
}
cout<<"\n\tPrincipal Amount = "<<pr;
void amount(float pr)
cout<<"\t\tTime = "<<ti<<" years"; {
cout<<"\tRate = "<<ra; cout<<"\n\tPrincipal Amount = "<<pr;
cout<<"\n\tInterest Amount = cout<<"\t\tTime = 2 years";
"<<(pr*ti*ra)<<"\n"; cout<<"\tRate = 0.04";
} cout<<"\n\tInterest Amount =
"<<(pr*2*0.04)<<"\n";
void amount(float pr, int ti)
}
{
int main()
cout<<"\n\tPrincipal Amount = "<<pr; {
cout<<"\t\tTime = "<<ti; cout<<"Results on amount(2000.0F)";
cout<<"\tRate = 0.04"; amount(2000.0F);
cout<<"\n\tInterest Amount = cout<<"\nResults on amount(2500.0F, 3)";
"<<(pr*ti*0.04)<<"\n"; amount(2500.0F, 3);
cout<<"\nResults on amount(2300.0F, 3,
}
0.11F)";
void amount(float pr, float ra) amount(2300.0F, 3, 0.11F);
{ cout<<"\nResults on amount(2, 0.12F)";
cout<<"\n\tPrincipal Amount = "<<pr; amount(2, 0.12F);
cout<<"\nResults on amount(6, 0.07F)";
16 cout<<"\t\tTime = 2 years"; amount(6, 0.07F);
1 cout<<"\tRate = "<<ra; getch();
C++ Classes and Objects
Classes and Objects are the most important
features of C++ .
Class
A class represents a group of similar objects.
A class is a way to bind the data describing an entity
and its associated functions together.
For instance, consider an account having
characteristics account no, type, and balance.
Its associated operations are deposit and
withdrawal.
class Account
{
int accountno;
char type;
float balance;
16 float deposit(float amount) { balance = balance + amount;
2
return balance; }
 C++ Class Declaration
In C++, the declaration of a class involves declaration of its
four associated attributes:
 Data Members are the data type properties that describe the
characteristics of a class. There may be zero or more data
members of any type in a class.
 Members Functions are the set of operations that may be
applied to objects of that class. There may be zero or more
members functions for a class.
 Program Access Levels that control access to members from
within the program. These access levels are private, protected,
or public.
 Class Tag name that serves as a type specifier for the class
using which objects of this class type can be created.
The class specification takes place in the following two
parts:
 class definition
 This doesn't actually define any data, but it does define what
16
the class name means, that is, what an object of the class
3 will consist of and what operations can be performed on such
C++ Classes and Objects
 C++ Class Declaration
Here is the general form of the class definition:
 class class-name
{
 private:
o [variable declarations;]
o [function declarations;]
 protected:
o [variable declarations;]
o [function declarations;]
 public:
o [variable declarations;]
o [function declarations;]
 };
 class Box
 {
 public:
o double length; // Length of a box
o double breadth; // Breadth of a box
o double height; // Height of a box
16
4  };
C++ Class Method's Definition
Members functions can be defined in the following
two places:
 Outside the class definition
 Inside the class definition
Class Method's Definition Outside the Class
Definition
 Member function definition outside the class definition is
much the same as that of function definitions you are familiar
with.
 Here, the only difference is that the name of the function is
the full name of the function also called as qualified-name of
a function which is written as:
 class-name::function-name
 The symbol ::, called the scope resolution operator, specifies
that the scope of the function is restricted to the class class-
name.
 return-type class-name :: function-name(parameter list)
16 {
5
Class Method's Definition Inside the Class
Definition
In this case, you don't need to put the membership
label along with the function name.
For example, we could define the class student as
shown here:
class Student
{
int rollno;
char name[40];
float marks;
void readData()
{
cout<<"Enter roll no: ";
cin>>rollno;
cout<<"Enter name: ";
gets(name);
16 cout<<"Enter marks: ";
6 cin>>marks;
C++ Classes and Objects
do {
 /* C++ Classes and float ITEM::largest(void)
{ cout<<"\nMain Menu\n";
Objects */ float larg=itprice[0]; cout<<"1.Display Largest
#include<iostream.h> Price\n";
for(int i=1; i<5; i++)
#include<conio.h> cout<<"2.Display Sum of
#include<stdlib.h> { Prices\n";
using namespace std; if(larg<itprice[i]) cout<<"3.Display Item List\
class ITEM { larg=itprice[i];} n";
{ } cout<<"4.Exit\n";
int itemcode[5];
return larg; } cout<<"Enter your choice(1-
float itprice[5];
public: float ITEM::sum(void) { 4): ";
void initialize(void); float sum=0; cin>>ch;
float largest(void);
for(int i=0; i<5; i++) { switch(ch) {
float sum(void);
void displayitems(void); sum = sum + case 1: big=order.largest();
}; itprice[i]; } cout<<"Largest Price =
void ITEM::initialize(void) return sum; } "<<big; break;
{
void case 2: tot=order.sum();
for(int i=0; i<5; i++)
TEM::displayitems(voi cout<<"Sum of Prices =
{ d) { "<<tot; break;
cout<<"Item No.:
"<<(i+1); cout<<"\nCode\tPrice\ case 3: order.displayitems();
cout<<"\nEnter item
n"; break;
code: "; for(int i=0; i<5; i++) { case 4:
cin>>itemcode[i]; cout<<"Exiting...press any
cout<<itemcode[i]<<"\
cout<<"Enter item price: t"; key..."; getch(); exit(1);
16 ";
7 cout<<itprice[i]<<"\n"; default:
cin>>itprice[i]; cout<<"\
C++ Scope Rules Pertaining to a
Class
A public member is accessible from
anywhere outside the class but within a
program.
You can set and get the value of public
variables without any member.
A private member variable or function
cannot be accessed, or even viewed
from outside the class.
Only the class and friend functions can
access private members.
A protected member variable or
16
8
function is very similar to a private
C++ Object
When you define a class, it doesn't define or create
objects of that class, rather it only specifies what
types of information the objects of this class type will
be containing.
Define C++ Objects
A class provides the blueprints for objects, so
basically an object is created from a class.
We declare objects of a class with exactly the same
sort of declaration that we declare variables of basic
types.
Following statements declare two objects of class
Box:
 Box Box1; // Declare Box1 of type Box
 Box Box2; // Declare Box2 of type Box

Accessing the Data Members


16
9 The public data members of objects of a class can be
Accessing the Data Members
/* C++ Classes and Objects - // box 1 specification
Example Program */ box1obj.heig = 5.0;
#include<iostream.h> box1obj.leng = 6.0;
box1obj.brea = 7.0;
#include<conio.h>
// box 2 specification
using namespace std; box2obj.heig = 10.0;
class Box box2obj.leng = 12.0;
{ box2obj.brea = 13.0; // calculate
public: volume of box 1
volume = box1obj.heig *
double leng; // Length of a box
box1obj.leng * box1obj.brea;
double brea; // Breadth of a box cout<<"Volume of Box1 =
double heig; // Height of a box "<<volume<<"\n"; // calculate
}; volume of box 2
void main() volume = box2obj.heig *
{ box2obj.leng * box2obj.brea;
cout<<"Volume of Box2 =
Box box1obj; // Declared box1obj of
"<<volume<<"\n";
type Box
getch();
Box box2obj; // Declared box2obj of return 0;
type Box }
double volume = 0.0; // Store the
17
0 volume of a box here
Array of Objects
/* C++ Classes and Objects - Example int main()
Program */ {
#include<iostream.h> int ino;
#include<conio.h> float cost;
class ITEM for(int z=0; z<5; z++)
{ {
int itemno; cout<<"Enter itemno and itemprice
float price; for item "<<z+1<<"\n";
public: cin>>ino>>cost;
void getdata(int i, float f) order[z].getdata(ino, cost);
{ }
itemno=i; cout<<"\n";
price=f;
for(z=0; z<5; z++)
}
void putdata(void) {
{ cout<<"Item "<<z+1<<"\n";
cout<<"Itemno: "<<itemno<<"\t"; order[z].putdata();
cout<<"Price: "<<price<<"\n\n";
}
}
getch();
};
ITEM order[5]; return 0;}
17
1
 Nested Classes in C++ INNER iobj1;
/* C++ Classes and Objects - Example public:
Program */ INNER iobj2;
#include<iostream.h> void second(void)
#include<conio.h> {
#include<stdlib.h> cout<<"\nOUTER::second()\n";
using namespace std; cout<<iobj2.c<<"\n";
class OUTER cout<<"A = "<<a<<"\n";
{ iobj1.print();
int a; }
class INNER OUTER()
{
{ a=25; }
int b;
public: };
int c; void main()
void print(void) {
{
OUTER oobj;
cout<<"\nINNER::print()"<<"\n";
cout<<"b("<<b<<"), c("<<c<<")\n"; oobj.second();
} oobj.iobj2.print();
INNER() getch();
{ return 0;
b=5; c=10;
17 }
2 } };
Destructors
Constructors and Destructors are special member
functions of a class for initializing and disposing of
objects belonging to that class.
C++ Constructor
A member function with the same name as its class
is called as Constructor and it is used to initialize the
objects of that class type with a legal initial value.
It is automatically called when an object is created
of that class.
If a class has a constructor, each object of that class
will be initialized before any use is made of the
object.
 class Student
 {
private :
17 int rollno;
3 float marks;
Destructors
Constructors and Destructors have no return type,
not even void.
A constructor for a class is needed so that the
compiler automatically initializes an object as
soon as it is created.
A class constructor, if defined, is called whenever
a program creates an object of that class.
C++ Constructor Declaration and Definition
It can be defined either inside the class definition or
outside the class definition.
The following code fragment defines a constructor
inside the class definition :
class X {
int i;
public:
17 int j, k;
4
Destructors
A constructor that accepts no parameter is called
the default constructor.
In the previous section, X::X() is the default
constructor for class X since it taken no
parameter.
If a class has no explicit constructor defined, the
compiler will supply a default constructor.
The default constructor provided by the compiler
does not do anything specific.
It simply allocates memory to data members of
object.
A constructor that accepts parameters for its
invocation is known as parameterized constructor.
Declaring a constructor with arguments hides the
17
5
default constructor.
Destructors
class Test
{
int ant;
public :
Test(int i) //constructor with arguments
{
ant = i;
}
//other members
};
int main()
{
Test object1(45); //ok, Argument value provided
Test object2; //Error !! No default constructor available :
}

17
6
Constructors
 The constructor functions have certain special
characteristics.
 These are :
Constructor functions are invoked automatically
when the objects are created.
If a class has a constructor, each object of that class
will be initialized before any use is made of the
object.
No return type (not even void) can be specified for a
constructor.
They cannot be inherited, through a derived class
can call the base class constructor.
A constructor may not be static.
Default constructors and copy constructors are
generated (by the compiler) where needed.
17
7 It is not possible to take the address of a constructor.
Destructors
If a class can have a constructor to set things up,
it should also have a destructor to destruct the
object
A destructor, as the name itself suggests, is used
to destroy the objects that have been created by a
constructor.
A destructor destroys the values of the object
being destroyed.
The name of a destructor, it is ~classname().
The symbol ~ refers to a NOT i.e., a destructor is a
NOT constructor.
A destructor is a member function and can be
defined like any other member function. However,
17
it does not take any argument neither does it
8 return any values.
Destructors
class Sample {
int i, j;
public :
Sample(int a, int b) //constructor
{
i = a;
j = b;
}
~Sample() {
cout << "Destructor at work\n" ;
}
//other members
};
int main() {
Sample s1(3, 4); //local object s1 constructed with values 3 & 4
using Sample()
….
/* automatically s1 is destructed at the end of the block using
17
destructor ~Sample()
9 }
Destructors
The destructors have some special characteristics
associated. These are :
Destructor functions are invoked automatically when
the objects are destroyed.
You can have only one destructor for a class. In other
words, destructors can't be overloaded.
If a class has a destructor, each object of that class
will be de-initialized before the object goes out of
scope.
Destructor functions also, obey the usual access rules
as other member functions do.
No argument can be provided to a destructor, neither
does it return any value.
They cannot be inherited.
A destructor may not be static.
18
0 It is not possible to take the address of a destructor.
C++ Inheritance
Inheritance is the capability of one class to inherit
the properties from another class.
The most important advantage of inheritance is
code reusability.
Once a base class is written and debugged, it can
be used in various situations without having to
redefine it or rewrite it.
Reusing existing code saves times, money, and
efforts also, and increases program's reliability.
Here are several reasons why inheritance was
introduced:
The capability to express the inheritance relationship
which ensures the closeness with the real-world
models.
18 
1 The idea of reusability.
C++ Inheritance
Inheritance may take place in many forms which
are :
Single Inheritance -
 When a sub class inherits only from one base class, known as
single inheritance
Multiple Inheritance -
 When a sub class inherits from multiple base classes, known as
multiple inheritance
Hierarchical Inheritance -
 When many sub classes inherit from a single base class, known
as hierarchical inheritance
Multilevel Inheritance -
 The transitive nature of inheritance is reflected by this form of
inheritance.
 When a sub class inherits from a class that itself inherits from
another class, known as multilevel inheritance
18 
Hybrid Inheritance -
2
1. Single Inheritance
In single inheritance, a class derives from one base
class only. This means that there is only one
subclass that is derived from one superclass.
Single inheritance is usually declared as
follows:
class subclassname : accessspecifier
superclassname
{
//class specific code;
};

18
3
#include <iostream>
#include <string> int main()
using namespace std; {
Dog dog;
class Animal cout<<"Dog has
{ "<<dog.legs<<"
string name=""; legs"<<endl;
public: cout<<"Dog has
int tail=1; "<<dog.tail<<"
tail"<<endl;
int legs=4; cout<<"Dog ";
}; dog.voiceAction();
}
class Dog : public Animal
{
public:
void voiceAction()
{
cout<<"Barks!!!";
}
18};
4
2. Multiple Inheritance -
Multiple inheritance is a type of inheritance in
which a class derives from more than one classes.
As shown in the above diagram, class C is a
subclass that has class A and class B as its parent.
In a real-life scenario, a child inherits from its father
and mother. This can be considered as an example
of multiple inheritance.

18
5
//Result is a combination of
#include <iostream> subject_marks and cocurricular
using namespace std; activities marks
//multiple inheritance example class Result : public student_marks,
class student_marks { public cocurricular_marks {
protected: int total_marks, avg_marks;
int rollNo, marks1, marks2; public:
public: void display()
void get() { {
cout << "Enter the Roll No.: "; cin >> rollNo; total_marks = (marks1 + marks2 +
comarks);
cout << "Enter the two highest marks: "; cin
>> marks1 >> marks2; avg_marks = total_marks / 3;
} cout << "\nRoll No: " << rollNo <<
"\nTotal marks: " << total_marks;
};
cout << "\nAverage marks: " <<
class cocurricular_marks {
avg_marks;
protected:
}
int comarks;
};
public:
int main()
void getsm() {
{
cout << "Enter the mark for CoCurricular
Result res;
Activities: "; cin >> comarks;
18 } res.get(); //read subject marks
6 res.getsm(); //read cocurricular activities
3. Multilevel Inheritance
In multilevel inheritance, a class is derived from
another derived class. This inheritance can have
as many levels as long as our implementation
doesn’t go wayward. In the above diagram, class
C is derived from Class B. Class B
is in turn derived from class A.

18
7
class Puppy:public Dog{
#include <iostream>
public:
#include <string>
void weeping()
using namespace std;
{
class Animal
cout<<"Weeps!!";
{
}
string name="";
};
public:
int main()
int tail=1;
{
int legs=4;
Puppy puppy;
};
cout<<"Puppy has
class Dog : public Animal
"<<puppy.legs<<"
{ legs"<<endl;
public: cout<<"Puppy has
void voiceAction() "<<puppy.tail<<"
{ tail"<<endl;
cout<<"Barks!!!"; cout<<"Puppy ";
18 } puppy.voiceAction();
8
cout<<" Puppy ";
4. Hybrid Inheritance
Hybrid inheritance is usually a combination of more
than one type of inheritance. In the above
representation, we have multiple inheritance (B, C,
and D) and multilevel inheritance (A, B and D) to
get a hybrid inheritance.

18
9
#include <iostream>
#include <string> class result : public marks, public
using namespace std; sports{//Derived class by multiple
//Hybrid inheritance = multilevel + multilpe
inheritance//
class student{ //First base Class int total_marks;
int id; float avg_marks;
string name;
public :
public:
void display(){
void getstudent(){
cout << "Enter student Id and student name"; total_marks=marks_math
cin >> id >> name; +marks_phy+marks_chem;
} avg_marks=total_marks/
}; 3.0;
class marks: public student{ //derived from student
protected:
int marks_math,marks_phy,marks_chem;
cout << "Total marks ="
<< total_marks << endl;
public:
void getmarks(){ cout << "Average marks
cout << "Enter 3 subject marks:"; cin
=" << avg_marks << endl;
>>marks_math>>marks_phy>>marks_chem; cout << "Average + Sports
} marks =" << avg_marks+spmarks;
};
}
class sports{
protected:
};
int spmarks; int main(){
public: result res;//object//
void getsports(){
res.getstudent();
cout << "Enter sports marks:"; cin >> spmarks;
19 res.getmarks();
}
0 res.getsports();
};
5. Hierarchical Inheritance
In hierarchical inheritance, more than one class
inherits from a single base class as shown in the
representation above. This gives it a structure of a
hierarchy.

19
1
#include <iostream> class Square : public Shape // inherit Shape class
using namespace std; {

//hierarchical inheritance example public:

class Shape // shape class -> base class int square_area() {


float area = 4*x;
{
return area;
public:
}
int x,y;
};
int main()
void get_data(int n,int m) {
{ Rectangle r;
x= n;
Triangle t;
y = m; Square s;
} int length,breadth,base,height,side;
}; //area of a Rectangle
class Rectangle : public Shape // inherit Shape class std::cout << "Enter the length and breadth of a rectangle: ";
cin>>length>>breadth;
{
r.get_data(length,breadth);
public:
int rect_area = r.area_rect();
int area_rect() {
std::cout << "Area of the rectangle = " <<rect_area<< std::endl;
int area = x*y;
//area of a triangle
return area;
std::cout << "Enter the base and height of the triangle: ";
} cin>>base>>height;
}; t.get_data(base,height);
class Triangle : public Shape // inherit Shape class float tri_area = t.triangle_area();

{ std::cout <<"Area of the triangle = " << tri_area<<std::endl;

public: //area of a Square


std::cout << "Enter the length of one side of the square: "; cin>>side;
int triangle_area() {
s.get_data(side,side);
float area = 0.5*x*y;
int sq_area = s.square_area();
return area;
19 std::cout <<"Area of the square = " << sq_area<<std::endl;
2
}
return 0;
Inheritance
class BASE2 {
/* C++ Inheritance - c=k;
Example Program */ protected: cout<<"Constructing
int b; DERIVED\n";
#include<iostream.h>
public: }
#include<conio.h> ~DERIVED() {
BASE2(int y) {
using namespace std; b=y; cout<<"Destructing
class BASE1 { cout<<"Constructing DERIVED\n";
protected: BASE2\n"; }
int a; } void show() {
public: ~BASE2() { cout<<"1."<<a<<"\
BASE1(int x) cout<<"Destructing t2."<<b<<"\
{ BASE2\n"; t3."<<c<<"\n";
a=x; } }
cout<<"Constructing };
BASE1\n";
};
class DERIVED:public int main() {
}
BASE2, public BASE1 { DERIVED obj(10,11,12);
~BASE1() {
int c; obj.show();
cout<<"Destructing
BASE1\n"; public: getch();
} DERIVED(int i, int j, int k): return 0;
BASE2(i),BASE1(j) {
};
19 }
3
C++ Data Encapsulation
Encapsulation refers to wrapping up of data and
associated functions into one single unit.
Encapsulation is an Object Oriented Programming
(OOP) concept that binds together the data and the
functions that manipulate the data, and that keeps
both safe from the outside the interference and
misuse.
Data encapsulation led to the important OOP
concept of data hiding.
Here is an example:
class JAVAENCAPSULATIONEXAMPLE {
public:
double getVol(void) {
return len * bre * hei;
}
19
4 private:
C++ Data Encapsulation
cout<<"Subtraction =
/* C++ Data Encapsulation - int getresult() "<<cob.getresult()<<"\
Example Program */ { return res; } n";
#include<iostream.h> private: // hidden from break; case '*':
#include<stdlib.h> outside cob.mulnumber(a, b);
int res; }; cout<<"Multiplication =
#include<conio.h> "<<cob.getresult()<<"\n";
using namespace std; int main() { break;
class CALC { CALC cob; case '/': cob.divnumber(a, b);
int a, b; cout<<"Division =
public:
"<<cob.getresult()<<"\n";
CALC(int i=0) char ch;
break;
{ res=i; } cout<<"Enter two default:
void addnumber(int num1, number: "; cout<<"Wrong
int num2) cin>>a>>b; operator...Exiting..Press a
{ res=num1+num2; } key..";
cout<<"Enter the
getch();
void subnumber(int num1, operator(+,-,/,*): ";
exit(1);
int num2) cin>>ch;
}
{ res=num1-num2; } switch(ch) { getch();
void mulnumber(int num1,
case '+': }
int num2)
cob.addnumber(a, b); getch();
{ res=num1*num2; }
cout<<"Summation = return 0;
void divnumber(int num1, "<<cob.getresult()<<"\
19 int num2) {
}
5
n";
res=num1/num2; }
C++ Polymorphism
In C++, polymorphism means having many forms.
Generally, polymorphism occurs when there is a
hierarchy of the classes and they are related by the
TRIANGLE(int a=0, int
inheritance.
/* C++ Polymorphism - Example
Program */ class RECTANGLE:public b=0):JAVAPOLYMORPHISM
JAVAPOLYMORPHISMEX EXAMPLE(a, b) { }
#include<iostream.h>
AMPLE { int area() {
#include<conio.h>
public: cout<<"Triangle class area\
using namespace std; n";
RECTANGLE(int a=0, int
class b=0):JAVAPOLYMORPHI
JAVAPOLYMORPHISMEXAMPLE
SMEXAMPLE(a, b) { } return(wid*hei/2); }
{
int area() };
protected:
int wid, hei; int main() {
{ cout<<"Rectangle JAVAPOLYMORPHISMEXAMPL
public:
class area\n"; E *sh;
JAVAPOLYMORPHISMEXAMPLE( RECTANGLE rec(10, 7);
int a=0, int b=0)
return(wid*hei);
TRIANGLE tri(10, 5);
{ }
sh = &rec;
wid=a; hei=b; } };
sh->area();
virtual int area() { class TRIANGLE:public
19 sh = &tri;
6 JAVAPOLYMORPHISMEX
cout<<"Parent class area\n";
C++ Data Abstraction
Data abstraction is the process of representing the
essential features without including the
implementation details.
Follow these two steps to provide or hide the
implementation details from outside the world:
Members which are defined with a public label are
accessible to the all parts of the program.
And the members which are defined with a private
label are not accessible to the code that uses the
class.

19
7
C++ Data Abstraction int main() {
/* C++ Data Abstraction - void mulnumber(int
CALC cob;
Example Program */ num1, int num2)
int a, b;
#include<iostream.h> {
cout<<"Enter two
#include<conio.h> res=num1*num2; number: ";
using namespace std; } cin>>a>>b;

class CALC { void divnumber(int cob.addnumber(a, b);


num1, int num2) cout<<"Sum =
public:
{ "<<cob.getresult()<<"\
CALC( int i=0) n";
{ res=num1/num2;
cob.subnumber(a, b);
res=i; } cout<<"Subtract =
} int getresult() "<<cob.getresult()<<"\
void addnumber(int num1, n";
{
int num2) { cob.mulnumber(a, b);
return res;
res=num1+num2; cout<<"Multiply =
} } "<<cob.getresult()<<"\
void subnumber(int num1, private: n";
int num2) { int res; cob.divnumber(a, b);
res=num1-num2; cout<<"Divide =
};
} "<<cob.getresult()<<"\
19 n";
8
getch();
C++ Interfaces
Basically Interface in C++, is used to describe the
behavior of C++ class without talking about a
particular implementation of the same class.
int main() {
class RECTANGLE:public
 Here is an example:JAVAINTERFACEEXAMPL RECTANGLE rob;
/* C++ Interfaces - Example
Program */
#include<iostream.h> E{ TRIANGLE tob;

#include<conio.h> public: int a, b;

using namespace std; int get_area() cout<<"Enter width and


{ height: \n";
class
JAVAINTERFACEEXAMPLE return (wid*hei); cin>>a>>b;
{ } rob.setwidth(a);
public: /* here is a pure virtual }; rob.setheight(b);
function, providing the cout<<"Rectangle Area =
interface framework */ class TRIANGLE:public
JAVAINTERFACEEXAMPL "<<rob.get_area()<<"\
virtual int n";
E{
get_area()=0;
public: tob.setwidth(a);
void setwidth(int wi) {
int get_area() tob.setheight(b);
wid=wi; }
{ cout<<"Triangle Area =
void setheight(int he) { "<<tob.get_area();
return (wid*hei)/2;
19 hei = he; } getch();
9 }
protected:
Thank You!

20
0

You might also like