SlideShare a Scribd company logo
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 1
OBJECT ORIENTED CONCEPTS
Introduction
The programming languages deal with two important aspects – data and algorithm. Data is the main
substance of the program and the algorithms are the methods that use these programs. OOP is the principle
of design and development of programs using the modular approach.

Procedural programming: The procedural programming focuses on processing of
instructions in order to perform a desired computation. Therefore, it emphasizes more on doing things
like algorithms. This programming is lengthy, increases the complexity of program, difficult to
understand and modify the program.
This technique is used in conventional programming languages such as C and Pascal. For example,
procedural programs make use of branching statements, where the flow of control changes its path
according to the result of the test expression.

Structured programming: Structured programming approach was a disciplined approach
which limits the branching to a small set of well-behaved construction (ex: if, if-else, while etc).
The idea of Top-down design is to break a large program into smaller programs. The major drawback is
that it is very difficult to model the real world scenario using this model.

Object oriented programming: Object oriented programming (OOP) is a concept that
combines both the data and the functions that operate on that data into a single unit called the object.
Object is an identifiable entity with some characteristics and behavior. OOP follows bottom-up design
technique. Class is the major concept that plays important role in this approach. Class is a template that
represents a group of objects which share common properties and relationships.

OOPs characteristics: The general concepts of OOPs includes
1. Modularity: Module is a logically self-contained unit that can be tested and executed
independently. Modularity is a technique adopted to divide a complex problem into a number of
self-contained independent programming fragments or modules.
2. Abstraction: Abstraction is an act, which represents the essential features of an entity without
including explanations or any background details about it.
3. Data Encapsulation: Wrapping of data and functions into a single unit is called data
encapsulation. The concept of insulating the data from direct access by the program is called data
hiding.
4. Inheritance: Inheritance is the process by which objects of one class acquires the properties of
the objects of another class. (Or) The process of deriving a new class from the existing class is
called inheritance.
5. Polymorphism: Polymorphism is the ability for a message to be processed in more than one
form. The process of making an operator to exhibit different behaviors in different instances is
known as operator overloading. Using a single function name to perform different types of tasks
is known as function overloading.
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 2
6. Dynamic Binding: Binding means linking of a procedure call to the code to be executed when it
is called. Dynamic binding means binding the procedure call during program run rime.
7. Message Passing: Passing message objects and invoking the function by the object by sending
a message is known as message passing.


OOPs Benefits:
 OOPs model the real world entity very well.
 Inheritance eliminates the redundancy (repetition) of code and hence supports code reusability.
 Data hiding helps to build secured programs.
 Multiple instances (objects) can be created.
 Work can be divided easily.
 OOPs can be easily upgraded from small to large systems.
 Complexity can be easily managed.
 Message passing concept helps the objects to communicate and share data.

OOPs disadvantages:
 OOPs use tricky method to do the programming.
 Special skills such as thinking in terms of design skills, programming skills and object is required
for a programmer.
 Proper planning and design is required before programming using OOPs technique.

OOPs Applications:
 Object oriented databases.
 Hypermedia, expert text and hypertext.
 Artificial intelligence and expert systems.
 Decision support systems and office automation systems.
 Parallel programming and neural networks.
 CAD, CAM, CIM systems.
 Simulation and modeling.
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 3
INTRODUCTION TO C++

History of C++:
 Until 1980, C programming was widely popular, and slowly people started realizing the drawbacks
of this language, at the same time a new programming approach that was Object Oriented
Programming.
 Bjarne Stroustrup and his team at Bell Laboratories (AT&T, USA) to help implement simulation
projects in an object-oriented and efficient way created the C++ programming language.
 C++ is a superset of C because; any valid C program is valid C++ program too but not the vice
versa is not true.
 C++ can make use of existing C software libraries with major addition of “Class Construct”.
 This language was called “C with classes” and later in 1983, Rick Mascitii named it “C++”.
 As the name C++ implies, C++ was derived from the C programming language: ++ is the
increment operator in C.

Characteristics of C++:
 Object-Oriented Programming: It allows the programmer to design applications like a
communication between object rather than on a structured sequence of code. It allows a greater
reusability of code in a more logical and productive way.
 Portability: We can compile the same C++ code in almost any type of computer & operating
system without making any changes.
 Modular Programming: An application’s body in C++ can be made up of several source code
files that are compiled separately and then linked together saving time.
 C Compatibility: Any code written in C can easily be included in a C++ program without making
any changes.
 Speed: The resulting code from a C++ compilation is very efficient due to its duality as high-level
and low-level language.
 Machine independent: It is a Machine Independent Language.
 Flexibility: It is highly flexible language and versatility.
 Wide range of library functions: It has huge library functions; it reduces the code development
time and reduces cost of software development.
 System Software Development: It can be used for developing System Software Viz., Operating
system, Compilers, Editors and Database.

C++ Character Set: Character Set means the valid set of characters that a language can
recognizes. The character set of C++ includes the following:
Alphabets
Upper letters case A, B, C, D... X, Y, Z
Lower letters case a, b, c, d …. x, y, z
Digits 0,1,2,3.......... 9
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 4
Special
Characters
, comma . Period ' Apostrophe
: Colon ; Semicolon ? Question mark
! Exclamation _ Underscore | Pipeline
{Left brace } Right Brace # Hash
[Left bracket ] Right Bracket A
Caret
(Left parenthesis ) Right parenthesis & ampersand
/ Slash  Back slash ~ Tilde
+ Plus sign - Minus Sign < Less Than
* Asterisk % Percentage > Greater Than
C++ Tokens: The smallest individual unit in a program is known as token. These elements help
us to construct statements, definitions, declarations, and so on, which in turn helps us to construct complete
program. Tokens used in C++ are:
 Identifier
 Reserved Keywords
 Constants or Literals
 Punctuators
 Operators

Identifiers: Identifiers is a name given to programming elements such as variables, functions,
arrays, objects, classes, etc. It contains letters, digits and underscore. C++ is a case sensitive; it treats
uppercase and lowercase characters differently.
The following are some valid identifiers:
Student Reg101 a1e2r3 _dos
Rules to be followed while creating identifiers:
 Identifiers are a sequence of characters which should begin with the alphabet either from A-Z
 (Uppercase) or a-z (lowercase) or _ (underscore).
 C++ treats uppercase and lowercase characters differently. For example, DATA is not same
as data.
 No Special character is allowed except underscore “_”.
 Identifier should be single words i.e. blank spaces cannot be included in identifier.
 Reserved Keywords should not be used as identifiers.
 Identifiers should be of reasonable length.

Keywords: Keyword is a predefined word that gives special meaning to the complier. The
programmer is not allowed to change its meaning. These are reserve for special purpose and must not be
used as identifier name.
Example: for, if, else, this, do, float, while, switch etc.
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 5
There are keywords in C++ as mentioned below:

Constants: A constant are identifiers whose value does not change during program execution.
Constants are sometimes referred to as literal.
A constant or literal my be any one of the following:
 Integer Constant
 Floating Constant
 Character Constant
 String Constant

Integer Constant: An integer constant is a whole number, which can be either positive or negative.
They do not have fractional part or exponents. We can specify integer constants in decimal, octal or
hexadecimal form.
 Decimal Integer Constant: It consists of any combination of digits taken from the set 0 to 9.
For example:
int a = 100; //Decimal Constant
int b = -145 // A negative decimal constant
int c = 065 // Leading zero specifies octal constant, not decimal
 Octal Integer Constant: It consists of any combination of digits taken from the set 0 to 7. However
the first digit must be 0, in order to identify the constant as octal number.
For example:
int a = 0123; //Octal Constant
int b = 097; // Error: 9 is not an octal digit.
 Hexadecimal Integer Constant: A Sequence of digits begin the specification with 0X or 0x, followed
by a sequence of digits in the range 0 to 9 and A (a) to F(f).
For example:
int a = 0x234;
int b = -0XABF;
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 6
 Unsigned Constant: To specify an unsigned type, use either u or U suffix. To specify a long type, use
either the l or L suffix.
For example:
unsigned a = 328u; //Unsigned value
long b = 0x7FFFFFL; //Long value specified as hex constant
unsigned long c = 0776745ul; //Unsigned long values as octal constant

Floating Point Constant: Floating-point constants are also called as “real constants”. These values
contain decimal points (.) and can contain exponents. They are used to represent values that will have a
fractional part and can be represented in two forms (i.e. fractional form and exponent form)
 Floating-point constants have a “mantissa”, which specifies the value of the number, an
“exponent” which specifies the magnitude of the number, and an optional suffix that specifies the
constant’s type.
 The mantissa is specified as a sequence of digits followed by a period, followed by an optional
sequence of digits representing the fractional part of the number.
 The exponent, if present, specifies the magnitude of the number as a power of 10.
o Example: 23.46e0 // means it is equal to 23.46 x 100 = 23.46 x 1 = 23.46
 It may be a positive or negative number. A number with no sign is assumed to be a positive number.
o For example, 345.89, 3.142

Character Constants: Character constants are specified as single character enclosed in pair of
single quotation marks.
 For example char ch = ‘P’; //Specifies normal character constant
 A single character constant such as ‘D’ or ‘r’ will have char data type. These character
constants will be assigned numerical values.
 The numerical values are the ASCII values, which are numbered sequentially for both
uppercase and lowercase letters.
 There are certain characters used in C++ which represents character constants. These constants
start with a back slash (  ) followed by a character. They are normally called as escape
sequence. Some of the commonly used escape sequences are.
Escape Sequence Meaning Escape Sequence Meaning
’ Single Quote ” Double Quote
? Question Mark  Back Slash
0 Null Character a Audible Bell
b Backspace f New Page
n New Line r Carriage Return
t Horizontal Tab v Vertical Tab
nnn Arbitrary octal value xnn Arbitrary Hexa Value
 Escape Sequence is a special string used to control output on the monitor, represented by a single
character, and hence occupy one byte.
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 7
String Constants: A string constant consists of zero or more character enclosed by double quotation
marks (“).
 Multiple character constants are called string constants and they are treated as an array of char.
 By default compiler adds a special character called the “Null Character” (0) at the end of the
string to mark the end of the string.
o For example: char str[15] = “C++ Programming” ;
 This is actually represented as char str[15] = “C++ Programming0” in the memory.

Punctuators: Punctuators in C++ have syntactic and semantic meaning to the compiler. Some
punctuators can be either alone or in combination.
The following characters are used as punctuators, which are also known as separators in C++.
Punctuator Name Function
! Exclamation Used along with “=” to indicate “not equal to”
% Percentage Used along with format specifiers
& Ampersand Used to represent address location or bitwise operation
; Semicolon Used to represent statement terminator.
[ ] Brackets Used to array subscripts
() Parenthesis Used to represent function calls and function parameters.
{ } Braces Used to represent start and end of a block of code.
# Ash sign Used to represent preprocessor directives.
 Back slash Used to represent escape sequence
: Colon Used to represent labeled statement
= Equal to Used to represent an assigning operator.
C++ Operators: An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations. C++ is rich in built-in operators and there are almost 45
different operators.
Operators in C++ are can be divided into the following classes:
 Arithmetic Operator
 Relational Operator
 Logical Operator
 Unary Operator
 Conditional Operator
 Bitwise Operator
 Assignment Operator
 Other Operator
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 8
Operator operates on constants and variables, which are called operands. Operators may also be
classified on the number of operands they act on either:
Unary Binary Ternary
Unary operators
Operate on only one
operand.
Binary operator
Operates on two operands.
Ternary operator
Operates on three operands.
Example: ++, - - +, -, *, /, %, &&, || ?:
Unary Operators
Unary operators have only one operand; they are evaluated before any other operation containing
them is evaluated.
The following are the list of unary operators.
Operator Name Function
! Logical NOT
If a condition is true then Logical NOT operator will make
false.
& Address-of Used to give the address of the operand
~ One’s
Complement
Converts 1 to 0 and 0 to 1
*
Pointer
dereference
Used along with the operand to represent the pointer data
+ Unary plus Used to represent a signed positive operand
++ Increment Used to increment an operand by 1
- Unary negation Used to represent a signed negative operand
- - Decrement Used to represent an operand by 1
Increment Operator: Increment operator is used to increasing the value of an integer by one. This is
represented by “++”.
Example: a++, a+1

Decrement Operator: Decrement operator is used to decreasing the value of an integer by one. This
is represented by “--”.
Example: a--, a-1
Both the increment & decrement operators come in two versions:
Prefix increment/decrement: When an increment or decrement operator precedes its operand, it is
called prefix increment or decrement (or pre-increment / decrement).
 In prefix increment/decrement, C++ performs the increment or decrement operation before using
the value of the operand.
 Example: If sum = 10 and count =20 then
Sum = sum + (++count);
 First count incremented and then evaluate sum = 31.
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 9
Postfix increment/decrement: When an increment or decrement operator follows its operand, it is
called postfix increment or decrement (or post-increment / decrement).
 In postfix increment/decrement, C++ first uses the value of the operand in evaluating the
expression before incrementing or decrementing the operand’s value.
 Example: If sum = 10 and count =20 then
Sum = sum + (count++);
 First evaluate sum = 30, and then increment count to 21.

Binary Operators: The binary operators are those operators that operate on two operands.
They are as Arithmetic, Relational, Logical, Bitwise, and Assignment operators.

Arithmetic Operator: Arithmetic operators are used to performing the basic arithmetic
operations such as arithmetic, subtraction, multiplication, division and modulo division (remainder after
division).
Operator Description Example( a=10, b=20)
+ Adds two operand a + b = 30
- Subtracts second operand from the first a - b = -10
* Multiply both operand a * b = 200
/ Divide numerator by denominators b / a = 2
%
Modulus operators and remainder of after an
integer division
b % a = 0
Relational Operator: Relational Operator is used to comparing two operands given in
expressions. They define the relationship that exists between two constants.
 For example, we may compare the age of two persons or the price of two items….these
comparisons can be done with the help of relational operators.
 The result in either TRUE(1) or FALSE(0).Some of the relational operators are:
Operator Description Example (a=10, b=5)
<
Checks if the value of left operand is less than the
value of right operand
a < b returns false(0)
<=
Checks if the value of left operand is less than or equal
to the value of right operand a <= b returns false(0)
>
Checks if the value of left operand is greater than the
value of right operand
a > b returns true(1)
>=
Checks if the value of left operand is greater than or
equal to the value of right operand a >= b returns false(0)
= = Checks if the value of two operands is equal or not a = = b returns false(0)
! = Checks if the value of two operands is equal or not a ! = b returns true(1)
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 10
Logical Operators: Logical operators are used to testing more than one condition and make
decisions.
Some of the logical operators are
Operator Meaning Description Example
&& Logical AND
If both the operands are non-zero
then condition becomes true.
If a=10 and b=5 then,
((a==10) && (b>5)) returns false.
|| Logical OR
If any of the two operands is nonzero
then condition becomes true.
If a=10 and b=5 then,
((a==10) || (b>5)) returns true.
! Logical NOT
If a condition is true then the Logical
NOT operator will make false.
If a=10 then,
!(a==10) returns false.
Bitwise Operators: A bitwise operator works on bits and performs bit-by-bit operation.
Bitwise operators are used in bit level programming.
Operators Meaning of operators
& Bitwise AND
1 Bitwise OR
A Bitwise exclusive OR
~ Bitwise complement
Assignment Operators: The most common assignment operator is =. This operator assigns
the value on the right side to the left side.
Example: var = 5 //5 is assigned to var
a = b; //value of b is assigned to a
5 = b; // Error! 5 is a constant.

C++ Shorthand’s: C++ Offers special shorthand is that simplify the coding of a certain type of
assignment statements.
The general format of C++ shorthand’s is:
Variable Operator = Expression
Following are some examples of C++ shorthand’s:
x - = 10; Equivalent to x = x - 10;
x * = 5; Equivalent to x = x * 5;
x / = 2 ; Equivalent to x = x / 2;
x % = z; Equivalent to x = x % z;
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 11
Conditional Operator: A ternary operator pair ”?:” is available in C++ to construct
conditional expressions of the form:
exp1? exp2: exp3, where exp1, exp2, and exp3 are expressions,
The operator “?:” works as follows: exp1 is evaluated first. If it is true, then the expression exp 2 is
evaluated and becomes the value of the expression. If exp1 is false, exp3 is evaluated and its value
becomes the value of the expression.
Example: a=10; b=5;
x = (a>b) ? a:b;
Special Operator:
Operators Meaning of operators
sizeof() It is a unary operator which is used in finding the size of the data type.
Example: sizeof(a)
, (comma) Comma operators are used to linking related expressions together.
Example: int a=10, b=5
. (dot) and ->
(arrow)
Member Operator used to reference individual members of classes,
structure and unions.
cast Casting Operator convert one data type to another.
& Address Operator & returns the address of the variable.
* Pointer Operator * is pointer to a variable.
Precedence of Operators or Hierarchy of Operators In C++:
 An expression is a combination of opcode and operand.
 The operators would be arithmetic, relational, and logical operators.
 If the expression contains multiple operators, the order in which operations carried out is called
the precedence of operators. It is also called as priority or hierarchy.
 The Operators with highest precedence appear at the top of the table and those with the lowest
appear at the bottom.
Category Operator Associativity
Postfix ( ) [ ]-> . ++-- Left to Right
Unary = - ! ~ ++ -- (type) * & sizeof Right to Left
Multiplicative */ % Left to Right
Additive + - Left to Right
Shift << >> Left to Right
Relational <<= >>= Left to Right
Equality == != Left to Right
Bitwise AND & Left to Right
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 12
Bitwise XOR ^ Left to Right
Bitwise OR 1 Left to Right
Logical AND && Left to Right
Logical OR II Left to Right
Conditional ?: Right to Left
Assignment = += _= *= /= %= Right to Left
What is operator precedence in C++?
 “The order in which different types of operators are evaluated is called as operator precedence”.
 It is also known as hierarchy of operators.
 In any expression, Operators having higher precedence are evaluated first.
 The expression is evaluated in the following sequence.
o Arithmetic
o Relational
o Logical
 There are some operators, which are given below. The higher the position of an operator is,
higher is its priority.
Operator Meaning
! Logical NOT
( ) Parenthesis
+, -, *, /, % Arithmetic and modulus
<, >, <=, >= Relational
&& Logical AND
II Logical OR
= Assignment
Type Conversion: Converting an expression of a given type into another type is known as type-
casting or type conversion.
Type conversions are of two types, they are:
 Implicit Conversion
 Explicit Conversion

Implicit Conversion: Implicit Conversions do not require any operator. They are automatically
performed when a value is copied to a compatible type.
 The C++ compiler will implicitly convert or promote values if it can be done safely.
 If not it will generate a warning or an error depending on the conversion required.
 For Example:
short a = 2000;
int b;
b = a;
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 13
Explicit Conversion: C++ is a strong-typed language. Many conversions, especially those that
imply a different interpretation of the value, require an explicit conversion.
 For Example:
short a = 2000;
int b;
b = (int) a; //c-like cast notation
b = int (a) // functional notation
 Implicit Conversions do not require any operator.

Translating a C++ program:


General Structure of C++ Program:
General Syntax Example Program
/* General Structure */
Pre-processor Directives
main ( )
{
Variable Declarations;
Executable Statements;
}
/* A Simple Program to display a Message * /
#include<iostream.h>
void main( )
{
cout<<” This is the first C++ Program”;
}
Different programming languages have their own format of coding. The basic components of a
C++program are:

Object Oriented Concepts & C++ Programming
Prof. K Adisesha 14
Comments or Documentation Section: Comments are the pieces of code that compiler ignores to
compile.
There are two types of comments in C++.
1. Single line comment: The comments that begin with // are single line comments. The Compiler
simply ignores everything following // in the same line.
2. Multiline comment: The multiline comment begin with /* and end with */ . This means everything
that falls between /* and */ is consider a comment even though it is spread across many lines.

Pre-processor Directives (Linker Section): The linker section begins with a hash (#) symbol.
#include……is a preprocessor directive.
 It is a signal for preprocessor, which runs the compiler.
 The statement directs the compiler to include the header file from the C++ Standard library.
 Example:
# include<iostream.h>
#include<conio.h>
# include<math.h>

Definition: In this section, we can define constants, expressions, structures, functions, classes and
objects. After the linker section gets executed, the definition section is executed by the compiler and this
section is optional.
 Example: # define PI 3.14

Global Declaration: We can declare variables here and those variables, which are declared before
the main function or any other function then the life or scope of such variables, remain throughout function
and can be used by other functions of the program.

main ( ) function: As the name itself indicates, this is the main function of every C++ program.
Execution of a C++ program starts with main ( ).
 No C++ program is executed without the main () function.
 The function main () should be written in the lowercase letter and shouldn’t be terminated with a
semicolon.
 It calls other library functions and user-defined functions.
 There must be one and only main ( ) in every C++ program.

Braces { }: The statements inside any function including the main ( ) function is enclosed with the
opening and the closing braces.
{
…………..;
…………..;
}

Declarations: The declaration is the part of the C++ program where all the variables, arrays, and
functions are declared with their basic data types. This helps the compiler to allocate the memory space
inside the computer memory.
Example:
int sum, x, y;

Object Oriented Concepts & C++ Programming
Prof. K Adisesha 15
Statements: These are instructions to the computer to perform some specific operations. These
statements can be expressions, input-output functions, conditional statements, looping statements,
function call and so on. They also include comments.
 Every statement end with semicolon “;” except control statements.
 Semicolon “;” also known as Terminator.
Example: A Simple C++ program to display a message on the screen:
#include<iostream.h>
#include<conio.h>
void main ()
{
clrscr();
cout<< “Welcome to Computer Science Class”;
getch();
}
The program produces following output:
Welcome to Computer Science Class

Library Function: C++ provides many built-in functions that save the programming time.
They include mathematical functions, character functions, string functions, and console input-output
functions.


Mathematical Function: Some of the important mathematical functions in header file math.h
are
Function Meaning
sqrt(x) Square Root of X
pow(x, y) x raised to the power y
sin(x) Sine of an angle x (measured in radians)
cos(x) Cosine of an angle x (measured in radians)
tan(x) Tangent of an angle x (measured in radians)
asin(x) Sin-1
(x) where x (measured in radians)
acos(x) Cos-1
(x) where x (measured in radians)
exp(x) Exponential function of x (ex)
log(x) Logarithm of x
log 10(x) Logarithm of number x to base 10
abs(x) Absolute value of integer number x
fabs(x) Absolute value of real number x
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 16
Character Function: Some of the important mathematical functions in header file ctype.h are:
Function Meaning
isalpha(c) It returns True if C is an uppercase letter and false if c is lowercase.
isdigit(c) It returns True if c is a digit (0 to 9) otherwise false
isalnum(c)
It returns True if c is digit from 0 through 9 or an alphabetic character
(either uppercase or lowercase) otherwise false
islower(c) It returns True if c is a lowercase letter otherwise False
isupper(c) It returns True if c is a uppercase letter otherwise False
toupper(c) It converts c to uppercase letter
tolower(c) It converts c to lowercase letter.
String Function: Some of the important mathematical functions in header file string.h are
Function Meaning
strlen(s) It gives the no. of characters including spaces present in a string
s.
strcat(s1, s2)
It concatenates the string s2 onto the end of the string s1. The
string s1 must have enough locations to hold s2.
strcpy(s1, s2)
It copies character string s2 to string s1. The s1 must have
enough
storage locations to hold s2.
strcmp((s1,s2)==0)
strcmp((s1,s2)>0)
strcmp((s1,s2)<0)
It compares s1 and s2 and find out whether s1 equal s2,
greater than s2 or s1 less than s2.
strcmpi ((s1,s2)==0)
strcmpi((s1,s2)>0)
strcmpi((s1,s2)<0)
It compares s1 and s2 ignoring case and find out whether s1
equal s2, greater than s2 or s1 less than s2.
strrev(s) It converts a string into its reverse.
strupr(s) It converts a string s into upper case.
strlwr(s) It converts a string into lower case.
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 17
Console I/O Function: Some of the important mathematical functions in header file stdio.h
are
Function Meaning
getchar()
It returns a single character from a standard input device (keyboard). It takes no
parameter and the returned value is the input character.
putchar() It takes one argument, which is the character to be sent to the output device. It also
returns this character as a result.
gets() It gets a string terminated by a newline character from the standard input
stream stdlin.puts() It takes a string which is to be sent to output device.
General Purpose standard Library Function: Some of the important mathematical
functions in header file stdio.h are
Function Meaning
randomize() It initialize/seeds the random number generator with a random number.
random(n) It generates a random number between 0 to n-1.
atoi(s) It converts string s into a numerical representation.
itoa(n) It converts a number to a string.
Some more Function:
 getch( ) and getche( ) functions
 On execution, the cursor blinks, the user must type a character and press enter key.
 The value of the character returned from getche( ) is assigned to ch.
 The getche( ) function echoes the character on the screen.
 Another function, getch( ), is similar to getche( ) but does not echo character to the screen.
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 18
DATA TYPES
Introduction
To understand any programming languages we need to first understand the elementary concepts, which
form the building block of that program. The basic building blocks include the variables, data types etc.
C++ provides a set of data types to handle the data that is used by the program.

Variable: A variable is an object or element and it is allowed change during the execution of
the program. Variable represents the name of the memory location. The variable_name is an identifier.
These variables are used to denote constants, arrays, function, structures, classes and files. The variables
are named storage location whose values can be manipulated during program run.
Declaration of a variable: The syntax for declaring a variable is:
datatype variable_name;
Some valid variables are:
reg_no, marks, name, stud, dob;
Some invalid variables are:
 Double - keyword cannot be name of the variable.
 Total marks - empty spaces are not allowed between variables names
 2student - variable name should be begin with an alphabet
 ?result - variable should begin with alphabet or underscore only.

Initializing a variable: The syntax to initialize a variable is:
data_type variable_name = value;
Example: int b = 100;
There are two values associated with a variable known as lvaue and rvalue. It means, for example,
 let p be a variable declared of the type int. then int p = 100; Here, name of the variable is p
o values assigned to variable is 100 i.e. rvalue
o memory address location is 2000 i.e. lvalue
 Lvalue is the location value. It holds the memory address location at which the data value is
stored.
 Rvalue is the data value. It holds the value assigned to the variable by the programmer i.e.
Rvalue of p = 100.

Data Types: Data Types can be defined as the set of values, which can be stored in a variable
along with the operations that can be performed on those values.
 C++ defines several types of data and each type has unique characteristics.
 C++ data types can be classified as:
1. The fundamental data type(built-in data)
2. Derived Data type
3. User-defined data type

 The simple or fundamental data types are the primary data types, which are not composed of any
other data types.
 The simple data types/fundamental data types include int, char, float, double and void.
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 19

The int type: The int type is used to store integers. Integers are whole numbers without any fractional
parts. This includes number such as:
 1, 45 and -9 are integers. 5.2 is not an integer because it contains a decimal point.
 The integer can be positive or negative values and the ranges of number we can store are from -
32786 to 32767.
 An integer is allocated 2 bytes (16 bits) of memory space.
 The possible operations include addition, subtraction, multiplication, division, remainder etc.
 The General form of an integer declaration is: int variable_name;
 Example: int a, b=5;

The char type: It is character data type to store any character from the basic character set.
Characters are enclosed in single quotation marks (‘). ‘A’, ‘a’, ‘b’, ‘9’, ‘+’ etc. are character
constants.
 When a variable of type char is declared, the compiler converts the character to its equivalent
ASCII code.
 A character is allocated only 1 byte (8 bits) of memory space.
 A character is represented in a program by the keyboard char.
 The general form of a character declaration is: char variable_list;
 Example: char alpha=’a’;

The float type: This represents the number with fractional part i.e. real numbers. The float type is
used to store real numbers. Number such as 1.8, 4.5, 12e-5 and -9.66 are all floating-point numbers.
It can also be both positive and negative. The range of numbers we can store from -34e-38 to 3.4e38. Float
is allocated 4 bytes (32 bits) of memory space.
 The general form of a float declaration is: float variable_name;
 Example: float a=5.5;
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 20
The double type: The double and float are very similar. The float type allows you to store single
precision floating point numbers, while the double keyword allows you to store double precision floating-
point numbers. Its size is typically 8 bytes of memory space. The range of numbers we can store are from
-1.7e308 to 1.7e308.
 The general form of a double declaration is: double variable_list;
 Example: double a = 5.5e-7; //a is equivalent to 5.5x10-7

The void type: The void data type has no values and no operations. In other words, both the set of
values and set of operations are empty.
 Example: void main( )
 In this declaration the main function does not return any value.

The bool type: The bool type has logical value true or false. The identifier true has the value 1, and
the identifier false has the value 0.
 The general form of a bool declaration is: bool variable_name;
 Example: bool legal_age=true;
 The statement legal_age= (age>=21); assigns the value true if age is greater than or equal to 21 or
else it returns the value false.

Derived data types: These data types are constructed using simple or fundamental data types.
This includes arrays, functions, pointers and references.

User defined data types: These data types are also constructed using simple or fundamental
data types. Some user defined data types include
 Enumerated
 Structure
 Union
 Class

Enumerated data type: AN enumeration is a user defined type consisting of a set of named
constants called enumerators.
 enum is a keyword that assigns values 0, 1, 2…… automatically.
 This helps in providing an alternative means for creating symbolic constants.
 The syntax for enum is as follows:
o enum [tag] { enum – list} ; //for definition for enumerated type
 Example : enum choice { bad, satisfactory, good, very_good};
choice mychoice;
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 21
INPUT AND OUTPUT OPERATORS

Introduction: The input output operations are done using library functions cin and cout objects
of the class iostream. Using the standard input and output library, we will able to interact with the user by
printing message on the screen and getting the user’s input from the keyboard.
 A stream is an object where a program can either insert/extract characters to/from it.
 The standard C++ library includes the header file iostream, where the standard input and output
stream objects are declared.

Input Operator “>>”: The standard input device is usually the keyboard. Input in C++ is done
by using the “stream extraction” (>>) on the cin stream. “cin” stands for “console input”.

 The operator must be followed by the variable that will store the data that is going to be extracted
from the stream.
 Example:
int age;
cin>>age;
 The first statement declares a variable of the type int called age, and the second one waits for an
input from cin (the keyboard) in order to store it in this integer variable.
 It can only process the input from the keyboard once the RETURN key has been pressed.
 We must always consider the type of the variable that we are using as a container with cin
extraction. For example, if we request an integer we will get an integer.

Output Operator “<<”: The standard output device is the screen (Monitor). Outputting in C++
is done by using the object followed by the “stream insertion” (<<). “cout” stands for console output.
Example:
cout<<”Let us learn C++”; // prints Let us learn C++ on the screen.
 The << operator inserts the data that follows it into the stream preceding it.
 The sentence in the instruction is enclosed between double quotes ( ” ), because it is constant string
of characters.
 Whenever we want to use constant strings of characters we must enclose them between double
quotes (“) so that they can be clearly distinguished from the variables name.
Example:
cout<<”sum”; //prints sum
cout<<sum; //prints the content of the variable sum
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 22
Cascading of I/O Operators: C++ supports the use of stream extraction (>>) and stream
insertion (<<) operator many times in a single input (cin) and output (cout) statements. If a program
requires more than one input variable then it is possible to input these variables in a single cin statement
using multiple stream extraction operators. Similarly, when we want to output more than one result then
this can be done using a single cout statement with multiple stream insertion operators. This is called
cascading of input output operators.
Example:
cout<<”Enter the first number”;
cin>>a;
cout<<”Enter the second number”;
cin>>b;
Instead of using cin statement twice, we can use a single cin statement and input the two numbers
using multiple stream extraction operators.
cout<<”Enter the two number”;
cin>>a>>b;
Similarly, we can even output multiple results in a single cout statements using cascading of stream
insertion operators.
cout<<”The sum of two number is”<<sum<<endl;

Formatted Output (Manipulators): Manipulators are the operators used with the insertion
operator << to format the data display. The most commonly used manipulators are “endl” and “setw”.
In order to use this manipulator, it is must to include header file iomanip.h
 The endl manipulator : The endl manipulator, when used in a output statement , causes a line feed
to be inserted. It has same effect as using new line character “n”.
cout<< “ Narayana PU Science College”<<endl;
cout<< “ Bangalore”;
o The output of the above code will be:
Narayana PU Science College
Bangalore
 The setw( ) Manipulator : The setw( ) manipulator sets the width of the field assign for the output. It
takes the size of the field (in number of character) as a parameter. The output will be right justified.
Example the code :
cout<<setw(6)<<”R” ;
 Generates the following output on the screen (each underscore represent a blank space)
_ _ _ _ _ R
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 23
Program: To fins the sum of two numbers:
#include<iostream.h>
#include<conio.h>
void main( )
{
int a, b, add;
clrscr( );
cout<<”Enter the two numbers”;
cin>>a>>b;
add = a + b;
cout<<”The sum of two number is”<<sum<<endl;
getch();
}
Program: Convert the temperature in
Fahrenheit into Celsius:
#include<iostream.h>
#include<conio.h>
void main( )
{
float fah, cel;
clrscr( );
cout<<”Enter the value of Fahrenheit”;
cin>>fah;
cel = ((5.0/9.0) * fah – 32.0);
cout<<fah<<”F = ”<<cel<<” C”<<endl;
getch();
}
Program: To interchange the values of two
variables using third variable.
#include<iostream.h>
#include<conio.h>
void main( )
{
int a, b, temp;
clrscr( );
cout<<”Enter the two numbers”;
cin>>a>>b;
cout<<”Before Interchanging : a = “<<a
<<” and b = “<<b<<endl;
temp = a;
a = b;
b = temp;
cout<<”After Interchanging : a = “ <<a<<endl;
cout<<”After Interchanging : b = “ <<b<<endl;
getch();
}
Program: To interchange the values of two
variables without using third variable.
#include<iostream.h>
#include<conio.h>
void main( )
{
int a, b;
clrscr( );
cout<<”Enter the two numbers”;
cin>>a>>b;
cout<<”Before Interchanging : a = “<<a
<<” and b = “<<b<<endl;
a = a + b ;
b = a – b ;
a = a – b ;
cout<<”After Interchanging : a = “ <<a<<endl;
cout<<”After Interchanging : b = “ <<b<<endl;
getch();
}
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 24
Program: To find the area and circumference
of a circle.
#include<iostream.h>
#include<conio.h>
void main( )
{
float rad, area, circum;
clrscr( );
cout<<”Enter the radius”;
cin>>rad;
area = 3.142 * rad * rad;
circum = 2 * 3.142 * rad;
cout<<”Area of circle = “<<area<<endl;
cout<<”Circumference of circle =
“<<circum<<endl;
getch();
}
Program: To find the area of triangle given
three sides.
#include<iostream.h>
#include<conio.h>
#include<math.h>
void main( )
{
float s1, s2, s3, s, area;
clrscr( );
cout<<”Enter the length of three sides”;
cin>>s1>>s2>>s3;
s = (s1 + s2+ s3)/2;
area = sqrt( s* (s-s1) * (s-s2) * (ss3));
cout<<”Area of triangle = “<<area<<endl;
getch();
}
Program: To convert days into years, months
and days.
#include<iostream.h>
#include<conio.h>
void main( )
{
int totaldays, days, year, month;
clrscr( );
cout<<”Enter the total days”;
cin>>totaldays;
year = totaldays/365;
totaldays = totaldays % 365;
month = totaldays/30;
days = totaldays % 30;
cout<<”Years = “<< years<<endl;
cout<<”Months = “<<month<<endl;
cout<<”Days = “<<days<<endl;
getch();
}
Program: To convert seconds into hours,
minutes and seconds.
#include<iostream.h>
#include<conio.h>
void main( )
{
int totalsec, min, hrs, secs;
clrscr( );
cout<<”Enter the total seconds”;
cin>>totalsec;
hrs = totalsec / 3600;
totalsec = totalsec % 3600;
min = totalsec/60;
secs = totalsec % 60;
cout<<”Hours = “<<hrs<<endl;
cout<<”Minutes = “<<min<<endl;
cout<<”Seconds = “<< secs<<endl;
getch();
}
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 25
CONTROL STATEMENTS
 Introduction
Control statements are statements that alter the sequence of flow of instructions. Any single input
statement, assignment and output statement is simple statement. A group of statement that are separated
by semicolon and enclosed within curled braces { and } is called a block or compound statement. The
order in which statements are executed in a program is called flow of control.

Types of control statements: C++ supports two basic control statements.
o Selection statements
o Iteration statements

Selection Statements: This statement allows us to select a statement or set of statements for
execution based on some condition. It is also known as conditional statement. This structure helps the
programmer to take appropriate decision.
The different selection statements, viz.
o if statement
o if – else statement
o Nested – if statement
o switch statement

if statement: This is the simplest form of if statement. This statement is also called as one-way
branching. This statement is used to decide whether a statement or set of statements should be executed
or not. The decision is based on a condition which can be evaluated to TRUE or FALSE.
The general form of simple – if statement is:
if (Test Condition) // This Condition is true
Statement 1;
Statement 2;
 Here, the test condition is tested which results in either a TRUE or
FALSE value. If the result of the test condition is TRUE then the
Statement 1 is executed. Otherwise, Statement 2 is executed.
 Example:
if( amount > = 5000 )
discount = amount * (10/100);
net-amount = amount – discount;
Write a C++ program to find the largest, smallest and second largest of three numbers using simple
if statement.
#include<iostream.h>
#include<conio.h>
void main( )
{
int a, b, c;
int largest, smallest, seclargest;
clrscr( );
cout<<”Enter the three numbers”<<endl;
cin>>a>>b>>c;
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 26
largest = a; //Assume first number as largest
if(b>largest)
largest = b;
if(c>largest)
largest = c;
smallest = a; //Assume first number as smallest
if(b<smallest)
smallest = b;
if(c<smallest)
smallest = c;
seclargest = (a + b + c) – (largest + smallest);
cout<<”Smallest Number is = “<<smallest<<endl;
cout<<”Second Largest Number is = “<<seclargest<<endl;
cout<<”Largest Number is = “<< largest<<endl;
getch( );
}
Write a C++ program to input the total amount in a bill, if the amount is greater than 1000, a
discount of 8% is given. Otherwise, no discount is given. Output the total amount, discount and the
final amount. Use simple if statement.
#include<iostream.h>
#include<conio.h>
void main( )
{
float TAmount, discount, FAmount ;
clrscr( );
cout<<”Enter the Total Amount”<<endl;
cin>>TAmount;
discount = 0; //Calculate Discount
if(TAmount>1000)
Discount = (8/100) * TAmount;
FAmount = TAmount – Discount //Calculate Final Amount
cout<<”Toatal Amount = “<<TAmount<<endl;
cout<<”Discount = “<<discount<<endl;
cout<<”Final Amount = “<< FAmount<<endl;
getch( );
}

if – else statement: This structure helps to decide whether a set of statements should be executed or
another set of statements should be executed. This statement is also called as two-way branching.
The general form of if – else statement is:
if (Test Condition)
Statement 1;
else
Statement 2;
Here, the test condition is tested. If the test condition is TRUE,
statement-1 is executed; otherwise, Statement 2 is executed.
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 27
Write a C++ program to check whether a given year is a leap year not, Using if - else statement.
#include<iostream.h>
#include<conio.h>
void main( )
{
int year ;
clrscr( );
cout<<”Enter the Year in the form YYYY”<<endl;
cin>>year;
if(year%4 ==0 && year%100!=0 || year%400 ==0)
cout<<year<<” is a leap year”<<endl;
else
cout<<year<<” is not leap year”<<endl;
getch( );
}
Write a C++ program to accept a character. Determine whether the character is a lower-case or
upper-case letter.
#include<iostream.h>
#include<conio.h>
void main( )
{
char ch ;
clrscr( );
cout<<”Enter the Character”<<endl;
cin>>ch;
if(ch>= ‘A’ && ch <=’Z’)
cout<<ch<<” is an Upper-Case Character”<<endl;
else
if(ch>= ‘a’ && ch <=’z’)
cout<<ch<<” is an Lower-Case Character”<<endl;
else
cout<<ch<<” is not an alphabet”<<endl;
getch( );
}

Nested if statement : If the statement of an if statement is another if statement then such an if
statement is called as Nested-if Statement. Nested-if statement contains an if statement within another if
statement.
There are two forms of nested if statements.

if – else - if statement : This structure helps the programmer to decide the execution of a statement
from multiple statements based on a condition. There will be more than one condition to test. This
statement is also called as multiple-way branch.

Object Oriented Concepts & C++ Programming
Prof. K Adisesha 28
The general form of if – else – if statement is:
if (Test Condition 1)
Statement 1;
else
if (Test Condition 2)
Statement 2;
else
………..
else
if( test Condition N)
Statement N;
else
Default Statement;
Here, Condition 1 is tested. If it is TRUE, Statement 1
is executed control transferred out of the structure.
Otherwise, Condition 2 is tested. If it is TRUE, Statement 2 is executed control is transferred out of the
structure and so on. If none of the condition is satisfied, a statement called default statement is executed.
Write a C++ program to input the number of units of electricity consumed in a house and calculate
the final amount using nested-if statement. Use the following data for calculation.
Units consumed Cost
< 30 Rs. 3.50 / Unit
>= 30 and < 50 Rs. 4.25 / Unit
>= 50 and < 100 Rs. 5.25 / Unit
>= 100 Rs. 5.85 / Unit
#include<iostream.h>
#include<conio.h>
void main( )
{
int units ;
float Billamount;
clrscr( );
cout<<”Enter the number of units consumed”<<endl;
cin>>units;
if(units < 30)
Billamount = units * 3.50 ;
else
if(units < 50)
Billamount = 29 * 3.50 + (units – 29) * 4.25 ;
else if(units < 100)
Billamount = 29 * 3.50 + 20 * 4.25 + (units – 49) * 5.25 ;
else
Billamount = 29 * 3.50 + 20 * 4.25 + 50 * 5.25 + (units – 99) * 5.85 ;
cout<<”Total Units Consumed =”<<units<<endl;
cout<<”Toatl Amount = “<<Billamount<<endl;
getch( );
}
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 29
Switch Statement : C++ has built in multiple-branch selection statement i.e. switch. If there are more
than two alternatives to be selected, multiple selection construct is used.
The general form of Switch statement is:
Switch ( Expression )
{
Case Label-1: Statement 1;
Break;
Case Label-2: Statement 1;
Break;
…………..
Case Label-N: Statement N;
Break;
Default : Default- Statement;
}


Ex: To find the name of the day given the day number
switch ( dayno )
{
Case 1: cout<< “Sunday”<<endl;
break;
Case 2: cout<< “Monday” <<endl;
break;
Case 3: cout<< “Tuesday” <<endl;
break;
Case 4: cout<< “Wednesday” <<endl;
break;
Case 5: cout<< “Thursday” <<endl;
break;
Case 6: cout<< “Friday” <<endl;
break;
Case 7: cout<< “Saturday” <<endl;
break;
default: cout<< “Invalid Day Number” <<endl;
}
 The switch statement is a bit peculiar within the C++ language because it uses labels instead of blocks.
 This force up to put break statements after the group of statements that we want to execute for a
specific condition.
 Otherwise, the remainder statements including those corresponding to other labels also are executed
until the end of the switch selective block or a break statement is reached.
Write a C++ program to input the marks of four subjects. Calculate the total percentage and output
the result as either “First Class” or “Second Class” or “Pass Class” or “Fail” using switch statement.
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 30
Class Range (%)
First Class Between 60% to 100%
Second Class Between 50% to 59%
Pass Class Between 40% to 49%
Fail Less than 40%
#include<iostream.h>
#include<conio.h>
void main( )
{
int m1, m2, m3, m4, total, choice;
float per;
clrscr( );
cout<<”Enter the First subject marks”<<endl;
cin>>m1;
cout<<”Enter the Second subject marks”<<endl;
cin>>m2;
cout<<”Enter the Third subject marks”<<endl;
cin>>m3;
cout<<”Enter the Fourth subject marks”<<endl;
cin>>m4;
total = m1 + m2 + m3 + m4;
per = (total / 400) * 100;
cout<<”Percentage = “<<per<<endl;
choice = (int) per/10;
cout<<”The result of the student is: “<<endl;
switch(choice)
{
case 10:
case 9:
case 8:
case 7:
case 6: cout<<”First Class ”<<endl;
break;
case 5: cout<<”Second Class”<<endl;
break;
case 4: cout<<”Pass Class”<<endl;
break;
default: cout<<”Fail”<<end;
}
getch( );
}

Iterative Constructs or Looping: Iterative statements are the statements that are used to
repeatedly execute a sequence of statements until some condition is satisfied or a given number of times.
The process of repeated execution of a sequence of statements until some condition is satisfied is called
as iteration, repetition, or loop. Iterative statements are also called as repetitive statement or looping
statements.
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 31
There are three types of looping structures in C++.
o while loop
o do while loop
o for loop

while loop: This is a pre-tested loop structure. This structure checks the condition at the beginning
of the structure. The set of statements are executed again and again until the condition is true. When the
condition becomes false, control is transferred out of the structure.
The general form of while structure is
while ( Test Condition)
{
Statement 1
Statement 2
……..
Statement N
}End of While
Example:
n = 10;
While ( n > 0)
{
cout<<n<<”t”;
- - n;
}
cout<<”End of while loop n”;
Output: 10 9 8 7 6 5 4 3 2 1 End of while loop
Write a C++ program to find sum of all the digits of a number using while statement.
#include<iostream.h>
#include<conio.h>
void main( )
{
int num, sum, rem;
clrscr( );
cout<<”Enter the Number”<<endl;
cin>>num;
sum = 0;
while(num!=0)
{
rem = num % 10;
sum = sum + rem;
num = num/10;
}
cout<<”Sum of the digits is “<<sum<<endl;
getch( );
}
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 32
Write a C++ program to input principal amount, rate of interest and time period. Calculate
compound interest using while statement.
(Hint: Amount = P * (1 + R/100)T, Compound Interest = Amount – P)
#include<iostream.h>
#include<conio.h>
void main( )
{
float pri, amt, priamt, rate, ci;
int time, year;
clrscr( );
cout<<”Enter the Principal amount, rate of interest and time”<<endl;
cin>>pri>>rate>>time;
year = 1;
priamt = pri;
while(year <= time)
{
amt = pri * (1 + rate/100);
year ++;
}
ci = amt – priamt;
cout<<”Compound Interest is “<<ci<<endl;
getch( );
}
Write a C++ program to check whether the given number is power of 2.
#include<iostream.h>
#include<conio.h>
void main( )
{
int num, m, flag;
clrscr( );
cout<<”Enter the Number”<<endl;
cin>>num;
m = num;
flag = 1;
while(num>2)
if(num % 2 ==1)
{
flag = 0;
break;
}
else
num = num/2;
if(flag)
cout<<m<<” is power of 2 “<<endl;
else
cout<<m<<” is not power of 2 “<<endl;
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 33
getch( );
}

do while statements:
 This is a post-tested loop structure.
 This structure checks the condition at the end of the structure.
 The set of statements are executed again and again until the
condition is true.
 When the condition becomes false, control is transferred out of
the structure.
 The general form of while structure is
do
{
Statement 1
Statement 2
……..
Statement N
} while ( Test Condition);

 Example:
i = 2;
do
{
cout<<i<<”t”;
i = i + 2;
}
while ( i < = 25);
Write a C++ program to check whether the given number is an Armstrong number using do-while
statement. (Hint: 153 = 13
+ 53
+ 33
)
#include<iostream.h>
#include<conio.h>
void main( )
{
int num, rem, sum, temp;
clrscr( );
cout<<”Enter the three digit number”<<endl;
cin>>num;
temp = num;
sum = 0;
do
{
rem = temp % 10;
sum = sum + rem * rem * rem;
temp = temp / 10;
}while(temp!=0);
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 34
if(sum == num)
cout<<num<<” is an Armstrong Number “<<endl;
else
cout<<num<<” is not an Armstrong Number “<<endl;
getch( );
}

for statement:
 This structure is the fixed execution structure.
 This structure is usually used when we know in advance exactly how many times asset of
statements is to be repeatedly executed again and again.
 This structure can be used as increment looping or decrement looping structure.
 The general form of for structure is as follows:
for ( Expression 1; Expression 2; Expression 3)
{
Statement 1;
Statement 2;
Statement N;
}
Where, Expression 1 represents Initialization
Expression 2 represents Condition
Expression 3 represents Increment/Decrement

 Example:
sum = 0;
for ( i=1; i<=10; i++)
sum = sum + i;

 This looping structure works as follows:
o Initialization is executed. Generally, it is an initial value setting for a counter variable and is
executed only one time.
o Condition is checked. if it is TRUE the loop continues, otherwise the loop ends and control
exists from structure.
o Statement is executed as usual, is can either a single statement or a block enclosed in curled
braces { and }.
o At last, whatever is specified in the increase field is executed and the loop gets back to
executed step 2.
o The initialization and increase fields are optional. They can remain empty, but in all cases,
the semicolon sign between them must be written compulsorily.
o Optionally, using the comma operator we can specify more than one expression in any of the
fields included in a for loop.
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 35
Write a C++ program to find the factorial of a number using for statement.
(Hint: 5! = 5 * 4 * 3 * 2 * 1 = 120)
#include<iostream.h>
#include<conio.h>
void main( )
{
int num, fact, i;
clrscr( );
cout<<”Enter the number”<<endl;
cin>>num;
fact = 1;
for( i = 1; i<= num; i++)
fact = fact * i;
cout<<” The factorial of a ”<<num<<”! is: “<<fact<<endl;
getch( );
}
Write a C++ program to generate the Fibonacci sequence up to a limit using for statement.
(Hint: 6 = 0 1 1 2 3 4)
#include<iostream.h>
#include<conio.h>
void main( )
{
int num, first, second, count, third;
clrscr( );
cout<<”Enter the number limit for Fibonacci Series”<<endl;
cin>>num;
first = 0;
second = 1;
cout<<first<<”t”<<second;
third = first + second;
for( count = 2; third<=num; count++)
{
cout<<”t”<<third
first = second;
second = third;
third = first + second;
}
cout<<”n Total terms = “<<count<<endl;
getch( );
}
 
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 36
Jump statements or Transfer of control from within loop
 Transfer of control within looping are used to
o Terminate the execution of loop.
o Exiting a loop.
o Half way through to skip the loop.
 All these can be done by using break, exit and continue statements.

break statement
 The break statement has two uses
o You can use it to terminate a case in the switch statement.
o You can also use it to force immediate termination of a loop like while, do-while and for,
by passing the normal loop conditional test.
 When the break statement is encountered inside a loop, the loop is immediately terminated and
program control resumes at the next statement.
 The general form of break statement is:
break;
 Example:
for (n=0; n<100; n++)
{
cout<<n;
if(n==10) break;
}
Program: To test whether a given number is prime or not using break statement.
#include<iostream.h>
#include<conio.h>
void main( )
{
int n, i, status;
clrscr( );
cout<<”Enter the number”;
cin>>n;
status=1;
for(i=2; i<=n/2; i++)
{
if(n % i ==0)
{
status=0;
cout<<”It is not a prime”<<endl;
break;
}
}
if(status)
cout<<”It is a prime number”<<endl;
getch( );
}

Object Oriented Concepts & C++ Programming
Prof. K Adisesha 37
exit( ) function:
 This function causes immediate termination of the entire program, forcing a return to the
operating system.
 In effect, exit( ) function acts as if it were breaking out of the entire program.
 The general form of the exit( ) function is:
exit( ); or void exit( int return_code);
 The return code is used by the operating system and may be used by calling programs.
 An exit code of 0 means that the program finished normally and any other value means that some
 Error or unexpected results happened.
Program: To test whether a given number is prime or not using exit( ) statement.
#include<iostream.h>
#include,conio.h>
void main( )
{
int n, i;
clrscr( );
cout<<”Enter the number”;
cin>>n;
for(i=2; i<=n/2; i++)
{
if(n % i ==0)
{
cout<<”It is not a prime”<<endl;
exit(0);
}
}
cout<<”It is a prime number”<<endl;
getch( );
}

continue statement:
 The continue statement causes the program to skip the rest of the loop in the current iteration as
if end of the statement block has been reached, causing it to jump to start of the following
iteration.
 The continue statement works somewhat like break statement.
 Instead of forcing termination, however continue forces the next iteration of the loop to take
place, skipping any code in between.
 The general form of the continue statement is:
continue;
 Example:
for (n=10; n<0; n--)
{
if(n==10) continue;
cout<<n;
}
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 38
goto statement:
 The goto allows to makes an absolute jump to another point in the program.
 This statement execution causes an unconditional jump or transfer of control from one statement
to the other statement with in a program ignoring any type of nesting limitations.
 The destination is identified by a label, which is then used as an argument for the goto statement.
 A label is made of a valid identifier followed by a colon (:).
 The general form of goto statement is:
statement1;
statement2;
goto label_name;
statement 3;
statement4;
label_name: statement5;
statement6;
Program: To print from 10 to 1 using goto statements.
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main( )
{
int n=10;
loop: cout<<”t”<<n;
n--;
if(n>0) goto loop;
cout<<”End of loop”;
getch( );
}
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 39
ARRAYS
Introduction
 In computer languages, we also need to group together data items of the same type.
 The most basic mechanism that accomplishes this in C++ is the array.
 Arrays can hold a few data items or tens of thousands.
 The data items grouped in an array can be simple types such as int or float, or they can be user-
defined types such as structures and objects.
 Arrays exist in almost every computer language. Array in C++ are similar to those in other
languages and identical to those in C.

Array Fundamentals: An array is collection of elements where all the elements are same data
type under the same name.
 The elements are numbered as 0, 1, 2….n-1.
 These numbers called as indices or subscripts.
 These numbers are used to locate the positions of elements within the array.
 If a is the name of the array, the elements can be directly accessed as
a[0], a[1], a[2],……, a[n-1].
o a[0] is the name of the first element present at position 0.
o a[1] is the name of the second element present at position 1 and so on.
o In general, a[i] is the element present at position i.
 An array can be represented as
a 10 20 30 40 50
0 1 2 3 4
 In the above array, a is the name of the array,
o a[0] contains the element 10
o a[1] contains the element 20
o a[2] contains the element 30
o a[3] contains the element 40
o a[4] contains the element 50.

 The method of numbering the ith element with index i-1 is called as zero- based indexing.
 That is, the element is always same as the number of “steps“ from the initial element a[0] to that
element. For example, the element a[3] is 3 steps from the element a[0].
 In C++, the subscripts always start with 0. For example, if b is the name of the array
b[0], b[1], b[2]……..are the elements and 0, 1, 2,……..are the subscripts.

Types of Arrays:
 There are 3 types of arrays.
o One-dimensional array
o Two-dimensional array
o Multi-dimensional array

One –dimensional array
 It is an array in which each element is accessed by using only one subscript.
 The only one subscript represents the position of the element in array.

Object Oriented Concepts & C++ Programming
Prof. K Adisesha 40
Two-dimensional array
 Each element is accessed using 2-subscripts in an array.
 The subscripts represent the position of the element in the array.

Multi-dimensional array
 A multi-dimensional array is an array of n-dimensions.
 In other words, an array of arrays is called a multi-dimensional array.
 A one-dimensional array of one-dimensional array is called a two dimensional array; a one-
dimensional array to two-dimensional array is called three-dimensional array and so on.

One-Dimensional Array:
 Each element is accessed by using only one subscript in an array.
 The only one subscript represents the position of the element in array.
 Like other variable, the array should also be defined before it is used to store elements.
 An array can be defined by specifying the data type of the elements followed by name of the array
and the number of elements that can be stored in the array.
 The number of elements that can be stored in the array is called the size of the array.
 The size of the array must be a constant or an expression that evaluates to a constant, and should
be an integer.
 The size should be enclosed within square brackets.

Declaration of One-dimensional array:
 Syntax: datatype array_name[size];
 Example: int regno[10];
 This example defines an array marks that can store 50 elements and all the elements are of int data
type.

Initialization of one-dimensional arrays:
 You can give values to each array element when array is first defined.
 Example 1: int a[5] = { 10, 20, 30, 40, 50};
 In the above example,
o value 10 is stored in a[0]
o value 20 is stored in a[1]
o value 30 is stored in a[2]
o value 40 is stored in a[3]
o value 50 is store in a[4]
 If there is less number of elements specified than the size of the array, the remaining elements are
filled with 0 by the compiler.
 If the array does not include an initialization, then the array elements may contain the unexpected
values called “garbage values”.
 When an array has explicit initialization, its size can be omitted from the declaration.
 Example: int a[5] = { 9, -5, 6, 2, 8}; is equivalent to int a[ ] = { 9, -5, 6, 2, 8};




Object Oriented Concepts & C++ Programming
Prof. K Adisesha 41
Accessing the elements:
 Consider the declaration, int a[5];
 We can read 5 elements into the array through the input device by writing the following program
fragment.
cout<<”Enter the elements:”;
for(i=0; i<5; i++)
cin>>a[i];
 To print the 5 elements of the above array, we write the following program fragment.
cout<<”The elements are:”;
for(i=0; i<5; i++)
cout<<a[i]<<”t”;
Sample Program 1: To read the elements into the array and printing the elements:
#include<iostream.h>
#include<conio.h>
void main( )
{
int a[50], i, n;
clrscr( );
cout<<”Enter the size of the array:”;
cin>>n;
cout<<”Enter the elements:”;
for(i=0; i<n; i++)
cin>>a[i];
cout<<”The elements are:”;
for(i=0; i<5; i++)
cout<<a[i]<<”t”;
getch( );
}

Memory representation of one-dimensional arrays:
 The elements of one-dimensional arrays are stored in continuous memory locations.
 Example: Consider the declaration, char A[5];
 The element a[0] is allocated at a particular memory location, the element a[1] is allocated at next
memory location and so forth. Since the array is of the type char, each element requires 1-byte.
1000 1001 1002 1003 1004
A[0] A[1] A[2] A[3] A[4]
Total Size = sizeof(type) * size_of_array;
Example:
o The total size of the char array required is 1 * 5 = 5 bytes.
o The total size of the int array required is 2 * 3 = 6 bytes.
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 42
Program to find the sum and average of n number of the array:
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main( )
{
int a[50], i, n, sum;
float avg;
clrscr( );
cout<<"How many elements?"<<endl;
cin>>n;
cout<<"Enter the elements:";
for(i=0; i<n; i++)
cin>>a[i];
sum = 0;
for(i=0; i<n; i++)
sum = sum + a[i];
avg=(float) sum / n;
cout<<"Sum = "<<sum<<endl;
cout<<"Average = "<<avg<<endl;
getch( );
}
Practical Program 18: To find the second largest of n number in the array:
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main( )
{
int a[50], i, n, largest, secondlar;
clrscr( );
cout<<"How many elements?"<<endl;
cin>>n;
cout<<"Enter the elements:";
for(i=0; i<n; i++)
cin>>a[i];
if(a[0] > a[1])
{
largest = a[0];
secondlar = a[1];
}
else
{
largest=a[1];
secondlar=a[0];
}
for(i=2; i<n; i++)
if(a[i] > largest)
{
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 43
secondlar = largest;
largest = a[i];
}
else
if(a[i] > secondlar)
secondlar = a[i];
cout<<"Largest = "<<largest<<endl;
cout<<"Second Largest = "<<secondlar<<endl;
getch( );
}
Sorting: The process of arrangement of data items in ascending or descending order is called sorting.
Program to arrange a list of numbers in ascending order:
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main( )
{
int a[50], i, temp, j, n;
clrscr( );
cout<<"Enter the number of elements:"<<endl;
cin>>n;
cout<<"Enter the elements:"<<endl;
for(i=0; i<n; i++)
cin>>a[i];
for(i=1; i<n; i++)
{
for(j=0; j<n-i; j++)
if(a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
cout<<"The sorted elements are:"<<endl;
for(i=0; i<n; i++)
cout<<a[i]<<”t”;
getch( );
}
Searching: The process of finding the position of a data item in the given collection of data items is
called searching.
We can search the position of an element in the array.
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 44
To find position of a given number in the array:
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main( )
{
int a[50], i, pos, ele, n;
clrscr( );
cout<<"Enter the number of elements:"<<endl;
cin>>n;
cout<<"Enter the elements:"<<endl;
for(i=0; i<n; i++)
cin>>a[i];
cout<<"Enter the search element:"<<endl;
cin>>ele;
pos=-1;
for(i=0; i<n; i++)
if(ele == a[i])
{
pos = i;
break;
}
if(pos >= 0)
cout<<ele<<" is present at position "<<pos<<endl;
else
cout<<ele<<" is not present"<<endl;
getch( );
}

Two -Dimensional arrays:
 It is an array in which each element is accessed using 2-subsripts.The subscripts represents position
of the elements in the array.
 The elements of two-dimensional arrays are represented as rows and columns. To identify any
element, we should know its row-number and column-number.

Declaration of Two -Dimensional array:
 A Two-dimensional array can be defined by specifying the data type of the elements followed by
name of the array followed by the number of rows (i.e. row-size) and number of columns (i.e.
column-size)in the array.
 The rows-size and column-size of the array must be constant are expressions that evaluates to an
integer.
 The rows-size and column-size should be separately enclosed within square brackets.
Syntax: data_type array_name[row size] [column_size];

Object Oriented Concepts & C++ Programming
Prof. K Adisesha 45
Initialization of Two-Dimensional arrays:
 Similar to the one-dimensional array, we can initialize a two-dimensional array either by
initializing it in its declaration or by using assignment statement.
Example: int a[2][3] = { 1,2,3,4,5,6};
Where a is a two-dimensional array which contains 2 rows and 3 columns and these assignments would
be
a[0][0] = 1 a[0][1] = 2 a[0][2] = 3
a[1][0] = 4 a[1][1] = 5 a[1][2] = 6

Note: If the values are missing in an initialize, they are automatically set to 0.
Accessing the elements:
 Consider the declaration int a[2][3];
 We can read 6 elements into the array, we need to use nested for loops.
 One loop processes the rows and another loop processes the columns.
 If outer loop is for rows and inner loop is for columns, then for each row index, all the columns
are processed and then the same process is repeated for next row index.
 To understand this, let us consider the following program fragment.
cout<<”enter the elements:”;
for (i=0; i<2; i++) //outer loop to control the rows
for (j=0; j<3; j++) //inner loop to the control columns
cin>>a[i][j];
To read the elements into the two-dimensional array and printing the
elements:
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main()
{
int a[5][5], i, j, m, n;
clrscr( );
cout<<"Enter the order:"<<endl;
cin>>m>>n;
cout<<"Enter the elements:"<<endl;
for(i=0; i<m; i++)
for(j=0; j<n; j++)
cin>>a[i][j];
cout<<”The array elements are:”<<endl;
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
cout<<a[i][j]<<”t”;
cout<<endl;
}
getch( );
}
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 46
Write a program to sum of all the row and sum of all the column in matrices separately:
#include<iostream.h>
#include<conio.h>
void main( )
{
int a[5][5], r, c, i, j, rsum, csum;
clrscr( );
cout << "Enter the order of matrix: ";
cin >> r>>c;
// Storing elements of matrix entered by user.
cout << "Enter elements of the matrix: " << endl;
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
cin >> a[i][j];
for(i = 0; i < r; i++)
{
rsum = 0;
for(j = 0; j < c; j++)
rsum = rsum + a[i][j];
cout<<”Sum of row no “<<i+1<<” = “<<rsum<<endl;
}
for(i = 0; i < c; i++)
{
csum = 0;
for(j = 0; j < r; j++)
csum = csum + a[j][i];
cout<<”Sum of column no “<<i+1<<” = “<<rsum<<endl;
}
getch( );
}
Write a program to find the sum of two matrices:
#include<iostream.h>
#include<conio.h>
void main( )
{
int a[5][5], b[5][5], sum[5][5], r1, c1, r2, c2, i, j;
clrscr( );
cout << "Enter the order of first matrix: ";
cin >> r1>>c1;
cout << "Enter the order of second matrix: ";
cin >> r2>>c2;
// Storing elements of first matrix entered by user.
cout << "Enter elements of 1st matrix: " << endl;
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
cin >> a[i][j];
// Storing elements of second matrix entered by user.
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 47
cout << "Enter elements of 2nd matrix: " << endl;
for(i = 0; i < r; i++)
for(j = 0; j < c; j++)
cin >> b[i][j];
if ( (r1 == r2) && (c1==c2)
{
for(i = 0; i < r; i++)
for(j = 0; j < c; j++)
sum[i][j] = a[i][j] + b[i][j]; // Adding Two matrices
cout << "Sum of two matrix is: " << endl;
for(i = 0; i < r; i++)
for(j = 0; j < c; j++)
cout << sum[i][j] << "t"; // Displaying the resultant sum matrix.
cout << endl;
}
else
cout<<”Matrices are not compatible…”<<endl;
getch( );
}
Program to Consider an array MARKS[20[5] which stores the marks obtained by 20 students in 5
subjects. Now write a program to:
 Find the average marks obtained in each subject.
 Find the average marks obtained by every student
 Find the number of students who have scored below 50 in their average.
#include<iostream.h>
#include<conio.h>
void main( )
{
int marks[20][5], n, s, total, count=0, i, j;
float average;
clrscr( );
cout << "Enter the number of students: ";
cin >> n;
cout << "Enter the number of subjects: ";
cin >> s;
cout << "Enter the marks: " << endl;
for (i = 0; i < n; i++)
for (j = 0; j < s; j++)
cin >> marks[i][j];
cout<<endl<<”Average of Subjects”<<endl;
cout<<”Sub1tSub2tSub3tSub4tSub5”<<endl;
for(i = 0; i < s; i++)
{
total = 0;
for(j = 0; j < n; j++)
total = total + marks[j][i];
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 48
average = total/n;
cout<<average<<”t”;
}
cout<<endl<<”Average of students:”<<endl;
cout<<”StudenttAverage”<<endl;
for(i = 0; i < n; i++)
{
total = 0;
for(j = 0; j < s; j++)
total = total + marks[i][j];
average = total/s;
if(average<50)
count++;
cout<<” t”<<i+1<<”t”<<average<<endl;
}
cout<<endl<<”Number of students less than average is ”<<count<<endl;
getch( );
}

Multi -Dimensional arrays:
 A Multi-Dimensional array is an array of n-dimensions.
 An array of arrays is called a multi-dimensional array.
Syntax: Data_type Array_name[s1][s2][s3]…..[sn];
where s1 is the size of the ith dimension.
Example:
int A[2][2][2];
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 49
FUNCTIONS

Introduction: A function is a named group of statements developed to solve a sub-problem and
returns a value to other functions when it is called.

Types of functions
There are two types of functions:
1. Library functions
2. User-defined functions

Library functions: A standard library is a collection of pre-defined functions and other
programming elements, which are accessed through header files.
 Header files are the files containing standard functions that our programs may use.
 The header files should be written angled brackets and its functions are included into our programs
by #include directive.

User-defined functions: We can create our own functions or sub-programs to solve our
problem. Such functions are normally referred to as user-defined functions.
 A user-defined function is a complete and independent program, which can be used (or
invoked) by the main program, or by the other sub-programs.
 The user-defined functions are written to perform definite calculations, after performing their task
they send back the result to the calling program or sub-program.

Different header files

iostream.h
 This header file contains C++ streams and i/o routines and are listed below.
 open, close, get, getline, read, write, put, seekg, seekp, tellg, tellp, eof etc.

stdio.h
 This header file contains functions and macros to perform standard i/o operations.
 When we include the header file iostream.h, the header file stdio.h is automatically included into
our program. The standard i/o functions of the header file stdio.h are listed below.
 fopen, fclose, printf, scanf, fprintf, fscanf, fread, fwrite etc.

string.h
 This header file declares functions to manipulate strings and memory manipulation routines.
 The functions contained in the header file string.h are listed below in the table.
Function Meaning
strlen(s) It gives the no. of characters including spaces present in a string s.
strcat(s1, s2) It concatenates the string s2 onto the end of the string s1.
strcpy(s1, s2) It copies character string s2 to string s1. The s1 must have enough
storage locations to hold s2.
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 50
strcmp((s1,s2)==0)
strcmp((s1,s2)>0)
strcmp((s1,s2)<0)
It compares s1 and s2 and find out whether s1 equal s2, greater
than s2 or s1 less than s2.
strcmpi((s1,s2)==0)
strcmpi((s1,s2)>0)
strcmpi((s1,s2)<0)
It compares s1 and s2 ignoring case and find out whether s1 equal
s2, greater than s2 or s1 less than s2.
strrev(s) It converts a string into its reverse.
strupr(s) It converts a string s into upper case.
strlwr(s) It converts a string into lower case.
stdlib.h
 This header file is used to declare conversion routines, search/sort routines and other miscellaneous
things. The functions are listed below.
atoi, atol, atof, free, malloc, calloc, realloc etc.

iomanip.h
 This header file contains functions and macros for I/O manipulators for creating parameterized
manipulations. The functions are listed.
endl, setw, setfile, setprecision, hex, oct etc.

math.h
 This header file declares prototypes for the mathematical functions and error handlers.
 The functions that are used to perform mathematical calculations and conversions are listed below
in the table.
Function Meaning
 sqrt(x) Square Root of X
 pow(x, y) x raised to the power y
 sin(x) Sine of an angle x (measured in radians)
 cos(x) Cosine of an angle x (measured in radians)
 tan(x) Tangent of an angle x (measured in radians)
 asin(x) Sin-1(x) where x (measured in radians)
 acos(x) Cos-1(x) where x (measured in radians)
 exp(x) Exponential function of x (ex)
 log(x) Logarithm of x
 log 10(x) Logarithm of number x to base 10
 abs(x) Absolute value of integer number x
 fabs(x) Absolute value of real number x
Character functions
 A character is any single character enclosed within single quotes.
 Some functions accept a character as argument.
 The argument is processed as an int by using its ASCII code.
 To use these functions, the header file ctype.h should be included.
 Any character enclosed within single quotes is called as a single character constant or simply, a
character constant.
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 51
 These functions will be of the form : int function-name(int character)
 Any character enclosed within single quotes is called as a single character constant or simply, a
character constant.
 Some functions that perform operations on characters are given below.
Function Meaning
 isalpha(c) It returns True if C is an uppercase letter and false if c is lowercase.
 isdigit(c) It returns True if c is a digit (0 to 9) otherwise false
 isalnum(c) It returns True if c is digit from 0 through 9 or an alphabetic character
 islower(c) It returns True if c is a lowercase letter otherwise False
 isupper(c) It returns True if c is a uppercase letter otherwise False
 toupper(c) It converts c to uppercase letter
 tolower(c) It converts c to lowercase letter.
Inputting single character
 We can input a character using the function get ( ).
 The general form is
char ch; or char ch;
cin =get(ch);
ch=cin.get(ch);

Outputting single character
 put ( ) function is used to display single character.
 The general form is cout.put (ch);
 Example: char ch;
ch=cin.get( );
cout.put (ch);
Program to determine the type of character.
#include<iostream.h>
#include<conio.h>
#include<ctype.h>
void main ( )
{
char ch;
clrscr( );
cout<<”Type-in a character:”;
ch=cin.get();
if((ch>=’A’ &&ch<=’Z’)||(ch>=’a’ &&ch<=’z’))
cout<<”It is an albhabet”<<endl;
else
if(ch>=’0’ &&ch<=’9’)
cout<<”It is a digit”<<endl;
else
cout<<”It is a special character”<<endl;
getch( );
}
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 52
Program to convert a character from upper-case to lower case and vice versa.
#include<iostream.h>
#include<conio.h>
#include<ctype.h>
void main( )
{
char ch;
clrscr( );
cout<<”Type-in a character:”;
ch=cin.get();
if( isupper (ch) )
{
ch= tolower (ch);
cout<<”The lower-case letter is”<<ch<<endl;
}
else
if( islower (ch) )
{
ch= toupper (ch);
cout<<”The upper-case letter is”<<ch<<endl;
}
else
cout<<”It is not an alphabet”<<endl;
getch();
}

String functions: A string is sequence of characters enclosed within double quotes.
 String are manipulated as one-dimensional array of characters and terminated by null (‘0’)
character.
 C++ provides many functions to manipulate strings.
 To use these functions, the header file string.h should be included.

Declaring a string variable
 The general form to declare a string is:
char string _name[size];
 String_ name is the name of the string variable
 Size is the number of characters in the string. The size helps the compiler to allocate required
number of memory locations to store the string.
Example: char st[50];
This declaration reserves 50-bytes to store the characters of the string variable st.

Initializing a string
 Like other variables, strings can also be initialized when they are declared.
Example: char s[10]=”Karnataka”;
 There are only 9 characters in the string. The null character (‘0’) is automatically appended to the
end of the string.
Example: char st[]={‘E’, ‘m’, ‘p’, ‘r’, ‘e’, ‘s’, ‘s’,’0’};
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 53
The string is initialized character –wise. In this case, we must specify the null character.
 If an entire string is initialized to a string-variable then the null character is automatically
appended to end-of-string.
 If string is initialized by giving the characters, then we must explicitly specify the string
terminator. i.e., null character.

Inputting a string: C++ provides the function getline( ) to read a string.
 The general form is: cin.getline (string, size);
Example :- cin.getline (st, 25);
getline( ) the function terminates reading characters on reading a newline character or when
number of characters read is equal to size.
 The newline character is read, but replaced by null character.

Outputting a string: C++ provides the function write ( ) to output a string.
 The general form is: cout.write (string, size);
Example:- cout.write (st, 25);
 write ( ) function displays the specified number of characters.
 This function does not stop displaying the characters when encountering the null character. As a
result, if the size specified is greater than the length of the string, it displays beyond the bounds of
the line.
Program to read a string and print the string.
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main( )
{
char s[50];
int l;
clrscr( );
cout<<”enter the string:”;
cin.getline(s,50);
l=strlen(s);
cout<<”the given string is”;
cout.write(s,l);
getch();
}
Some string manipulation functions are given below:
strlen( ) function: This function returns the length of the string .i.e., the number of characters
present in the string, excluding the null character.
 The general form is variable=strlen(string);
 A string of length ‘0’ is called a null string.
Example:- l = strlen (“empress”); returns 7
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 54
Program to find the length of the string using the library function.
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
char st[100];
int l;
clrscr( );
cout<<”enter the string:”;
cin.getline (st,100)
l=strlen (st);
cout<<”length=”<<l<<endl;
getch();
}
Program to find the length of the string without using the library function.
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
char st[100];
int i;
clrscr();
cout<<”enter the string:”;
cin.getline(st,100);
for (i=0; st[i]!=’0’; i++) //for loop terminated
cout<<”length=”<<i<<endl;
getch();
}

strcat( ) function: This function is used to concatenate 2 strings. The process of combining 2
strings to form a string is called as concatenation.
 The general form is strcat(string1, string2);
Example:- char str1[ ]=”win”;
char str2[ ]=”dows8”;
strcat(str1,str2);
str1 becomes “windows8”.

strcpy( ) function: A string cannot be copied to another string by using assignment statement.
The function
 strcpy() is used to copy a string into another string.
 The general form is strcpy (string1, string2);
 It copies all the characters to string2 to string1.
Example:- char str1[ ]=”computer”;
char str2[ ]=”science”;
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 55
strcpy (str1,str2);
str1 becomes ”science”

strcmp( ) function: This function is used to alphabetically compare a string with another string.
This function is case-sensitive. i.e., it treats the uppercase letters and lowercase letters as different.
The general form is strcmp (string1, string2);
 It compares all the characters of str2 with str1. The function returns a positive value if
 string1>string2, a negative vale if string 1<string2 or it string1 is same as string2.
Example:- char str1[ ]=”There”;
char str2[ ]=”there”;
strcmp (str2,str1); //gives a positive value
But, strcmp (str1,str2); //gives a negative value

strcmpi ( ) function: This function is used to alphabetically compare a string with another string.
This function is not case-sensitive. i.e., it treats the uppercase letter and lowercase letter as same.
The general form is strcmpi (string1,string2);
 It compares all the characters of str2 with str1. This function returns a positive value if
string1>string2, a negative value if string1<string2 or 0 it string1 is same as string2.
Example:- char str1[ ]=”There”;
char str2[ ]=”there”;
strcmpi (str2,str1); //gives 0
Program to determine whether the string is a palindrome.
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main( )
{
char s[100], r[100]; //s is the string and r is the reserved string
clrscr();
cout<<”Enter the String:”;
cin.getline(s,100);
strcpy (r, s); // Copy the characters of the string s to r
strrev (r); // Reverse the characters of the string r
if(strcmpi(s, r) == 0)
cout<<”It is palindrome”<<endl;
else
cout<<”It is not palindrome”<<endl;
getch();
}
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 56
To count the number of vowels and consonants in a string.
#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
void main( )
{
char s[100];
int l, i, cons=0, vow=0;
clrscr( );
cout<<”enter the string:”;
cin.getline(s,100);
l=strlen(s);
for(i=0;i<1;i++)
if( isalpha (s[i]) )
switch (toupper (s[i]) )
{
case ’A’:
case ’E’:
case ’I’:
case ’O’:
case ’U’: vow++;
break;
default: cons++;
}
cout<<”Number of Vowels:”<<vow<<endl;
cout<<”Number of Consonants:”<<cons<<endl;
getch();
}

Other functions
C++ provides some useful functions under the library stdlib.h. Some functions are rand( ),
srand( ), random( ) and randomized( ).
These functions are used to generate pseudo-random numbers. i.e.,numbers that are uniformly
distributed within a given interval and for which there is no particular pattern.
Computer will generate a number by itself!! Randomly, using this randomized ( ).
Function Meaning
 randomize() It initialize/seeds the random number generator with a random number.
 random(n) It generates a random number between 0 to n-1.
 atoi(s) It converts string s into a numerical representation.
 itoa(n) It converts a number to a string.
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 57
USER DEFINED FUNCTIONS

Definition: User-defined function is a function defined by the user to solve his/her problem.
 Such a function can be called (or invoked) from anywhere and any number of times in the
program.
 The purpose of using a function is to make the program design process easy, understandable
and thereby avoiding ambiguity.

Advantages of user-defined functions:
 If there is set of statements to be repeated several times in the program, these statements can
be replaced as a function and called whenever and whenever required.
 If a task in needed in more than one program or to a group of programmers, a function can be
developed and made available to other programs or other programmers.
 Programs can be modularized into functions. Each function can be developed independently,
debugged and tested.
 If a problem is divided into sub-problems, a team of programmers can be formed to solve each
sub-problem, rather solving by a single person.
 If functions are developed in a program, the number of line decreases.

Function definition or structure of user-defined function:
 Return type-specifiers: is the data type of the value return by the function to another function
when it is called. It can be char, int, float or void. Data type void is used when the function return
no value to calling function.
 Function-name: is the name of the function. It is an identifier to identify the particular function
in a program.
 Argument-list with declaration: is the list of arguments or parameters or variables with their
declaration. Each argument should be declared separately. Each declaration should be separated
by comma. The list should be enclosed within parenthesis.
 The complete line is called the function header. Note that there is no semicolon at the end.
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 58
 Local-variable declaration: is the declaration of the variables that are used within the function.
Since these variables are local to the function, these variables are called as local variables.
 Executable statements: are the statements that perform the necessary operations to solve the
problem. If the function is returning a value, a return statement should be included. Otherwise,
return statement is not necessary.
 Local declaration and executable statements are together called as body of the function. The body
of the function should be enclosed within the curled braces.
Program to find the greatest of three numbers.
#include<iostream.h>
#include<conio.h> void main( )
{
int biggest (int, int, int); //Function prototype int a, b, c, big;
clrscr( );
cout<<”Enter the three numbers”;
cin>>a>>b>>c;
big = biggest(a, b, c); // Function call-statement cout<<”Biggest=”<<big<<endl; getch( );
}
int biggest (int x, int y, int z) // Called Function
{
int big;
big = x>y?(x>z?x:z):(y>z?y:z);
return (big); }

Calling a function: Function call is the statement that is used to call or make another function
execute.
 The definition of the program can come either before the main( ) function or after the main( )
function.
 Calling function is a function that transfer control from it to another function by specifying the
name of that function and passing arguments.
 Called function is a function that receives the call and arguments from another calling function.
 When a function call is made, the control jumps calling function to the called function.
main ( ) function:
 The main ( ) function returns a value of type int to the operating system. If the program runs
successfully, 0 is returned. Otherwise, a non-zero value is returned to the operating system,
indicating that the program contains errors.
 If the main ( ) function is not returning a value, the data type void can be used as return type
specifiers.
 The general form of main ( ) function is:
int main ( )
{
Executable-Statements;
return 0;
} 
void main( )
{
Executable-Statements;
} 
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 59
Returning a value:
 When a function is called, the statements in the called function are executed.
 After executing the statements, the function returns value to the calling function. The return
statement is used to return a value.
 A function can return only one value or none to the calling function, for every function call.
 The general form of return statements is:
return (expression); OR return 0; 

Function Prototype:
 A function prototype is a declaration of the function that tells the program about the type of the
value return by the function and the number and type of arguments.
 The general form of function prototype is:
General Form Example
return-type-specifier function-name (type arg1, type
arg2….)
OR
return-type-specifier function-name ( type, type ….)
int biggest(int x, int y, int z);
OR
int biggest( int, int , int);

Types of Arguments: A variable in a function header is called an argument.
The arguments are used to pass information from the calling function to the called function.
Actual Arguments: The function call statement contains name of the function and the list of
arguments to be passed. These arguments or parameters are called as actual arguments.
 The arguments can be constants, variables, or expressions.
 Example: big = biggest (a, b, c);
Formal Arguments: The function header contains return-type-specifier, function name and list
of arguments with their declaration.
 These arguments are called as formal arguments or dummy arguments. Formal arguments get their
values from the actual arguments.
 Example: int biggest (int x, int y, int z)
Local Variables: The variables declared inside function or block is said belong to that block.
These variables are called as Local variables.
 Values of local variables are accessible only in that block.
 The function’s formal arguments are also considered as local variables.
 Example:
function-name (int a, int b) { int x, y; //x and y are local variables; …………; }

Global Variables: The variables declared outside the function are called as global variables. These
variables are referred by the same data type and same name throughout the program in both calling
function and called function.
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 60
 Whenever if some variables are to treated as same value in both main( ) and in other functions, it
is advisable to use global variables.
Example:
int a, b; // a and b are global variables void main( ) { int p, q; // p and q are local variables ……. }
Program to find the LCM of two numbers:
#include<iostream.h>
#include<conio.h>
int a,b; // a and b are global variables
int gcd(int x, int y)
{ int r; // r is local variable
while(b!=0)
{
r = a%b;
a=b;
b=r;
}
return a;
}
void main( )
{
int gcd(int x, int y) //Function Prototype
int product, lcm, g;
clrscr( );
cout<<”enter two numbers:”;
cin>>a>>b;
produt= a *b;
g = gcd(a, b);
lcm = product/g;
cout<<”GCD=”<<g<<endl;
cout<<”LCM=”<<lcm<<endl;
getch();
}

Scope of Variables:
 Scope of variables refers to the part of the program where the value of the variable can be used.
 The scope of the variables begins from where the variable declared.
 If the declaration is inside a function, the scope extends to the end of the innermost block that
contains the declaration.
 Example: To illustrate scope of variables
#include<iostream.h>
#include<conio.h>
void f( );
void g( );
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 61
int x=10;
void main( )
{
int x = 20;
{
int x = 30;
cout<<”In block inside main( ): x=”<<x<<endl;
}
cout<<”In main(): x=”<<x<<endl;
cout<<”In main(): ::x=””<<::x<<endl;
f( );
g( );
}
void f()
{ cout<<”In f(): x=”<<x<<endl;
}
void g()
{
int x=40;
cout<<”In g(): x=”<<x<<
endl;
}

Types of Function:
 There are different types of functions:
a. Function with no arguments and no return values.
b. Function with arguments and with no return values.
c. Function with no arguments and with return values.
d. Function with arguments and with return values.
e. Recursive function.

Function with no arguments and no return values: In this method, the simply performs
independent task. The function does not receive or send any arguments.
General Form Example
void function-name( )
{
Statements;
}
void natural( )
{
for(int i=1; i<=10; i++)
cout<<”t”<<I;
}





Object Oriented Concepts & C++ Programming
Prof. K Adisesha 62
Function with arguments and with no return values: In this method, the function receives some
arguments and does not return any value.
General Form Example
void function-name(argument
list)
{
Statements;
} 
void sum(int x, int y, int z )
{
int sum;
sum= x + y+ z;
cout<<”Sum =”<<sum;
}


Function with no arguments and with return values: In this method, the function receives no
arguments but return a value.
General Form Example
return-type function-
name() {
Statements;
return(value)
} 
int greatest( )
{
if(a>b);
return(a);
else
return(b);
}

Function with arguments and with return values:
 In this method, the function receives some arguments and returns a value.
General Form Example
return-type function-name(argument-list)
{
Statements;
return(value)
} 
float interest(float p, float t, float r)
{
si = (p * t * r)/100;
return(si);
} 

Recursive function: Recursive function is a function that calls itself. The process of calling
function by itself is called as recursion.
General Form
return-type function-name(argument-list)
{
Statements;
return(function-name(argument-list))
}

Object Oriented Concepts & C++ Programming
Prof. K Adisesha 63
Passing default arguments to functions:
 In C++, to call a function we need not pass all the values for the arguments to a function from the
calling function.
 It allows us to assign default values to the formal arguments.
 Default values can be assigned to the argument which does not have a matching argument int the
function call.
 Default values are assigned in the function prototype.
 The default values are assigned to the arguments as we initialize variables.
 Example:
float interest(float amt, int time, float rate =0.15)
si = interest(5000,5) //third argument is missing
si=interest(5000, 5, 0.2) //No missing arguments

Uses of default values:
 Default arguments are useful in situations where some arguments always have the same value.
 Default arguments provide flexibility to the programmer.
 Default arguments are used to add new arguments to the existing functions.
 Default arguments are used to combine similar functions into one.

Passing Constant arguments:
 In C++, we can declare some arguments as constants. The compiler cannot modify the arguments
marked as constants.
 Example:
int strlen(const char *p);
int total(const int x, const int y);

Pass by value or Call by Value:
 A function can be called by passing arguments from the calling function into the called function.
 Thus data is transferred through argument list.
 The calling function sends the data to the called function through actual parameters.
 The called function receives the data into its corresponding formal parameters.
 In pass by value, a copy of data sent by calling function stored in temporary locations,
 The called function uses these values as the initial values of the formal parameters.
 The formal parameters are processed or changed to generate the required result.
 However these changes are affected to the original values stored in the actual parameters.
 Example:
void main( )
{
void swap(int, int); //Function prototype
{
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 64
int a, b;
clrscr( );
cout<<”Enter two numbers”;
cin>>a>>b;
cout<<”Before calling the function: a=”<<a<<””and b=”<<b<<endl;
swap(a, b); //Actual Arguments
cout<<”After calling the function: a=”<<a<<””and b=”<<b<<endl;
getch();
}
void swap(int x, int y) //Formal Arguments
{
int temp;
temp = x;
x = y;
y= temp;
}

Pass by reference or call by reference:
 Sometimes we need to change the values of the actual arguments in the calling function. This is
not possible in the passing by value method.
 C++ allows us to pass arguments to the function by using reference variables.
 When we pass arguments by reference, the formal arguments int the called function become the
aliases to the actual arguments of the calling function i.e. the called function is actually uses the
original data with a different name.
 Example:
void main( )
{
void swap(int &, int &); //Function prototype
{
int a, b;
clrscr( );
cout<<”Enter two numbers”;
cin>>a>>b;
cout<<”Before calling the function: a=”<<a<<””and b=”<<b<<endl;
swap(a, b); //Actual Arguments
cout<<”After calling the function: a=”<<a<<””and b=”<<b<<endl;
getch();
}
void swap(int &x, int &y) //Formal Arguments
{
int temp;
temp = x;
x = y;
y= temp;
}
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 65
STRUCTURES
Introduction:
A structure is a collection of simple variables. The variables in a structure can be of same or
different types: some can be int, some can be float and so on.
 The data items in a structure are called the members of the structure.
 For C++ programmers, structures are one of the two important building blocks in the understanding
of objects and classes.
 The syntax of a structure is almost identical to that of a class. 

Defining a structure: A structure is a collection of various data elements under one name.
 The process of defining a structure includes giving the structure a name called the tag and telling
the compiler the name and the data type of each piece of data you want to be included in a structure.
 Syntax:
Struct structure-name
{
datatype member-name-1;
datatype member-name-2;
……………………..
datatype member-name-n;
};
o The keyword struct introduces the structure definition.
o Next comes the structure name or tag, which is part.
o The declarations of the structures members are enclosed in braces.
o The list of all structure members is called template.
o A semicolon follows the closing braces, terminating the entire structure.
Example: A structure definition to hold employee information.
struct employee
{
int idno; // 2 bytes
char name[15]; // 15 bytes
char designation[10]; // 10 bytes
float salary; // 4 bytes
};

 This structure is named employee. It contains four members: an integer named idno, a character
array to hold 15 characters for a name, another character array to hold 10 characters for designation
and float named salary.
 The structure requires an area in memory, which is 31 bytes long.

Declaring a structure or defining a structure variable:
 A structure can be declared (or a structure variable can be defined) as we defined a basic built-in
data type.
 The general form is
structure-name variable;
Example 1: student old_student, new_student;
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 66
old_student and new_student are the two structure variables declared as we declare built-in data
types.
Example 2: employee emp1, emp2;
emp1and emp2 are the two structure variables declared as belong to the user-defined data type employee.
 We can combine the definition of the structure and definition of structure variables.
Example:
struct employee
{
int idno
char name[15];
char designation[10];
float salary;
} emp1, emp2;
Accessing the elements of a structure
 After the structure variables are defined, we should know how the member of a structure variable
is accessed.
 A member of a structure is always part of a structure and it is not possible to refer the member
directly.
 The member of a structure can be accessed using dot operator.
 The syntax of dot operator is as follows:
structure_variable-name.member_name
 The structure member is written in three parts:
o The name of the structure variable (part1);
o The dot operator, which consists of a period (.)
o The member name (part3).
 Note: The real name of the dot operator is member access operator.
 Example 1: To access the name of the member emp1 of the tag employee, we write
 emp1.name;
 Example 2: To access the salary of the member emp2 of the tag employee, we write
 emp2.salary
Sample Program: To input and display the information of a student
#include<iostream.h>
#include<iomanip.h>
#include<string.h>
void main ( )
{
struct student
{
int regno;
char name[15];
char comb[4];
float perc;
} st;
cout<<”Enter the register number of the student:”;
cin>>st.regno;
cout<<”Enter the name of the student:”;
cin>>st.name;
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 67
cout<<”Enter the combination of the student:”;
cin>>st.comb;
cout<<”Enter the percentage of the student:”;
cin>>st.perc;
cout<<”Register No:”<<st.regno<<endl;
cout<<”Name: ”<<st.name<<endl;
cout<<”Combination:”<<st.comb<<endl;
cout<<”Percentage:”<<st.perc<<endl;
getch();
}
Sample run:
Enter the register number of the student: 1234
Enter the name of the student: Adisesha
Enter the combination of the student: PCMC
Enter the percentage of the student: 90.05
Register no: 1234
Name: Adisesha
Combination: PCMC
Percentage:90.05
Initializing a structure:
 Like any other data type, it is also possible to initialize the structure members of a structure
variable.
 Structures members are initialized when they are declared.
 Example: A program may contain the following initialization of the structure.
Employee emp1=
{
1234,
“Lakshmi”,
“Manager”,
10500.00
};
 This initialization initializes idno field to 1234, the name field to ”Lakshmi”, the designation field
to “Manager” and the salary field to 10500.00.
 A structure variable can be assigned to another structure variable.
Example: std2 = std1;
 Here, std1 and std2 are the structure variables of the structure std.
 The value of each member of std1 is assigned to the corresponding member of std2.
 Since a large structure can have dozens of members, such an assignment statement can require the
computer to do a considerable amount of work.
Note that one structure variable can be assigned to another only when they are of the same structure type.
If you try to assign a variable of one structure type to variable of another type, the compiler will complain.

Nested structures: A structure can be defined as a member of another structure. Such
structure where one structure is embedded within another structure is called as a nested structure.
Object Oriented Concepts & C++ Programming
Prof. K Adisesha 68
 During the declaration of nested structure, the definition of the embedded structure must appear
before the definition of outer structure.
 Example: consider the definition of the following structure.
struct distance
{
int feet;
float inches;
};
struct room
{
distance length;
distance breadth;
};
 The structure room contains another structure distance as one of its members.
 Whenever nested structures are used, the definition of the internal structure should precede the
definition of the outer structure.
 In the above example, the definition of the structure distance precedes the definition of the structure
room.
 Example: consider the definition of structure student.
struct date
{
int dayno;
char month[10];
int year;
};
struct student
{
int regno;
date doa, dob;
int marks;
}std;
To access the field regno of the structure std, we write std.regno.
To access the day number of the date of admission of the structure std, we write std.doa.dayno.
To access the year of date of birth of the student std, we write std.dob.year.

Array of structures: An array of structure is an array in which each element of the array is a
structure. Thus it is a collection of structures put together as an array.
 A single variable that represents a structure creates memory space to store one set of information.
 If we want to create memory space for more instances then we may have to increases the number
of variables or use the facility called arrays.
 For example, let us consider that there are 10 students studying in a college. We have defined the
structure so that it could maintain information about students of the college. If we have to store
data of 10 students, we need to use arrays rather than a single variable.
 When create an array of the structure, we are creating an array of the entire template. This can be
done as follows.
struct student
{
int regno;
char name [15];
char comb;
float fees;
} s [10];

More Related Content

PPTX
Types of Constructor in C++
PDF
Introduction to c++ ppt 1
PPTX
Structures in c language
PPTX
Expression and Operartor In C Programming
PDF
Keywords, identifiers ,datatypes in C++
PPTX
Array Introduction One-dimensional array Multidimensional array
PPTX
Destructors
PPTX
classes and objects in C++
Types of Constructor in C++
Introduction to c++ ppt 1
Structures in c language
Expression and Operartor In C Programming
Keywords, identifiers ,datatypes in C++
Array Introduction One-dimensional array Multidimensional array
Destructors
classes and objects in C++

What's hot (20)

PPTX
Control statements in c
PPTX
Lesson 7 io statements
PPT
Two dimensional array
PPTX
Function template
PPTX
data types in C programming
PPTX
Pointer in c
PPTX
Data types in C
PDF
I PUC CS Lab_programs
PDF
Chapter 5 - Operators in C++
PPTX
Command line arguments
PPTX
Characteristics of OOPS
PPTX
Array ppt
PPTX
Operators and expressions in c language
PPTX
Stack data structure
DOCX
PYTHON NOTES
 
PPSX
Function in c
PPTX
Exception handling c++
PDF
Lecture02(constants, variable & data types)
PDF
Structures and Pointers
PDF
Control statements in c
Lesson 7 io statements
Two dimensional array
Function template
data types in C programming
Pointer in c
Data types in C
I PUC CS Lab_programs
Chapter 5 - Operators in C++
Command line arguments
Characteristics of OOPS
Array ppt
Operators and expressions in c language
Stack data structure
PYTHON NOTES
 
Function in c
Exception handling c++
Lecture02(constants, variable & data types)
Structures and Pointers
Ad

Similar to 1 puc programming using c++ (20)

PPTX
object oriented programming language in c++
PDF
C++ Programming with examples for B.Tech
PDF
Deepakkumarassignmentnumberdiles1 01.pdf
PDF
PPTX
PCCF UNIT 2 CLASS.pptx
PDF
OOPS_Unit_1
DOCX
LECTURE NOTES ON Object Oriented Programming Using C++
PPT
Topic 1 PBO
PPTX
PCCF UNIT 2.pptx
PPTX
Programming in c++
PPTX
Programming in c++
PDF
CS305PC_C++_UNIT 1 notes jntuh third semester
PDF
C++ programing lanuage
PPT
Bca 2nd sem u-1 iintroduction
PPTX
PDF
Introduction to c++
PPTX
Unit 1 introduction to c++.pptx
DOCX
C++ Pogramming Language Course.docx Under
PPTX
Introduction to programming using c
PPTX
Oop in c++ lecture 1
object oriented programming language in c++
C++ Programming with examples for B.Tech
Deepakkumarassignmentnumberdiles1 01.pdf
PCCF UNIT 2 CLASS.pptx
OOPS_Unit_1
LECTURE NOTES ON Object Oriented Programming Using C++
Topic 1 PBO
PCCF UNIT 2.pptx
Programming in c++
Programming in c++
CS305PC_C++_UNIT 1 notes jntuh third semester
C++ programing lanuage
Bca 2nd sem u-1 iintroduction
Introduction to c++
Unit 1 introduction to c++.pptx
C++ Pogramming Language Course.docx Under
Introduction to programming using c
Oop in c++ lecture 1
Ad

More from Prof. Dr. K. Adisesha (20)

PDF
MACHINE LEARNING Notes by Dr. K. Adisesha
PDF
Probabilistic and Stochastic Models Unit-3-Adi.pdf
PDF
Genetic Algorithm in Machine Learning PPT by-Adi
PDF
Unsupervised Machine Learning PPT Adi.pdf
PDF
Supervised Machine Learning PPT by K. Adisesha
PDF
Introduction to Machine Learning PPT by K. Adisesha
PPSX
Design and Analysis of Algorithms ppt by K. Adi
PPSX
Data Structure using C by Dr. K Adisesha .ppsx
PDF
Operating System-4 "File Management" by Adi.pdf
PDF
Operating System-3 "Memory Management" by Adi.pdf
PDF
Operating System Concepts Part-1 by_Adi.pdf
PDF
Operating System-2_Process Managementby_Adi.pdf
PDF
Software Engineering notes by K. Adisesha.pdf
PDF
Software Engineering-Unit 1 by Adisesha.pdf
PDF
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
PDF
Software Engineering-Unit 3 "System Modelling" by Adi.pdf
PDF
Software Engineering-Unit 4 "Architectural Design" by Adi.pdf
PDF
Software Engineering-Unit 5 "Software Testing"by Adi.pdf
PDF
Computer Networks Notes by -Dr. K. Adisesha
PDF
CCN Unit-1&2 Data Communication &Networking by K. Adiaesha
MACHINE LEARNING Notes by Dr. K. Adisesha
Probabilistic and Stochastic Models Unit-3-Adi.pdf
Genetic Algorithm in Machine Learning PPT by-Adi
Unsupervised Machine Learning PPT Adi.pdf
Supervised Machine Learning PPT by K. Adisesha
Introduction to Machine Learning PPT by K. Adisesha
Design and Analysis of Algorithms ppt by K. Adi
Data Structure using C by Dr. K Adisesha .ppsx
Operating System-4 "File Management" by Adi.pdf
Operating System-3 "Memory Management" by Adi.pdf
Operating System Concepts Part-1 by_Adi.pdf
Operating System-2_Process Managementby_Adi.pdf
Software Engineering notes by K. Adisesha.pdf
Software Engineering-Unit 1 by Adisesha.pdf
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
Software Engineering-Unit 3 "System Modelling" by Adi.pdf
Software Engineering-Unit 4 "Architectural Design" by Adi.pdf
Software Engineering-Unit 5 "Software Testing"by Adi.pdf
Computer Networks Notes by -Dr. K. Adisesha
CCN Unit-1&2 Data Communication &Networking by K. Adiaesha

Recently uploaded (20)

PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PPTX
Pharma ospi slides which help in ospi learning
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
Cell Structure & Organelles in detailed.
PPTX
GDM (1) (1).pptx small presentation for students
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
Open Quiz Monsoon Mind Game Final Set.pptx
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PPTX
Open Quiz Monsoon Mind Game Prelims.pptx
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
master seminar digital applications in india
FourierSeries-QuestionsWithAnswers(Part-A).pdf
human mycosis Human fungal infections are called human mycosis..pptx
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Microbial disease of the cardiovascular and lymphatic systems
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Pharma ospi slides which help in ospi learning
Anesthesia in Laparoscopic Surgery in India
Cell Structure & Organelles in detailed.
GDM (1) (1).pptx small presentation for students
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Renaissance Architecture: A Journey from Faith to Humanism
Open Quiz Monsoon Mind Game Final Set.pptx
2.FourierTransform-ShortQuestionswithAnswers.pdf
O7-L3 Supply Chain Operations - ICLT Program
Abdominal Access Techniques with Prof. Dr. R K Mishra
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
Open Quiz Monsoon Mind Game Prelims.pptx
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
master seminar digital applications in india

1 puc programming using c++

  • 1. Object Oriented Concepts & C++ Programming Prof. K Adisesha 1 OBJECT ORIENTED CONCEPTS Introduction The programming languages deal with two important aspects – data and algorithm. Data is the main substance of the program and the algorithms are the methods that use these programs. OOP is the principle of design and development of programs using the modular approach.  Procedural programming: The procedural programming focuses on processing of instructions in order to perform a desired computation. Therefore, it emphasizes more on doing things like algorithms. This programming is lengthy, increases the complexity of program, difficult to understand and modify the program. This technique is used in conventional programming languages such as C and Pascal. For example, procedural programs make use of branching statements, where the flow of control changes its path according to the result of the test expression.  Structured programming: Structured programming approach was a disciplined approach which limits the branching to a small set of well-behaved construction (ex: if, if-else, while etc). The idea of Top-down design is to break a large program into smaller programs. The major drawback is that it is very difficult to model the real world scenario using this model.  Object oriented programming: Object oriented programming (OOP) is a concept that combines both the data and the functions that operate on that data into a single unit called the object. Object is an identifiable entity with some characteristics and behavior. OOP follows bottom-up design technique. Class is the major concept that plays important role in this approach. Class is a template that represents a group of objects which share common properties and relationships.  OOPs characteristics: The general concepts of OOPs includes 1. Modularity: Module is a logically self-contained unit that can be tested and executed independently. Modularity is a technique adopted to divide a complex problem into a number of self-contained independent programming fragments or modules. 2. Abstraction: Abstraction is an act, which represents the essential features of an entity without including explanations or any background details about it. 3. Data Encapsulation: Wrapping of data and functions into a single unit is called data encapsulation. The concept of insulating the data from direct access by the program is called data hiding. 4. Inheritance: Inheritance is the process by which objects of one class acquires the properties of the objects of another class. (Or) The process of deriving a new class from the existing class is called inheritance. 5. Polymorphism: Polymorphism is the ability for a message to be processed in more than one form. The process of making an operator to exhibit different behaviors in different instances is known as operator overloading. Using a single function name to perform different types of tasks is known as function overloading.
  • 2. Object Oriented Concepts & C++ Programming Prof. K Adisesha 2 6. Dynamic Binding: Binding means linking of a procedure call to the code to be executed when it is called. Dynamic binding means binding the procedure call during program run rime. 7. Message Passing: Passing message objects and invoking the function by the object by sending a message is known as message passing.   OOPs Benefits:  OOPs model the real world entity very well.  Inheritance eliminates the redundancy (repetition) of code and hence supports code reusability.  Data hiding helps to build secured programs.  Multiple instances (objects) can be created.  Work can be divided easily.  OOPs can be easily upgraded from small to large systems.  Complexity can be easily managed.  Message passing concept helps the objects to communicate and share data.  OOPs disadvantages:  OOPs use tricky method to do the programming.  Special skills such as thinking in terms of design skills, programming skills and object is required for a programmer.  Proper planning and design is required before programming using OOPs technique.  OOPs Applications:  Object oriented databases.  Hypermedia, expert text and hypertext.  Artificial intelligence and expert systems.  Decision support systems and office automation systems.  Parallel programming and neural networks.  CAD, CAM, CIM systems.  Simulation and modeling.
  • 3. Object Oriented Concepts & C++ Programming Prof. K Adisesha 3 INTRODUCTION TO C++  History of C++:  Until 1980, C programming was widely popular, and slowly people started realizing the drawbacks of this language, at the same time a new programming approach that was Object Oriented Programming.  Bjarne Stroustrup and his team at Bell Laboratories (AT&T, USA) to help implement simulation projects in an object-oriented and efficient way created the C++ programming language.  C++ is a superset of C because; any valid C program is valid C++ program too but not the vice versa is not true.  C++ can make use of existing C software libraries with major addition of “Class Construct”.  This language was called “C with classes” and later in 1983, Rick Mascitii named it “C++”.  As the name C++ implies, C++ was derived from the C programming language: ++ is the increment operator in C.  Characteristics of C++:  Object-Oriented Programming: It allows the programmer to design applications like a communication between object rather than on a structured sequence of code. It allows a greater reusability of code in a more logical and productive way.  Portability: We can compile the same C++ code in almost any type of computer & operating system without making any changes.  Modular Programming: An application’s body in C++ can be made up of several source code files that are compiled separately and then linked together saving time.  C Compatibility: Any code written in C can easily be included in a C++ program without making any changes.  Speed: The resulting code from a C++ compilation is very efficient due to its duality as high-level and low-level language.  Machine independent: It is a Machine Independent Language.  Flexibility: It is highly flexible language and versatility.  Wide range of library functions: It has huge library functions; it reduces the code development time and reduces cost of software development.  System Software Development: It can be used for developing System Software Viz., Operating system, Compilers, Editors and Database.  C++ Character Set: Character Set means the valid set of characters that a language can recognizes. The character set of C++ includes the following: Alphabets Upper letters case A, B, C, D... X, Y, Z Lower letters case a, b, c, d …. x, y, z Digits 0,1,2,3.......... 9
  • 4. Object Oriented Concepts & C++ Programming Prof. K Adisesha 4 Special Characters , comma . Period ' Apostrophe : Colon ; Semicolon ? Question mark ! Exclamation _ Underscore | Pipeline {Left brace } Right Brace # Hash [Left bracket ] Right Bracket A Caret (Left parenthesis ) Right parenthesis & ampersand / Slash Back slash ~ Tilde + Plus sign - Minus Sign < Less Than * Asterisk % Percentage > Greater Than C++ Tokens: The smallest individual unit in a program is known as token. These elements help us to construct statements, definitions, declarations, and so on, which in turn helps us to construct complete program. Tokens used in C++ are:  Identifier  Reserved Keywords  Constants or Literals  Punctuators  Operators  Identifiers: Identifiers is a name given to programming elements such as variables, functions, arrays, objects, classes, etc. It contains letters, digits and underscore. C++ is a case sensitive; it treats uppercase and lowercase characters differently. The following are some valid identifiers: Student Reg101 a1e2r3 _dos Rules to be followed while creating identifiers:  Identifiers are a sequence of characters which should begin with the alphabet either from A-Z  (Uppercase) or a-z (lowercase) or _ (underscore).  C++ treats uppercase and lowercase characters differently. For example, DATA is not same as data.  No Special character is allowed except underscore “_”.  Identifier should be single words i.e. blank spaces cannot be included in identifier.  Reserved Keywords should not be used as identifiers.  Identifiers should be of reasonable length.  Keywords: Keyword is a predefined word that gives special meaning to the complier. The programmer is not allowed to change its meaning. These are reserve for special purpose and must not be used as identifier name. Example: for, if, else, this, do, float, while, switch etc.
  • 5. Object Oriented Concepts & C++ Programming Prof. K Adisesha 5 There are keywords in C++ as mentioned below:  Constants: A constant are identifiers whose value does not change during program execution. Constants are sometimes referred to as literal. A constant or literal my be any one of the following:  Integer Constant  Floating Constant  Character Constant  String Constant  Integer Constant: An integer constant is a whole number, which can be either positive or negative. They do not have fractional part or exponents. We can specify integer constants in decimal, octal or hexadecimal form.  Decimal Integer Constant: It consists of any combination of digits taken from the set 0 to 9. For example: int a = 100; //Decimal Constant int b = -145 // A negative decimal constant int c = 065 // Leading zero specifies octal constant, not decimal  Octal Integer Constant: It consists of any combination of digits taken from the set 0 to 7. However the first digit must be 0, in order to identify the constant as octal number. For example: int a = 0123; //Octal Constant int b = 097; // Error: 9 is not an octal digit.  Hexadecimal Integer Constant: A Sequence of digits begin the specification with 0X or 0x, followed by a sequence of digits in the range 0 to 9 and A (a) to F(f). For example: int a = 0x234; int b = -0XABF;
  • 6. Object Oriented Concepts & C++ Programming Prof. K Adisesha 6  Unsigned Constant: To specify an unsigned type, use either u or U suffix. To specify a long type, use either the l or L suffix. For example: unsigned a = 328u; //Unsigned value long b = 0x7FFFFFL; //Long value specified as hex constant unsigned long c = 0776745ul; //Unsigned long values as octal constant  Floating Point Constant: Floating-point constants are also called as “real constants”. These values contain decimal points (.) and can contain exponents. They are used to represent values that will have a fractional part and can be represented in two forms (i.e. fractional form and exponent form)  Floating-point constants have a “mantissa”, which specifies the value of the number, an “exponent” which specifies the magnitude of the number, and an optional suffix that specifies the constant’s type.  The mantissa is specified as a sequence of digits followed by a period, followed by an optional sequence of digits representing the fractional part of the number.  The exponent, if present, specifies the magnitude of the number as a power of 10. o Example: 23.46e0 // means it is equal to 23.46 x 100 = 23.46 x 1 = 23.46  It may be a positive or negative number. A number with no sign is assumed to be a positive number. o For example, 345.89, 3.142  Character Constants: Character constants are specified as single character enclosed in pair of single quotation marks.  For example char ch = ‘P’; //Specifies normal character constant  A single character constant such as ‘D’ or ‘r’ will have char data type. These character constants will be assigned numerical values.  The numerical values are the ASCII values, which are numbered sequentially for both uppercase and lowercase letters.  There are certain characters used in C++ which represents character constants. These constants start with a back slash ( ) followed by a character. They are normally called as escape sequence. Some of the commonly used escape sequences are. Escape Sequence Meaning Escape Sequence Meaning ’ Single Quote ” Double Quote ? Question Mark Back Slash 0 Null Character a Audible Bell b Backspace f New Page n New Line r Carriage Return t Horizontal Tab v Vertical Tab nnn Arbitrary octal value xnn Arbitrary Hexa Value  Escape Sequence is a special string used to control output on the monitor, represented by a single character, and hence occupy one byte.
  • 7. Object Oriented Concepts & C++ Programming Prof. K Adisesha 7 String Constants: A string constant consists of zero or more character enclosed by double quotation marks (“).  Multiple character constants are called string constants and they are treated as an array of char.  By default compiler adds a special character called the “Null Character” (0) at the end of the string to mark the end of the string. o For example: char str[15] = “C++ Programming” ;  This is actually represented as char str[15] = “C++ Programming0” in the memory.  Punctuators: Punctuators in C++ have syntactic and semantic meaning to the compiler. Some punctuators can be either alone or in combination. The following characters are used as punctuators, which are also known as separators in C++. Punctuator Name Function ! Exclamation Used along with “=” to indicate “not equal to” % Percentage Used along with format specifiers & Ampersand Used to represent address location or bitwise operation ; Semicolon Used to represent statement terminator. [ ] Brackets Used to array subscripts () Parenthesis Used to represent function calls and function parameters. { } Braces Used to represent start and end of a block of code. # Ash sign Used to represent preprocessor directives. Back slash Used to represent escape sequence : Colon Used to represent labeled statement = Equal to Used to represent an assigning operator. C++ Operators: An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C++ is rich in built-in operators and there are almost 45 different operators. Operators in C++ are can be divided into the following classes:  Arithmetic Operator  Relational Operator  Logical Operator  Unary Operator  Conditional Operator  Bitwise Operator  Assignment Operator  Other Operator
  • 8. Object Oriented Concepts & C++ Programming Prof. K Adisesha 8 Operator operates on constants and variables, which are called operands. Operators may also be classified on the number of operands they act on either: Unary Binary Ternary Unary operators Operate on only one operand. Binary operator Operates on two operands. Ternary operator Operates on three operands. Example: ++, - - +, -, *, /, %, &&, || ?: Unary Operators Unary operators have only one operand; they are evaluated before any other operation containing them is evaluated. The following are the list of unary operators. Operator Name Function ! Logical NOT If a condition is true then Logical NOT operator will make false. & Address-of Used to give the address of the operand ~ One’s Complement Converts 1 to 0 and 0 to 1 * Pointer dereference Used along with the operand to represent the pointer data + Unary plus Used to represent a signed positive operand ++ Increment Used to increment an operand by 1 - Unary negation Used to represent a signed negative operand - - Decrement Used to represent an operand by 1 Increment Operator: Increment operator is used to increasing the value of an integer by one. This is represented by “++”. Example: a++, a+1  Decrement Operator: Decrement operator is used to decreasing the value of an integer by one. This is represented by “--”. Example: a--, a-1 Both the increment & decrement operators come in two versions: Prefix increment/decrement: When an increment or decrement operator precedes its operand, it is called prefix increment or decrement (or pre-increment / decrement).  In prefix increment/decrement, C++ performs the increment or decrement operation before using the value of the operand.  Example: If sum = 10 and count =20 then Sum = sum + (++count);  First count incremented and then evaluate sum = 31.
  • 9. Object Oriented Concepts & C++ Programming Prof. K Adisesha 9 Postfix increment/decrement: When an increment or decrement operator follows its operand, it is called postfix increment or decrement (or post-increment / decrement).  In postfix increment/decrement, C++ first uses the value of the operand in evaluating the expression before incrementing or decrementing the operand’s value.  Example: If sum = 10 and count =20 then Sum = sum + (count++);  First evaluate sum = 30, and then increment count to 21.  Binary Operators: The binary operators are those operators that operate on two operands. They are as Arithmetic, Relational, Logical, Bitwise, and Assignment operators.  Arithmetic Operator: Arithmetic operators are used to performing the basic arithmetic operations such as arithmetic, subtraction, multiplication, division and modulo division (remainder after division). Operator Description Example( a=10, b=20) + Adds two operand a + b = 30 - Subtracts second operand from the first a - b = -10 * Multiply both operand a * b = 200 / Divide numerator by denominators b / a = 2 % Modulus operators and remainder of after an integer division b % a = 0 Relational Operator: Relational Operator is used to comparing two operands given in expressions. They define the relationship that exists between two constants.  For example, we may compare the age of two persons or the price of two items….these comparisons can be done with the help of relational operators.  The result in either TRUE(1) or FALSE(0).Some of the relational operators are: Operator Description Example (a=10, b=5) < Checks if the value of left operand is less than the value of right operand a < b returns false(0) <= Checks if the value of left operand is less than or equal to the value of right operand a <= b returns false(0) > Checks if the value of left operand is greater than the value of right operand a > b returns true(1) >= Checks if the value of left operand is greater than or equal to the value of right operand a >= b returns false(0) = = Checks if the value of two operands is equal or not a = = b returns false(0) ! = Checks if the value of two operands is equal or not a ! = b returns true(1)
  • 10. Object Oriented Concepts & C++ Programming Prof. K Adisesha 10 Logical Operators: Logical operators are used to testing more than one condition and make decisions. Some of the logical operators are Operator Meaning Description Example && Logical AND If both the operands are non-zero then condition becomes true. If a=10 and b=5 then, ((a==10) && (b>5)) returns false. || Logical OR If any of the two operands is nonzero then condition becomes true. If a=10 and b=5 then, ((a==10) || (b>5)) returns true. ! Logical NOT If a condition is true then the Logical NOT operator will make false. If a=10 then, !(a==10) returns false. Bitwise Operators: A bitwise operator works on bits and performs bit-by-bit operation. Bitwise operators are used in bit level programming. Operators Meaning of operators & Bitwise AND 1 Bitwise OR A Bitwise exclusive OR ~ Bitwise complement Assignment Operators: The most common assignment operator is =. This operator assigns the value on the right side to the left side. Example: var = 5 //5 is assigned to var a = b; //value of b is assigned to a 5 = b; // Error! 5 is a constant.  C++ Shorthand’s: C++ Offers special shorthand is that simplify the coding of a certain type of assignment statements. The general format of C++ shorthand’s is: Variable Operator = Expression Following are some examples of C++ shorthand’s: x - = 10; Equivalent to x = x - 10; x * = 5; Equivalent to x = x * 5; x / = 2 ; Equivalent to x = x / 2; x % = z; Equivalent to x = x % z;
  • 11. Object Oriented Concepts & C++ Programming Prof. K Adisesha 11 Conditional Operator: A ternary operator pair ”?:” is available in C++ to construct conditional expressions of the form: exp1? exp2: exp3, where exp1, exp2, and exp3 are expressions, The operator “?:” works as follows: exp1 is evaluated first. If it is true, then the expression exp 2 is evaluated and becomes the value of the expression. If exp1 is false, exp3 is evaluated and its value becomes the value of the expression. Example: a=10; b=5; x = (a>b) ? a:b; Special Operator: Operators Meaning of operators sizeof() It is a unary operator which is used in finding the size of the data type. Example: sizeof(a) , (comma) Comma operators are used to linking related expressions together. Example: int a=10, b=5 . (dot) and -> (arrow) Member Operator used to reference individual members of classes, structure and unions. cast Casting Operator convert one data type to another. & Address Operator & returns the address of the variable. * Pointer Operator * is pointer to a variable. Precedence of Operators or Hierarchy of Operators In C++:  An expression is a combination of opcode and operand.  The operators would be arithmetic, relational, and logical operators.  If the expression contains multiple operators, the order in which operations carried out is called the precedence of operators. It is also called as priority or hierarchy.  The Operators with highest precedence appear at the top of the table and those with the lowest appear at the bottom. Category Operator Associativity Postfix ( ) [ ]-> . ++-- Left to Right Unary = - ! ~ ++ -- (type) * & sizeof Right to Left Multiplicative */ % Left to Right Additive + - Left to Right Shift << >> Left to Right Relational <<= >>= Left to Right Equality == != Left to Right Bitwise AND & Left to Right
  • 12. Object Oriented Concepts & C++ Programming Prof. K Adisesha 12 Bitwise XOR ^ Left to Right Bitwise OR 1 Left to Right Logical AND && Left to Right Logical OR II Left to Right Conditional ?: Right to Left Assignment = += _= *= /= %= Right to Left What is operator precedence in C++?  “The order in which different types of operators are evaluated is called as operator precedence”.  It is also known as hierarchy of operators.  In any expression, Operators having higher precedence are evaluated first.  The expression is evaluated in the following sequence. o Arithmetic o Relational o Logical  There are some operators, which are given below. The higher the position of an operator is, higher is its priority. Operator Meaning ! Logical NOT ( ) Parenthesis +, -, *, /, % Arithmetic and modulus <, >, <=, >= Relational && Logical AND II Logical OR = Assignment Type Conversion: Converting an expression of a given type into another type is known as type- casting or type conversion. Type conversions are of two types, they are:  Implicit Conversion  Explicit Conversion  Implicit Conversion: Implicit Conversions do not require any operator. They are automatically performed when a value is copied to a compatible type.  The C++ compiler will implicitly convert or promote values if it can be done safely.  If not it will generate a warning or an error depending on the conversion required.  For Example: short a = 2000; int b; b = a;
  • 13. Object Oriented Concepts & C++ Programming Prof. K Adisesha 13 Explicit Conversion: C++ is a strong-typed language. Many conversions, especially those that imply a different interpretation of the value, require an explicit conversion.  For Example: short a = 2000; int b; b = (int) a; //c-like cast notation b = int (a) // functional notation  Implicit Conversions do not require any operator.  Translating a C++ program:   General Structure of C++ Program: General Syntax Example Program /* General Structure */ Pre-processor Directives main ( ) { Variable Declarations; Executable Statements; } /* A Simple Program to display a Message * / #include<iostream.h> void main( ) { cout<<” This is the first C++ Program”; } Different programming languages have their own format of coding. The basic components of a C++program are: 
  • 14. Object Oriented Concepts & C++ Programming Prof. K Adisesha 14 Comments or Documentation Section: Comments are the pieces of code that compiler ignores to compile. There are two types of comments in C++. 1. Single line comment: The comments that begin with // are single line comments. The Compiler simply ignores everything following // in the same line. 2. Multiline comment: The multiline comment begin with /* and end with */ . This means everything that falls between /* and */ is consider a comment even though it is spread across many lines.  Pre-processor Directives (Linker Section): The linker section begins with a hash (#) symbol. #include……is a preprocessor directive.  It is a signal for preprocessor, which runs the compiler.  The statement directs the compiler to include the header file from the C++ Standard library.  Example: # include<iostream.h> #include<conio.h> # include<math.h>  Definition: In this section, we can define constants, expressions, structures, functions, classes and objects. After the linker section gets executed, the definition section is executed by the compiler and this section is optional.  Example: # define PI 3.14  Global Declaration: We can declare variables here and those variables, which are declared before the main function or any other function then the life or scope of such variables, remain throughout function and can be used by other functions of the program.  main ( ) function: As the name itself indicates, this is the main function of every C++ program. Execution of a C++ program starts with main ( ).  No C++ program is executed without the main () function.  The function main () should be written in the lowercase letter and shouldn’t be terminated with a semicolon.  It calls other library functions and user-defined functions.  There must be one and only main ( ) in every C++ program.  Braces { }: The statements inside any function including the main ( ) function is enclosed with the opening and the closing braces. { …………..; …………..; }  Declarations: The declaration is the part of the C++ program where all the variables, arrays, and functions are declared with their basic data types. This helps the compiler to allocate the memory space inside the computer memory. Example: int sum, x, y; 
  • 15. Object Oriented Concepts & C++ Programming Prof. K Adisesha 15 Statements: These are instructions to the computer to perform some specific operations. These statements can be expressions, input-output functions, conditional statements, looping statements, function call and so on. They also include comments.  Every statement end with semicolon “;” except control statements.  Semicolon “;” also known as Terminator. Example: A Simple C++ program to display a message on the screen: #include<iostream.h> #include<conio.h> void main () { clrscr(); cout<< “Welcome to Computer Science Class”; getch(); } The program produces following output: Welcome to Computer Science Class  Library Function: C++ provides many built-in functions that save the programming time. They include mathematical functions, character functions, string functions, and console input-output functions.   Mathematical Function: Some of the important mathematical functions in header file math.h are Function Meaning sqrt(x) Square Root of X pow(x, y) x raised to the power y sin(x) Sine of an angle x (measured in radians) cos(x) Cosine of an angle x (measured in radians) tan(x) Tangent of an angle x (measured in radians) asin(x) Sin-1 (x) where x (measured in radians) acos(x) Cos-1 (x) where x (measured in radians) exp(x) Exponential function of x (ex) log(x) Logarithm of x log 10(x) Logarithm of number x to base 10 abs(x) Absolute value of integer number x fabs(x) Absolute value of real number x
  • 16. Object Oriented Concepts & C++ Programming Prof. K Adisesha 16 Character Function: Some of the important mathematical functions in header file ctype.h are: Function Meaning isalpha(c) It returns True if C is an uppercase letter and false if c is lowercase. isdigit(c) It returns True if c is a digit (0 to 9) otherwise false isalnum(c) It returns True if c is digit from 0 through 9 or an alphabetic character (either uppercase or lowercase) otherwise false islower(c) It returns True if c is a lowercase letter otherwise False isupper(c) It returns True if c is a uppercase letter otherwise False toupper(c) It converts c to uppercase letter tolower(c) It converts c to lowercase letter. String Function: Some of the important mathematical functions in header file string.h are Function Meaning strlen(s) It gives the no. of characters including spaces present in a string s. strcat(s1, s2) It concatenates the string s2 onto the end of the string s1. The string s1 must have enough locations to hold s2. strcpy(s1, s2) It copies character string s2 to string s1. The s1 must have enough storage locations to hold s2. strcmp((s1,s2)==0) strcmp((s1,s2)>0) strcmp((s1,s2)<0) It compares s1 and s2 and find out whether s1 equal s2, greater than s2 or s1 less than s2. strcmpi ((s1,s2)==0) strcmpi((s1,s2)>0) strcmpi((s1,s2)<0) It compares s1 and s2 ignoring case and find out whether s1 equal s2, greater than s2 or s1 less than s2. strrev(s) It converts a string into its reverse. strupr(s) It converts a string s into upper case. strlwr(s) It converts a string into lower case.
  • 17. Object Oriented Concepts & C++ Programming Prof. K Adisesha 17 Console I/O Function: Some of the important mathematical functions in header file stdio.h are Function Meaning getchar() It returns a single character from a standard input device (keyboard). It takes no parameter and the returned value is the input character. putchar() It takes one argument, which is the character to be sent to the output device. It also returns this character as a result. gets() It gets a string terminated by a newline character from the standard input stream stdlin.puts() It takes a string which is to be sent to output device. General Purpose standard Library Function: Some of the important mathematical functions in header file stdio.h are Function Meaning randomize() It initialize/seeds the random number generator with a random number. random(n) It generates a random number between 0 to n-1. atoi(s) It converts string s into a numerical representation. itoa(n) It converts a number to a string. Some more Function:  getch( ) and getche( ) functions  On execution, the cursor blinks, the user must type a character and press enter key.  The value of the character returned from getche( ) is assigned to ch.  The getche( ) function echoes the character on the screen.  Another function, getch( ), is similar to getche( ) but does not echo character to the screen.
  • 18. Object Oriented Concepts & C++ Programming Prof. K Adisesha 18 DATA TYPES Introduction To understand any programming languages we need to first understand the elementary concepts, which form the building block of that program. The basic building blocks include the variables, data types etc. C++ provides a set of data types to handle the data that is used by the program.  Variable: A variable is an object or element and it is allowed change during the execution of the program. Variable represents the name of the memory location. The variable_name is an identifier. These variables are used to denote constants, arrays, function, structures, classes and files. The variables are named storage location whose values can be manipulated during program run. Declaration of a variable: The syntax for declaring a variable is: datatype variable_name; Some valid variables are: reg_no, marks, name, stud, dob; Some invalid variables are:  Double - keyword cannot be name of the variable.  Total marks - empty spaces are not allowed between variables names  2student - variable name should be begin with an alphabet  ?result - variable should begin with alphabet or underscore only.  Initializing a variable: The syntax to initialize a variable is: data_type variable_name = value; Example: int b = 100; There are two values associated with a variable known as lvaue and rvalue. It means, for example,  let p be a variable declared of the type int. then int p = 100; Here, name of the variable is p o values assigned to variable is 100 i.e. rvalue o memory address location is 2000 i.e. lvalue  Lvalue is the location value. It holds the memory address location at which the data value is stored.  Rvalue is the data value. It holds the value assigned to the variable by the programmer i.e. Rvalue of p = 100.  Data Types: Data Types can be defined as the set of values, which can be stored in a variable along with the operations that can be performed on those values.  C++ defines several types of data and each type has unique characteristics.  C++ data types can be classified as: 1. The fundamental data type(built-in data) 2. Derived Data type 3. User-defined data type   The simple or fundamental data types are the primary data types, which are not composed of any other data types.  The simple data types/fundamental data types include int, char, float, double and void.
  • 19. Object Oriented Concepts & C++ Programming Prof. K Adisesha 19  The int type: The int type is used to store integers. Integers are whole numbers without any fractional parts. This includes number such as:  1, 45 and -9 are integers. 5.2 is not an integer because it contains a decimal point.  The integer can be positive or negative values and the ranges of number we can store are from - 32786 to 32767.  An integer is allocated 2 bytes (16 bits) of memory space.  The possible operations include addition, subtraction, multiplication, division, remainder etc.  The General form of an integer declaration is: int variable_name;  Example: int a, b=5;  The char type: It is character data type to store any character from the basic character set. Characters are enclosed in single quotation marks (‘). ‘A’, ‘a’, ‘b’, ‘9’, ‘+’ etc. are character constants.  When a variable of type char is declared, the compiler converts the character to its equivalent ASCII code.  A character is allocated only 1 byte (8 bits) of memory space.  A character is represented in a program by the keyboard char.  The general form of a character declaration is: char variable_list;  Example: char alpha=’a’;  The float type: This represents the number with fractional part i.e. real numbers. The float type is used to store real numbers. Number such as 1.8, 4.5, 12e-5 and -9.66 are all floating-point numbers. It can also be both positive and negative. The range of numbers we can store from -34e-38 to 3.4e38. Float is allocated 4 bytes (32 bits) of memory space.  The general form of a float declaration is: float variable_name;  Example: float a=5.5;
  • 20. Object Oriented Concepts & C++ Programming Prof. K Adisesha 20 The double type: The double and float are very similar. The float type allows you to store single precision floating point numbers, while the double keyword allows you to store double precision floating- point numbers. Its size is typically 8 bytes of memory space. The range of numbers we can store are from -1.7e308 to 1.7e308.  The general form of a double declaration is: double variable_list;  Example: double a = 5.5e-7; //a is equivalent to 5.5x10-7  The void type: The void data type has no values and no operations. In other words, both the set of values and set of operations are empty.  Example: void main( )  In this declaration the main function does not return any value.  The bool type: The bool type has logical value true or false. The identifier true has the value 1, and the identifier false has the value 0.  The general form of a bool declaration is: bool variable_name;  Example: bool legal_age=true;  The statement legal_age= (age>=21); assigns the value true if age is greater than or equal to 21 or else it returns the value false.  Derived data types: These data types are constructed using simple or fundamental data types. This includes arrays, functions, pointers and references.  User defined data types: These data types are also constructed using simple or fundamental data types. Some user defined data types include  Enumerated  Structure  Union  Class  Enumerated data type: AN enumeration is a user defined type consisting of a set of named constants called enumerators.  enum is a keyword that assigns values 0, 1, 2…… automatically.  This helps in providing an alternative means for creating symbolic constants.  The syntax for enum is as follows: o enum [tag] { enum – list} ; //for definition for enumerated type  Example : enum choice { bad, satisfactory, good, very_good}; choice mychoice;
  • 21. Object Oriented Concepts & C++ Programming Prof. K Adisesha 21 INPUT AND OUTPUT OPERATORS  Introduction: The input output operations are done using library functions cin and cout objects of the class iostream. Using the standard input and output library, we will able to interact with the user by printing message on the screen and getting the user’s input from the keyboard.  A stream is an object where a program can either insert/extract characters to/from it.  The standard C++ library includes the header file iostream, where the standard input and output stream objects are declared.  Input Operator “>>”: The standard input device is usually the keyboard. Input in C++ is done by using the “stream extraction” (>>) on the cin stream. “cin” stands for “console input”.   The operator must be followed by the variable that will store the data that is going to be extracted from the stream.  Example: int age; cin>>age;  The first statement declares a variable of the type int called age, and the second one waits for an input from cin (the keyboard) in order to store it in this integer variable.  It can only process the input from the keyboard once the RETURN key has been pressed.  We must always consider the type of the variable that we are using as a container with cin extraction. For example, if we request an integer we will get an integer.  Output Operator “<<”: The standard output device is the screen (Monitor). Outputting in C++ is done by using the object followed by the “stream insertion” (<<). “cout” stands for console output. Example: cout<<”Let us learn C++”; // prints Let us learn C++ on the screen.  The << operator inserts the data that follows it into the stream preceding it.  The sentence in the instruction is enclosed between double quotes ( ” ), because it is constant string of characters.  Whenever we want to use constant strings of characters we must enclose them between double quotes (“) so that they can be clearly distinguished from the variables name. Example: cout<<”sum”; //prints sum cout<<sum; //prints the content of the variable sum
  • 22. Object Oriented Concepts & C++ Programming Prof. K Adisesha 22 Cascading of I/O Operators: C++ supports the use of stream extraction (>>) and stream insertion (<<) operator many times in a single input (cin) and output (cout) statements. If a program requires more than one input variable then it is possible to input these variables in a single cin statement using multiple stream extraction operators. Similarly, when we want to output more than one result then this can be done using a single cout statement with multiple stream insertion operators. This is called cascading of input output operators. Example: cout<<”Enter the first number”; cin>>a; cout<<”Enter the second number”; cin>>b; Instead of using cin statement twice, we can use a single cin statement and input the two numbers using multiple stream extraction operators. cout<<”Enter the two number”; cin>>a>>b; Similarly, we can even output multiple results in a single cout statements using cascading of stream insertion operators. cout<<”The sum of two number is”<<sum<<endl;  Formatted Output (Manipulators): Manipulators are the operators used with the insertion operator << to format the data display. The most commonly used manipulators are “endl” and “setw”. In order to use this manipulator, it is must to include header file iomanip.h  The endl manipulator : The endl manipulator, when used in a output statement , causes a line feed to be inserted. It has same effect as using new line character “n”. cout<< “ Narayana PU Science College”<<endl; cout<< “ Bangalore”; o The output of the above code will be: Narayana PU Science College Bangalore  The setw( ) Manipulator : The setw( ) manipulator sets the width of the field assign for the output. It takes the size of the field (in number of character) as a parameter. The output will be right justified. Example the code : cout<<setw(6)<<”R” ;  Generates the following output on the screen (each underscore represent a blank space) _ _ _ _ _ R
  • 23. Object Oriented Concepts & C++ Programming Prof. K Adisesha 23 Program: To fins the sum of two numbers: #include<iostream.h> #include<conio.h> void main( ) { int a, b, add; clrscr( ); cout<<”Enter the two numbers”; cin>>a>>b; add = a + b; cout<<”The sum of two number is”<<sum<<endl; getch(); } Program: Convert the temperature in Fahrenheit into Celsius: #include<iostream.h> #include<conio.h> void main( ) { float fah, cel; clrscr( ); cout<<”Enter the value of Fahrenheit”; cin>>fah; cel = ((5.0/9.0) * fah – 32.0); cout<<fah<<”F = ”<<cel<<” C”<<endl; getch(); } Program: To interchange the values of two variables using third variable. #include<iostream.h> #include<conio.h> void main( ) { int a, b, temp; clrscr( ); cout<<”Enter the two numbers”; cin>>a>>b; cout<<”Before Interchanging : a = “<<a <<” and b = “<<b<<endl; temp = a; a = b; b = temp; cout<<”After Interchanging : a = “ <<a<<endl; cout<<”After Interchanging : b = “ <<b<<endl; getch(); } Program: To interchange the values of two variables without using third variable. #include<iostream.h> #include<conio.h> void main( ) { int a, b; clrscr( ); cout<<”Enter the two numbers”; cin>>a>>b; cout<<”Before Interchanging : a = “<<a <<” and b = “<<b<<endl; a = a + b ; b = a – b ; a = a – b ; cout<<”After Interchanging : a = “ <<a<<endl; cout<<”After Interchanging : b = “ <<b<<endl; getch(); }
  • 24. Object Oriented Concepts & C++ Programming Prof. K Adisesha 24 Program: To find the area and circumference of a circle. #include<iostream.h> #include<conio.h> void main( ) { float rad, area, circum; clrscr( ); cout<<”Enter the radius”; cin>>rad; area = 3.142 * rad * rad; circum = 2 * 3.142 * rad; cout<<”Area of circle = “<<area<<endl; cout<<”Circumference of circle = “<<circum<<endl; getch(); } Program: To find the area of triangle given three sides. #include<iostream.h> #include<conio.h> #include<math.h> void main( ) { float s1, s2, s3, s, area; clrscr( ); cout<<”Enter the length of three sides”; cin>>s1>>s2>>s3; s = (s1 + s2+ s3)/2; area = sqrt( s* (s-s1) * (s-s2) * (ss3)); cout<<”Area of triangle = “<<area<<endl; getch(); } Program: To convert days into years, months and days. #include<iostream.h> #include<conio.h> void main( ) { int totaldays, days, year, month; clrscr( ); cout<<”Enter the total days”; cin>>totaldays; year = totaldays/365; totaldays = totaldays % 365; month = totaldays/30; days = totaldays % 30; cout<<”Years = “<< years<<endl; cout<<”Months = “<<month<<endl; cout<<”Days = “<<days<<endl; getch(); } Program: To convert seconds into hours, minutes and seconds. #include<iostream.h> #include<conio.h> void main( ) { int totalsec, min, hrs, secs; clrscr( ); cout<<”Enter the total seconds”; cin>>totalsec; hrs = totalsec / 3600; totalsec = totalsec % 3600; min = totalsec/60; secs = totalsec % 60; cout<<”Hours = “<<hrs<<endl; cout<<”Minutes = “<<min<<endl; cout<<”Seconds = “<< secs<<endl; getch(); }
  • 25. Object Oriented Concepts & C++ Programming Prof. K Adisesha 25 CONTROL STATEMENTS  Introduction Control statements are statements that alter the sequence of flow of instructions. Any single input statement, assignment and output statement is simple statement. A group of statement that are separated by semicolon and enclosed within curled braces { and } is called a block or compound statement. The order in which statements are executed in a program is called flow of control.  Types of control statements: C++ supports two basic control statements. o Selection statements o Iteration statements  Selection Statements: This statement allows us to select a statement or set of statements for execution based on some condition. It is also known as conditional statement. This structure helps the programmer to take appropriate decision. The different selection statements, viz. o if statement o if – else statement o Nested – if statement o switch statement  if statement: This is the simplest form of if statement. This statement is also called as one-way branching. This statement is used to decide whether a statement or set of statements should be executed or not. The decision is based on a condition which can be evaluated to TRUE or FALSE. The general form of simple – if statement is: if (Test Condition) // This Condition is true Statement 1; Statement 2;  Here, the test condition is tested which results in either a TRUE or FALSE value. If the result of the test condition is TRUE then the Statement 1 is executed. Otherwise, Statement 2 is executed.  Example: if( amount > = 5000 ) discount = amount * (10/100); net-amount = amount – discount; Write a C++ program to find the largest, smallest and second largest of three numbers using simple if statement. #include<iostream.h> #include<conio.h> void main( ) { int a, b, c; int largest, smallest, seclargest; clrscr( ); cout<<”Enter the three numbers”<<endl; cin>>a>>b>>c;
  • 26. Object Oriented Concepts & C++ Programming Prof. K Adisesha 26 largest = a; //Assume first number as largest if(b>largest) largest = b; if(c>largest) largest = c; smallest = a; //Assume first number as smallest if(b<smallest) smallest = b; if(c<smallest) smallest = c; seclargest = (a + b + c) – (largest + smallest); cout<<”Smallest Number is = “<<smallest<<endl; cout<<”Second Largest Number is = “<<seclargest<<endl; cout<<”Largest Number is = “<< largest<<endl; getch( ); } Write a C++ program to input the total amount in a bill, if the amount is greater than 1000, a discount of 8% is given. Otherwise, no discount is given. Output the total amount, discount and the final amount. Use simple if statement. #include<iostream.h> #include<conio.h> void main( ) { float TAmount, discount, FAmount ; clrscr( ); cout<<”Enter the Total Amount”<<endl; cin>>TAmount; discount = 0; //Calculate Discount if(TAmount>1000) Discount = (8/100) * TAmount; FAmount = TAmount – Discount //Calculate Final Amount cout<<”Toatal Amount = “<<TAmount<<endl; cout<<”Discount = “<<discount<<endl; cout<<”Final Amount = “<< FAmount<<endl; getch( ); }  if – else statement: This structure helps to decide whether a set of statements should be executed or another set of statements should be executed. This statement is also called as two-way branching. The general form of if – else statement is: if (Test Condition) Statement 1; else Statement 2; Here, the test condition is tested. If the test condition is TRUE, statement-1 is executed; otherwise, Statement 2 is executed.
  • 27. Object Oriented Concepts & C++ Programming Prof. K Adisesha 27 Write a C++ program to check whether a given year is a leap year not, Using if - else statement. #include<iostream.h> #include<conio.h> void main( ) { int year ; clrscr( ); cout<<”Enter the Year in the form YYYY”<<endl; cin>>year; if(year%4 ==0 && year%100!=0 || year%400 ==0) cout<<year<<” is a leap year”<<endl; else cout<<year<<” is not leap year”<<endl; getch( ); } Write a C++ program to accept a character. Determine whether the character is a lower-case or upper-case letter. #include<iostream.h> #include<conio.h> void main( ) { char ch ; clrscr( ); cout<<”Enter the Character”<<endl; cin>>ch; if(ch>= ‘A’ && ch <=’Z’) cout<<ch<<” is an Upper-Case Character”<<endl; else if(ch>= ‘a’ && ch <=’z’) cout<<ch<<” is an Lower-Case Character”<<endl; else cout<<ch<<” is not an alphabet”<<endl; getch( ); }  Nested if statement : If the statement of an if statement is another if statement then such an if statement is called as Nested-if Statement. Nested-if statement contains an if statement within another if statement. There are two forms of nested if statements.  if – else - if statement : This structure helps the programmer to decide the execution of a statement from multiple statements based on a condition. There will be more than one condition to test. This statement is also called as multiple-way branch. 
  • 28. Object Oriented Concepts & C++ Programming Prof. K Adisesha 28 The general form of if – else – if statement is: if (Test Condition 1) Statement 1; else if (Test Condition 2) Statement 2; else ……….. else if( test Condition N) Statement N; else Default Statement; Here, Condition 1 is tested. If it is TRUE, Statement 1 is executed control transferred out of the structure. Otherwise, Condition 2 is tested. If it is TRUE, Statement 2 is executed control is transferred out of the structure and so on. If none of the condition is satisfied, a statement called default statement is executed. Write a C++ program to input the number of units of electricity consumed in a house and calculate the final amount using nested-if statement. Use the following data for calculation. Units consumed Cost < 30 Rs. 3.50 / Unit >= 30 and < 50 Rs. 4.25 / Unit >= 50 and < 100 Rs. 5.25 / Unit >= 100 Rs. 5.85 / Unit #include<iostream.h> #include<conio.h> void main( ) { int units ; float Billamount; clrscr( ); cout<<”Enter the number of units consumed”<<endl; cin>>units; if(units < 30) Billamount = units * 3.50 ; else if(units < 50) Billamount = 29 * 3.50 + (units – 29) * 4.25 ; else if(units < 100) Billamount = 29 * 3.50 + 20 * 4.25 + (units – 49) * 5.25 ; else Billamount = 29 * 3.50 + 20 * 4.25 + 50 * 5.25 + (units – 99) * 5.85 ; cout<<”Total Units Consumed =”<<units<<endl; cout<<”Toatl Amount = “<<Billamount<<endl; getch( ); }
  • 29. Object Oriented Concepts & C++ Programming Prof. K Adisesha 29 Switch Statement : C++ has built in multiple-branch selection statement i.e. switch. If there are more than two alternatives to be selected, multiple selection construct is used. The general form of Switch statement is: Switch ( Expression ) { Case Label-1: Statement 1; Break; Case Label-2: Statement 1; Break; ………….. Case Label-N: Statement N; Break; Default : Default- Statement; }   Ex: To find the name of the day given the day number switch ( dayno ) { Case 1: cout<< “Sunday”<<endl; break; Case 2: cout<< “Monday” <<endl; break; Case 3: cout<< “Tuesday” <<endl; break; Case 4: cout<< “Wednesday” <<endl; break; Case 5: cout<< “Thursday” <<endl; break; Case 6: cout<< “Friday” <<endl; break; Case 7: cout<< “Saturday” <<endl; break; default: cout<< “Invalid Day Number” <<endl; }  The switch statement is a bit peculiar within the C++ language because it uses labels instead of blocks.  This force up to put break statements after the group of statements that we want to execute for a specific condition.  Otherwise, the remainder statements including those corresponding to other labels also are executed until the end of the switch selective block or a break statement is reached. Write a C++ program to input the marks of four subjects. Calculate the total percentage and output the result as either “First Class” or “Second Class” or “Pass Class” or “Fail” using switch statement.
  • 30. Object Oriented Concepts & C++ Programming Prof. K Adisesha 30 Class Range (%) First Class Between 60% to 100% Second Class Between 50% to 59% Pass Class Between 40% to 49% Fail Less than 40% #include<iostream.h> #include<conio.h> void main( ) { int m1, m2, m3, m4, total, choice; float per; clrscr( ); cout<<”Enter the First subject marks”<<endl; cin>>m1; cout<<”Enter the Second subject marks”<<endl; cin>>m2; cout<<”Enter the Third subject marks”<<endl; cin>>m3; cout<<”Enter the Fourth subject marks”<<endl; cin>>m4; total = m1 + m2 + m3 + m4; per = (total / 400) * 100; cout<<”Percentage = “<<per<<endl; choice = (int) per/10; cout<<”The result of the student is: “<<endl; switch(choice) { case 10: case 9: case 8: case 7: case 6: cout<<”First Class ”<<endl; break; case 5: cout<<”Second Class”<<endl; break; case 4: cout<<”Pass Class”<<endl; break; default: cout<<”Fail”<<end; } getch( ); }  Iterative Constructs or Looping: Iterative statements are the statements that are used to repeatedly execute a sequence of statements until some condition is satisfied or a given number of times. The process of repeated execution of a sequence of statements until some condition is satisfied is called as iteration, repetition, or loop. Iterative statements are also called as repetitive statement or looping statements.
  • 31. Object Oriented Concepts & C++ Programming Prof. K Adisesha 31 There are three types of looping structures in C++. o while loop o do while loop o for loop  while loop: This is a pre-tested loop structure. This structure checks the condition at the beginning of the structure. The set of statements are executed again and again until the condition is true. When the condition becomes false, control is transferred out of the structure. The general form of while structure is while ( Test Condition) { Statement 1 Statement 2 …….. Statement N }End of While Example: n = 10; While ( n > 0) { cout<<n<<”t”; - - n; } cout<<”End of while loop n”; Output: 10 9 8 7 6 5 4 3 2 1 End of while loop Write a C++ program to find sum of all the digits of a number using while statement. #include<iostream.h> #include<conio.h> void main( ) { int num, sum, rem; clrscr( ); cout<<”Enter the Number”<<endl; cin>>num; sum = 0; while(num!=0) { rem = num % 10; sum = sum + rem; num = num/10; } cout<<”Sum of the digits is “<<sum<<endl; getch( ); }
  • 32. Object Oriented Concepts & C++ Programming Prof. K Adisesha 32 Write a C++ program to input principal amount, rate of interest and time period. Calculate compound interest using while statement. (Hint: Amount = P * (1 + R/100)T, Compound Interest = Amount – P) #include<iostream.h> #include<conio.h> void main( ) { float pri, amt, priamt, rate, ci; int time, year; clrscr( ); cout<<”Enter the Principal amount, rate of interest and time”<<endl; cin>>pri>>rate>>time; year = 1; priamt = pri; while(year <= time) { amt = pri * (1 + rate/100); year ++; } ci = amt – priamt; cout<<”Compound Interest is “<<ci<<endl; getch( ); } Write a C++ program to check whether the given number is power of 2. #include<iostream.h> #include<conio.h> void main( ) { int num, m, flag; clrscr( ); cout<<”Enter the Number”<<endl; cin>>num; m = num; flag = 1; while(num>2) if(num % 2 ==1) { flag = 0; break; } else num = num/2; if(flag) cout<<m<<” is power of 2 “<<endl; else cout<<m<<” is not power of 2 “<<endl;
  • 33. Object Oriented Concepts & C++ Programming Prof. K Adisesha 33 getch( ); }  do while statements:  This is a post-tested loop structure.  This structure checks the condition at the end of the structure.  The set of statements are executed again and again until the condition is true.  When the condition becomes false, control is transferred out of the structure.  The general form of while structure is do { Statement 1 Statement 2 …….. Statement N } while ( Test Condition);   Example: i = 2; do { cout<<i<<”t”; i = i + 2; } while ( i < = 25); Write a C++ program to check whether the given number is an Armstrong number using do-while statement. (Hint: 153 = 13 + 53 + 33 ) #include<iostream.h> #include<conio.h> void main( ) { int num, rem, sum, temp; clrscr( ); cout<<”Enter the three digit number”<<endl; cin>>num; temp = num; sum = 0; do { rem = temp % 10; sum = sum + rem * rem * rem; temp = temp / 10; }while(temp!=0);
  • 34. Object Oriented Concepts & C++ Programming Prof. K Adisesha 34 if(sum == num) cout<<num<<” is an Armstrong Number “<<endl; else cout<<num<<” is not an Armstrong Number “<<endl; getch( ); }  for statement:  This structure is the fixed execution structure.  This structure is usually used when we know in advance exactly how many times asset of statements is to be repeatedly executed again and again.  This structure can be used as increment looping or decrement looping structure.  The general form of for structure is as follows: for ( Expression 1; Expression 2; Expression 3) { Statement 1; Statement 2; Statement N; } Where, Expression 1 represents Initialization Expression 2 represents Condition Expression 3 represents Increment/Decrement   Example: sum = 0; for ( i=1; i<=10; i++) sum = sum + i;   This looping structure works as follows: o Initialization is executed. Generally, it is an initial value setting for a counter variable and is executed only one time. o Condition is checked. if it is TRUE the loop continues, otherwise the loop ends and control exists from structure. o Statement is executed as usual, is can either a single statement or a block enclosed in curled braces { and }. o At last, whatever is specified in the increase field is executed and the loop gets back to executed step 2. o The initialization and increase fields are optional. They can remain empty, but in all cases, the semicolon sign between them must be written compulsorily. o Optionally, using the comma operator we can specify more than one expression in any of the fields included in a for loop.
  • 35. Object Oriented Concepts & C++ Programming Prof. K Adisesha 35 Write a C++ program to find the factorial of a number using for statement. (Hint: 5! = 5 * 4 * 3 * 2 * 1 = 120) #include<iostream.h> #include<conio.h> void main( ) { int num, fact, i; clrscr( ); cout<<”Enter the number”<<endl; cin>>num; fact = 1; for( i = 1; i<= num; i++) fact = fact * i; cout<<” The factorial of a ”<<num<<”! is: “<<fact<<endl; getch( ); } Write a C++ program to generate the Fibonacci sequence up to a limit using for statement. (Hint: 6 = 0 1 1 2 3 4) #include<iostream.h> #include<conio.h> void main( ) { int num, first, second, count, third; clrscr( ); cout<<”Enter the number limit for Fibonacci Series”<<endl; cin>>num; first = 0; second = 1; cout<<first<<”t”<<second; third = first + second; for( count = 2; third<=num; count++) { cout<<”t”<<third first = second; second = third; third = first + second; } cout<<”n Total terms = “<<count<<endl; getch( ); }  
  • 36. Object Oriented Concepts & C++ Programming Prof. K Adisesha 36 Jump statements or Transfer of control from within loop  Transfer of control within looping are used to o Terminate the execution of loop. o Exiting a loop. o Half way through to skip the loop.  All these can be done by using break, exit and continue statements.  break statement  The break statement has two uses o You can use it to terminate a case in the switch statement. o You can also use it to force immediate termination of a loop like while, do-while and for, by passing the normal loop conditional test.  When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement.  The general form of break statement is: break;  Example: for (n=0; n<100; n++) { cout<<n; if(n==10) break; } Program: To test whether a given number is prime or not using break statement. #include<iostream.h> #include<conio.h> void main( ) { int n, i, status; clrscr( ); cout<<”Enter the number”; cin>>n; status=1; for(i=2; i<=n/2; i++) { if(n % i ==0) { status=0; cout<<”It is not a prime”<<endl; break; } } if(status) cout<<”It is a prime number”<<endl; getch( ); } 
  • 37. Object Oriented Concepts & C++ Programming Prof. K Adisesha 37 exit( ) function:  This function causes immediate termination of the entire program, forcing a return to the operating system.  In effect, exit( ) function acts as if it were breaking out of the entire program.  The general form of the exit( ) function is: exit( ); or void exit( int return_code);  The return code is used by the operating system and may be used by calling programs.  An exit code of 0 means that the program finished normally and any other value means that some  Error or unexpected results happened. Program: To test whether a given number is prime or not using exit( ) statement. #include<iostream.h> #include,conio.h> void main( ) { int n, i; clrscr( ); cout<<”Enter the number”; cin>>n; for(i=2; i<=n/2; i++) { if(n % i ==0) { cout<<”It is not a prime”<<endl; exit(0); } } cout<<”It is a prime number”<<endl; getch( ); }  continue statement:  The continue statement causes the program to skip the rest of the loop in the current iteration as if end of the statement block has been reached, causing it to jump to start of the following iteration.  The continue statement works somewhat like break statement.  Instead of forcing termination, however continue forces the next iteration of the loop to take place, skipping any code in between.  The general form of the continue statement is: continue;  Example: for (n=10; n<0; n--) { if(n==10) continue; cout<<n; }
  • 38. Object Oriented Concepts & C++ Programming Prof. K Adisesha 38 goto statement:  The goto allows to makes an absolute jump to another point in the program.  This statement execution causes an unconditional jump or transfer of control from one statement to the other statement with in a program ignoring any type of nesting limitations.  The destination is identified by a label, which is then used as an argument for the goto statement.  A label is made of a valid identifier followed by a colon (:).  The general form of goto statement is: statement1; statement2; goto label_name; statement 3; statement4; label_name: statement5; statement6; Program: To print from 10 to 1 using goto statements. #include<iostream.h> #include<conio.h> #include<iomanip.h> void main( ) { int n=10; loop: cout<<”t”<<n; n--; if(n>0) goto loop; cout<<”End of loop”; getch( ); }
  • 39. Object Oriented Concepts & C++ Programming Prof. K Adisesha 39 ARRAYS Introduction  In computer languages, we also need to group together data items of the same type.  The most basic mechanism that accomplishes this in C++ is the array.  Arrays can hold a few data items or tens of thousands.  The data items grouped in an array can be simple types such as int or float, or they can be user- defined types such as structures and objects.  Arrays exist in almost every computer language. Array in C++ are similar to those in other languages and identical to those in C.  Array Fundamentals: An array is collection of elements where all the elements are same data type under the same name.  The elements are numbered as 0, 1, 2….n-1.  These numbers called as indices or subscripts.  These numbers are used to locate the positions of elements within the array.  If a is the name of the array, the elements can be directly accessed as a[0], a[1], a[2],……, a[n-1]. o a[0] is the name of the first element present at position 0. o a[1] is the name of the second element present at position 1 and so on. o In general, a[i] is the element present at position i.  An array can be represented as a 10 20 30 40 50 0 1 2 3 4  In the above array, a is the name of the array, o a[0] contains the element 10 o a[1] contains the element 20 o a[2] contains the element 30 o a[3] contains the element 40 o a[4] contains the element 50.   The method of numbering the ith element with index i-1 is called as zero- based indexing.  That is, the element is always same as the number of “steps“ from the initial element a[0] to that element. For example, the element a[3] is 3 steps from the element a[0].  In C++, the subscripts always start with 0. For example, if b is the name of the array b[0], b[1], b[2]……..are the elements and 0, 1, 2,……..are the subscripts.  Types of Arrays:  There are 3 types of arrays. o One-dimensional array o Two-dimensional array o Multi-dimensional array  One –dimensional array  It is an array in which each element is accessed by using only one subscript.  The only one subscript represents the position of the element in array. 
  • 40. Object Oriented Concepts & C++ Programming Prof. K Adisesha 40 Two-dimensional array  Each element is accessed using 2-subscripts in an array.  The subscripts represent the position of the element in the array.  Multi-dimensional array  A multi-dimensional array is an array of n-dimensions.  In other words, an array of arrays is called a multi-dimensional array.  A one-dimensional array of one-dimensional array is called a two dimensional array; a one- dimensional array to two-dimensional array is called three-dimensional array and so on.  One-Dimensional Array:  Each element is accessed by using only one subscript in an array.  The only one subscript represents the position of the element in array.  Like other variable, the array should also be defined before it is used to store elements.  An array can be defined by specifying the data type of the elements followed by name of the array and the number of elements that can be stored in the array.  The number of elements that can be stored in the array is called the size of the array.  The size of the array must be a constant or an expression that evaluates to a constant, and should be an integer.  The size should be enclosed within square brackets.  Declaration of One-dimensional array:  Syntax: datatype array_name[size];  Example: int regno[10];  This example defines an array marks that can store 50 elements and all the elements are of int data type.  Initialization of one-dimensional arrays:  You can give values to each array element when array is first defined.  Example 1: int a[5] = { 10, 20, 30, 40, 50};  In the above example, o value 10 is stored in a[0] o value 20 is stored in a[1] o value 30 is stored in a[2] o value 40 is stored in a[3] o value 50 is store in a[4]  If there is less number of elements specified than the size of the array, the remaining elements are filled with 0 by the compiler.  If the array does not include an initialization, then the array elements may contain the unexpected values called “garbage values”.  When an array has explicit initialization, its size can be omitted from the declaration.  Example: int a[5] = { 9, -5, 6, 2, 8}; is equivalent to int a[ ] = { 9, -5, 6, 2, 8};    
  • 41. Object Oriented Concepts & C++ Programming Prof. K Adisesha 41 Accessing the elements:  Consider the declaration, int a[5];  We can read 5 elements into the array through the input device by writing the following program fragment. cout<<”Enter the elements:”; for(i=0; i<5; i++) cin>>a[i];  To print the 5 elements of the above array, we write the following program fragment. cout<<”The elements are:”; for(i=0; i<5; i++) cout<<a[i]<<”t”; Sample Program 1: To read the elements into the array and printing the elements: #include<iostream.h> #include<conio.h> void main( ) { int a[50], i, n; clrscr( ); cout<<”Enter the size of the array:”; cin>>n; cout<<”Enter the elements:”; for(i=0; i<n; i++) cin>>a[i]; cout<<”The elements are:”; for(i=0; i<5; i++) cout<<a[i]<<”t”; getch( ); }  Memory representation of one-dimensional arrays:  The elements of one-dimensional arrays are stored in continuous memory locations.  Example: Consider the declaration, char A[5];  The element a[0] is allocated at a particular memory location, the element a[1] is allocated at next memory location and so forth. Since the array is of the type char, each element requires 1-byte. 1000 1001 1002 1003 1004 A[0] A[1] A[2] A[3] A[4] Total Size = sizeof(type) * size_of_array; Example: o The total size of the char array required is 1 * 5 = 5 bytes. o The total size of the int array required is 2 * 3 = 6 bytes.
  • 42. Object Oriented Concepts & C++ Programming Prof. K Adisesha 42 Program to find the sum and average of n number of the array: #include<iostream.h> #include<conio.h> #include<iomanip.h> void main( ) { int a[50], i, n, sum; float avg; clrscr( ); cout<<"How many elements?"<<endl; cin>>n; cout<<"Enter the elements:"; for(i=0; i<n; i++) cin>>a[i]; sum = 0; for(i=0; i<n; i++) sum = sum + a[i]; avg=(float) sum / n; cout<<"Sum = "<<sum<<endl; cout<<"Average = "<<avg<<endl; getch( ); } Practical Program 18: To find the second largest of n number in the array: #include<iostream.h> #include<conio.h> #include<iomanip.h> void main( ) { int a[50], i, n, largest, secondlar; clrscr( ); cout<<"How many elements?"<<endl; cin>>n; cout<<"Enter the elements:"; for(i=0; i<n; i++) cin>>a[i]; if(a[0] > a[1]) { largest = a[0]; secondlar = a[1]; } else { largest=a[1]; secondlar=a[0]; } for(i=2; i<n; i++) if(a[i] > largest) {
  • 43. Object Oriented Concepts & C++ Programming Prof. K Adisesha 43 secondlar = largest; largest = a[i]; } else if(a[i] > secondlar) secondlar = a[i]; cout<<"Largest = "<<largest<<endl; cout<<"Second Largest = "<<secondlar<<endl; getch( ); } Sorting: The process of arrangement of data items in ascending or descending order is called sorting. Program to arrange a list of numbers in ascending order: #include<iostream.h> #include<conio.h> #include<iomanip.h> void main( ) { int a[50], i, temp, j, n; clrscr( ); cout<<"Enter the number of elements:"<<endl; cin>>n; cout<<"Enter the elements:"<<endl; for(i=0; i<n; i++) cin>>a[i]; for(i=1; i<n; i++) { for(j=0; j<n-i; j++) if(a[j] > a[j+1]) { temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } cout<<"The sorted elements are:"<<endl; for(i=0; i<n; i++) cout<<a[i]<<”t”; getch( ); } Searching: The process of finding the position of a data item in the given collection of data items is called searching. We can search the position of an element in the array.
  • 44. Object Oriented Concepts & C++ Programming Prof. K Adisesha 44 To find position of a given number in the array: #include<iostream.h> #include<conio.h> #include<iomanip.h> void main( ) { int a[50], i, pos, ele, n; clrscr( ); cout<<"Enter the number of elements:"<<endl; cin>>n; cout<<"Enter the elements:"<<endl; for(i=0; i<n; i++) cin>>a[i]; cout<<"Enter the search element:"<<endl; cin>>ele; pos=-1; for(i=0; i<n; i++) if(ele == a[i]) { pos = i; break; } if(pos >= 0) cout<<ele<<" is present at position "<<pos<<endl; else cout<<ele<<" is not present"<<endl; getch( ); }  Two -Dimensional arrays:  It is an array in which each element is accessed using 2-subsripts.The subscripts represents position of the elements in the array.  The elements of two-dimensional arrays are represented as rows and columns. To identify any element, we should know its row-number and column-number.  Declaration of Two -Dimensional array:  A Two-dimensional array can be defined by specifying the data type of the elements followed by name of the array followed by the number of rows (i.e. row-size) and number of columns (i.e. column-size)in the array.  The rows-size and column-size of the array must be constant are expressions that evaluates to an integer.  The rows-size and column-size should be separately enclosed within square brackets. Syntax: data_type array_name[row size] [column_size]; 
  • 45. Object Oriented Concepts & C++ Programming Prof. K Adisesha 45 Initialization of Two-Dimensional arrays:  Similar to the one-dimensional array, we can initialize a two-dimensional array either by initializing it in its declaration or by using assignment statement. Example: int a[2][3] = { 1,2,3,4,5,6}; Where a is a two-dimensional array which contains 2 rows and 3 columns and these assignments would be a[0][0] = 1 a[0][1] = 2 a[0][2] = 3 a[1][0] = 4 a[1][1] = 5 a[1][2] = 6  Note: If the values are missing in an initialize, they are automatically set to 0. Accessing the elements:  Consider the declaration int a[2][3];  We can read 6 elements into the array, we need to use nested for loops.  One loop processes the rows and another loop processes the columns.  If outer loop is for rows and inner loop is for columns, then for each row index, all the columns are processed and then the same process is repeated for next row index.  To understand this, let us consider the following program fragment. cout<<”enter the elements:”; for (i=0; i<2; i++) //outer loop to control the rows for (j=0; j<3; j++) //inner loop to the control columns cin>>a[i][j]; To read the elements into the two-dimensional array and printing the elements: #include<iostream.h> #include<conio.h> #include<iomanip.h> void main() { int a[5][5], i, j, m, n; clrscr( ); cout<<"Enter the order:"<<endl; cin>>m>>n; cout<<"Enter the elements:"<<endl; for(i=0; i<m; i++) for(j=0; j<n; j++) cin>>a[i][j]; cout<<”The array elements are:”<<endl; for(i=0; i<m; i++) { for(j=0; j<n; j++) cout<<a[i][j]<<”t”; cout<<endl; } getch( ); }
  • 46. Object Oriented Concepts & C++ Programming Prof. K Adisesha 46 Write a program to sum of all the row and sum of all the column in matrices separately: #include<iostream.h> #include<conio.h> void main( ) { int a[5][5], r, c, i, j, rsum, csum; clrscr( ); cout << "Enter the order of matrix: "; cin >> r>>c; // Storing elements of matrix entered by user. cout << "Enter elements of the matrix: " << endl; for (i = 0; i < r; i++) for (j = 0; j < c; j++) cin >> a[i][j]; for(i = 0; i < r; i++) { rsum = 0; for(j = 0; j < c; j++) rsum = rsum + a[i][j]; cout<<”Sum of row no “<<i+1<<” = “<<rsum<<endl; } for(i = 0; i < c; i++) { csum = 0; for(j = 0; j < r; j++) csum = csum + a[j][i]; cout<<”Sum of column no “<<i+1<<” = “<<rsum<<endl; } getch( ); } Write a program to find the sum of two matrices: #include<iostream.h> #include<conio.h> void main( ) { int a[5][5], b[5][5], sum[5][5], r1, c1, r2, c2, i, j; clrscr( ); cout << "Enter the order of first matrix: "; cin >> r1>>c1; cout << "Enter the order of second matrix: "; cin >> r2>>c2; // Storing elements of first matrix entered by user. cout << "Enter elements of 1st matrix: " << endl; for (i = 0; i < r; i++) for (j = 0; j < c; j++) cin >> a[i][j]; // Storing elements of second matrix entered by user.
  • 47. Object Oriented Concepts & C++ Programming Prof. K Adisesha 47 cout << "Enter elements of 2nd matrix: " << endl; for(i = 0; i < r; i++) for(j = 0; j < c; j++) cin >> b[i][j]; if ( (r1 == r2) && (c1==c2) { for(i = 0; i < r; i++) for(j = 0; j < c; j++) sum[i][j] = a[i][j] + b[i][j]; // Adding Two matrices cout << "Sum of two matrix is: " << endl; for(i = 0; i < r; i++) for(j = 0; j < c; j++) cout << sum[i][j] << "t"; // Displaying the resultant sum matrix. cout << endl; } else cout<<”Matrices are not compatible…”<<endl; getch( ); } Program to Consider an array MARKS[20[5] which stores the marks obtained by 20 students in 5 subjects. Now write a program to:  Find the average marks obtained in each subject.  Find the average marks obtained by every student  Find the number of students who have scored below 50 in their average. #include<iostream.h> #include<conio.h> void main( ) { int marks[20][5], n, s, total, count=0, i, j; float average; clrscr( ); cout << "Enter the number of students: "; cin >> n; cout << "Enter the number of subjects: "; cin >> s; cout << "Enter the marks: " << endl; for (i = 0; i < n; i++) for (j = 0; j < s; j++) cin >> marks[i][j]; cout<<endl<<”Average of Subjects”<<endl; cout<<”Sub1tSub2tSub3tSub4tSub5”<<endl; for(i = 0; i < s; i++) { total = 0; for(j = 0; j < n; j++) total = total + marks[j][i];
  • 48. Object Oriented Concepts & C++ Programming Prof. K Adisesha 48 average = total/n; cout<<average<<”t”; } cout<<endl<<”Average of students:”<<endl; cout<<”StudenttAverage”<<endl; for(i = 0; i < n; i++) { total = 0; for(j = 0; j < s; j++) total = total + marks[i][j]; average = total/s; if(average<50) count++; cout<<” t”<<i+1<<”t”<<average<<endl; } cout<<endl<<”Number of students less than average is ”<<count<<endl; getch( ); }  Multi -Dimensional arrays:  A Multi-Dimensional array is an array of n-dimensions.  An array of arrays is called a multi-dimensional array. Syntax: Data_type Array_name[s1][s2][s3]…..[sn]; where s1 is the size of the ith dimension. Example: int A[2][2][2];
  • 49. Object Oriented Concepts & C++ Programming Prof. K Adisesha 49 FUNCTIONS  Introduction: A function is a named group of statements developed to solve a sub-problem and returns a value to other functions when it is called.  Types of functions There are two types of functions: 1. Library functions 2. User-defined functions  Library functions: A standard library is a collection of pre-defined functions and other programming elements, which are accessed through header files.  Header files are the files containing standard functions that our programs may use.  The header files should be written angled brackets and its functions are included into our programs by #include directive.  User-defined functions: We can create our own functions or sub-programs to solve our problem. Such functions are normally referred to as user-defined functions.  A user-defined function is a complete and independent program, which can be used (or invoked) by the main program, or by the other sub-programs.  The user-defined functions are written to perform definite calculations, after performing their task they send back the result to the calling program or sub-program.  Different header files  iostream.h  This header file contains C++ streams and i/o routines and are listed below.  open, close, get, getline, read, write, put, seekg, seekp, tellg, tellp, eof etc.  stdio.h  This header file contains functions and macros to perform standard i/o operations.  When we include the header file iostream.h, the header file stdio.h is automatically included into our program. The standard i/o functions of the header file stdio.h are listed below.  fopen, fclose, printf, scanf, fprintf, fscanf, fread, fwrite etc.  string.h  This header file declares functions to manipulate strings and memory manipulation routines.  The functions contained in the header file string.h are listed below in the table. Function Meaning strlen(s) It gives the no. of characters including spaces present in a string s. strcat(s1, s2) It concatenates the string s2 onto the end of the string s1. strcpy(s1, s2) It copies character string s2 to string s1. The s1 must have enough storage locations to hold s2.
  • 50. Object Oriented Concepts & C++ Programming Prof. K Adisesha 50 strcmp((s1,s2)==0) strcmp((s1,s2)>0) strcmp((s1,s2)<0) It compares s1 and s2 and find out whether s1 equal s2, greater than s2 or s1 less than s2. strcmpi((s1,s2)==0) strcmpi((s1,s2)>0) strcmpi((s1,s2)<0) It compares s1 and s2 ignoring case and find out whether s1 equal s2, greater than s2 or s1 less than s2. strrev(s) It converts a string into its reverse. strupr(s) It converts a string s into upper case. strlwr(s) It converts a string into lower case. stdlib.h  This header file is used to declare conversion routines, search/sort routines and other miscellaneous things. The functions are listed below. atoi, atol, atof, free, malloc, calloc, realloc etc.  iomanip.h  This header file contains functions and macros for I/O manipulators for creating parameterized manipulations. The functions are listed. endl, setw, setfile, setprecision, hex, oct etc.  math.h  This header file declares prototypes for the mathematical functions and error handlers.  The functions that are used to perform mathematical calculations and conversions are listed below in the table. Function Meaning  sqrt(x) Square Root of X  pow(x, y) x raised to the power y  sin(x) Sine of an angle x (measured in radians)  cos(x) Cosine of an angle x (measured in radians)  tan(x) Tangent of an angle x (measured in radians)  asin(x) Sin-1(x) where x (measured in radians)  acos(x) Cos-1(x) where x (measured in radians)  exp(x) Exponential function of x (ex)  log(x) Logarithm of x  log 10(x) Logarithm of number x to base 10  abs(x) Absolute value of integer number x  fabs(x) Absolute value of real number x Character functions  A character is any single character enclosed within single quotes.  Some functions accept a character as argument.  The argument is processed as an int by using its ASCII code.  To use these functions, the header file ctype.h should be included.  Any character enclosed within single quotes is called as a single character constant or simply, a character constant.
  • 51. Object Oriented Concepts & C++ Programming Prof. K Adisesha 51  These functions will be of the form : int function-name(int character)  Any character enclosed within single quotes is called as a single character constant or simply, a character constant.  Some functions that perform operations on characters are given below. Function Meaning  isalpha(c) It returns True if C is an uppercase letter and false if c is lowercase.  isdigit(c) It returns True if c is a digit (0 to 9) otherwise false  isalnum(c) It returns True if c is digit from 0 through 9 or an alphabetic character  islower(c) It returns True if c is a lowercase letter otherwise False  isupper(c) It returns True if c is a uppercase letter otherwise False  toupper(c) It converts c to uppercase letter  tolower(c) It converts c to lowercase letter. Inputting single character  We can input a character using the function get ( ).  The general form is char ch; or char ch; cin =get(ch); ch=cin.get(ch);  Outputting single character  put ( ) function is used to display single character.  The general form is cout.put (ch);  Example: char ch; ch=cin.get( ); cout.put (ch); Program to determine the type of character. #include<iostream.h> #include<conio.h> #include<ctype.h> void main ( ) { char ch; clrscr( ); cout<<”Type-in a character:”; ch=cin.get(); if((ch>=’A’ &&ch<=’Z’)||(ch>=’a’ &&ch<=’z’)) cout<<”It is an albhabet”<<endl; else if(ch>=’0’ &&ch<=’9’) cout<<”It is a digit”<<endl; else cout<<”It is a special character”<<endl; getch( ); }
  • 52. Object Oriented Concepts & C++ Programming Prof. K Adisesha 52 Program to convert a character from upper-case to lower case and vice versa. #include<iostream.h> #include<conio.h> #include<ctype.h> void main( ) { char ch; clrscr( ); cout<<”Type-in a character:”; ch=cin.get(); if( isupper (ch) ) { ch= tolower (ch); cout<<”The lower-case letter is”<<ch<<endl; } else if( islower (ch) ) { ch= toupper (ch); cout<<”The upper-case letter is”<<ch<<endl; } else cout<<”It is not an alphabet”<<endl; getch(); }  String functions: A string is sequence of characters enclosed within double quotes.  String are manipulated as one-dimensional array of characters and terminated by null (‘0’) character.  C++ provides many functions to manipulate strings.  To use these functions, the header file string.h should be included.  Declaring a string variable  The general form to declare a string is: char string _name[size];  String_ name is the name of the string variable  Size is the number of characters in the string. The size helps the compiler to allocate required number of memory locations to store the string. Example: char st[50]; This declaration reserves 50-bytes to store the characters of the string variable st.  Initializing a string  Like other variables, strings can also be initialized when they are declared. Example: char s[10]=”Karnataka”;  There are only 9 characters in the string. The null character (‘0’) is automatically appended to the end of the string. Example: char st[]={‘E’, ‘m’, ‘p’, ‘r’, ‘e’, ‘s’, ‘s’,’0’};
  • 53. Object Oriented Concepts & C++ Programming Prof. K Adisesha 53 The string is initialized character –wise. In this case, we must specify the null character.  If an entire string is initialized to a string-variable then the null character is automatically appended to end-of-string.  If string is initialized by giving the characters, then we must explicitly specify the string terminator. i.e., null character.  Inputting a string: C++ provides the function getline( ) to read a string.  The general form is: cin.getline (string, size); Example :- cin.getline (st, 25); getline( ) the function terminates reading characters on reading a newline character or when number of characters read is equal to size.  The newline character is read, but replaced by null character.  Outputting a string: C++ provides the function write ( ) to output a string.  The general form is: cout.write (string, size); Example:- cout.write (st, 25);  write ( ) function displays the specified number of characters.  This function does not stop displaying the characters when encountering the null character. As a result, if the size specified is greater than the length of the string, it displays beyond the bounds of the line. Program to read a string and print the string. #include<iostream.h> #include<conio.h> #include<string.h> void main( ) { char s[50]; int l; clrscr( ); cout<<”enter the string:”; cin.getline(s,50); l=strlen(s); cout<<”the given string is”; cout.write(s,l); getch(); } Some string manipulation functions are given below: strlen( ) function: This function returns the length of the string .i.e., the number of characters present in the string, excluding the null character.  The general form is variable=strlen(string);  A string of length ‘0’ is called a null string. Example:- l = strlen (“empress”); returns 7
  • 54. Object Oriented Concepts & C++ Programming Prof. K Adisesha 54 Program to find the length of the string using the library function. #include<iostream.h> #include<conio.h> #include<string.h> void main() { char st[100]; int l; clrscr( ); cout<<”enter the string:”; cin.getline (st,100) l=strlen (st); cout<<”length=”<<l<<endl; getch(); } Program to find the length of the string without using the library function. #include<iostream.h> #include<conio.h> #include<string.h> void main() { char st[100]; int i; clrscr(); cout<<”enter the string:”; cin.getline(st,100); for (i=0; st[i]!=’0’; i++) //for loop terminated cout<<”length=”<<i<<endl; getch(); }  strcat( ) function: This function is used to concatenate 2 strings. The process of combining 2 strings to form a string is called as concatenation.  The general form is strcat(string1, string2); Example:- char str1[ ]=”win”; char str2[ ]=”dows8”; strcat(str1,str2); str1 becomes “windows8”.  strcpy( ) function: A string cannot be copied to another string by using assignment statement. The function  strcpy() is used to copy a string into another string.  The general form is strcpy (string1, string2);  It copies all the characters to string2 to string1. Example:- char str1[ ]=”computer”; char str2[ ]=”science”;
  • 55. Object Oriented Concepts & C++ Programming Prof. K Adisesha 55 strcpy (str1,str2); str1 becomes ”science”  strcmp( ) function: This function is used to alphabetically compare a string with another string. This function is case-sensitive. i.e., it treats the uppercase letters and lowercase letters as different. The general form is strcmp (string1, string2);  It compares all the characters of str2 with str1. The function returns a positive value if  string1>string2, a negative vale if string 1<string2 or it string1 is same as string2. Example:- char str1[ ]=”There”; char str2[ ]=”there”; strcmp (str2,str1); //gives a positive value But, strcmp (str1,str2); //gives a negative value  strcmpi ( ) function: This function is used to alphabetically compare a string with another string. This function is not case-sensitive. i.e., it treats the uppercase letter and lowercase letter as same. The general form is strcmpi (string1,string2);  It compares all the characters of str2 with str1. This function returns a positive value if string1>string2, a negative value if string1<string2 or 0 it string1 is same as string2. Example:- char str1[ ]=”There”; char str2[ ]=”there”; strcmpi (str2,str1); //gives 0 Program to determine whether the string is a palindrome. #include<iostream.h> #include<conio.h> #include<string.h> void main( ) { char s[100], r[100]; //s is the string and r is the reserved string clrscr(); cout<<”Enter the String:”; cin.getline(s,100); strcpy (r, s); // Copy the characters of the string s to r strrev (r); // Reverse the characters of the string r if(strcmpi(s, r) == 0) cout<<”It is palindrome”<<endl; else cout<<”It is not palindrome”<<endl; getch(); }
  • 56. Object Oriented Concepts & C++ Programming Prof. K Adisesha 56 To count the number of vowels and consonants in a string. #include<iostream.h> #include<conio.h> #include<string.h> #include<ctype.h> void main( ) { char s[100]; int l, i, cons=0, vow=0; clrscr( ); cout<<”enter the string:”; cin.getline(s,100); l=strlen(s); for(i=0;i<1;i++) if( isalpha (s[i]) ) switch (toupper (s[i]) ) { case ’A’: case ’E’: case ’I’: case ’O’: case ’U’: vow++; break; default: cons++; } cout<<”Number of Vowels:”<<vow<<endl; cout<<”Number of Consonants:”<<cons<<endl; getch(); }  Other functions C++ provides some useful functions under the library stdlib.h. Some functions are rand( ), srand( ), random( ) and randomized( ). These functions are used to generate pseudo-random numbers. i.e.,numbers that are uniformly distributed within a given interval and for which there is no particular pattern. Computer will generate a number by itself!! Randomly, using this randomized ( ). Function Meaning  randomize() It initialize/seeds the random number generator with a random number.  random(n) It generates a random number between 0 to n-1.  atoi(s) It converts string s into a numerical representation.  itoa(n) It converts a number to a string.
  • 57. Object Oriented Concepts & C++ Programming Prof. K Adisesha 57 USER DEFINED FUNCTIONS  Definition: User-defined function is a function defined by the user to solve his/her problem.  Such a function can be called (or invoked) from anywhere and any number of times in the program.  The purpose of using a function is to make the program design process easy, understandable and thereby avoiding ambiguity.  Advantages of user-defined functions:  If there is set of statements to be repeated several times in the program, these statements can be replaced as a function and called whenever and whenever required.  If a task in needed in more than one program or to a group of programmers, a function can be developed and made available to other programs or other programmers.  Programs can be modularized into functions. Each function can be developed independently, debugged and tested.  If a problem is divided into sub-problems, a team of programmers can be formed to solve each sub-problem, rather solving by a single person.  If functions are developed in a program, the number of line decreases.  Function definition or structure of user-defined function:  Return type-specifiers: is the data type of the value return by the function to another function when it is called. It can be char, int, float or void. Data type void is used when the function return no value to calling function.  Function-name: is the name of the function. It is an identifier to identify the particular function in a program.  Argument-list with declaration: is the list of arguments or parameters or variables with their declaration. Each argument should be declared separately. Each declaration should be separated by comma. The list should be enclosed within parenthesis.  The complete line is called the function header. Note that there is no semicolon at the end.
  • 58. Object Oriented Concepts & C++ Programming Prof. K Adisesha 58  Local-variable declaration: is the declaration of the variables that are used within the function. Since these variables are local to the function, these variables are called as local variables.  Executable statements: are the statements that perform the necessary operations to solve the problem. If the function is returning a value, a return statement should be included. Otherwise, return statement is not necessary.  Local declaration and executable statements are together called as body of the function. The body of the function should be enclosed within the curled braces. Program to find the greatest of three numbers. #include<iostream.h> #include<conio.h> void main( ) { int biggest (int, int, int); //Function prototype int a, b, c, big; clrscr( ); cout<<”Enter the three numbers”; cin>>a>>b>>c; big = biggest(a, b, c); // Function call-statement cout<<”Biggest=”<<big<<endl; getch( ); } int biggest (int x, int y, int z) // Called Function { int big; big = x>y?(x>z?x:z):(y>z?y:z); return (big); }  Calling a function: Function call is the statement that is used to call or make another function execute.  The definition of the program can come either before the main( ) function or after the main( ) function.  Calling function is a function that transfer control from it to another function by specifying the name of that function and passing arguments.  Called function is a function that receives the call and arguments from another calling function.  When a function call is made, the control jumps calling function to the called function. main ( ) function:  The main ( ) function returns a value of type int to the operating system. If the program runs successfully, 0 is returned. Otherwise, a non-zero value is returned to the operating system, indicating that the program contains errors.  If the main ( ) function is not returning a value, the data type void can be used as return type specifiers.  The general form of main ( ) function is: int main ( ) { Executable-Statements; return 0; }  void main( ) { Executable-Statements; } 
  • 59. Object Oriented Concepts & C++ Programming Prof. K Adisesha 59 Returning a value:  When a function is called, the statements in the called function are executed.  After executing the statements, the function returns value to the calling function. The return statement is used to return a value.  A function can return only one value or none to the calling function, for every function call.  The general form of return statements is: return (expression); OR return 0;   Function Prototype:  A function prototype is a declaration of the function that tells the program about the type of the value return by the function and the number and type of arguments.  The general form of function prototype is: General Form Example return-type-specifier function-name (type arg1, type arg2….) OR return-type-specifier function-name ( type, type ….) int biggest(int x, int y, int z); OR int biggest( int, int , int);  Types of Arguments: A variable in a function header is called an argument. The arguments are used to pass information from the calling function to the called function. Actual Arguments: The function call statement contains name of the function and the list of arguments to be passed. These arguments or parameters are called as actual arguments.  The arguments can be constants, variables, or expressions.  Example: big = biggest (a, b, c); Formal Arguments: The function header contains return-type-specifier, function name and list of arguments with their declaration.  These arguments are called as formal arguments or dummy arguments. Formal arguments get their values from the actual arguments.  Example: int biggest (int x, int y, int z) Local Variables: The variables declared inside function or block is said belong to that block. These variables are called as Local variables.  Values of local variables are accessible only in that block.  The function’s formal arguments are also considered as local variables.  Example: function-name (int a, int b) { int x, y; //x and y are local variables; …………; }  Global Variables: The variables declared outside the function are called as global variables. These variables are referred by the same data type and same name throughout the program in both calling function and called function.
  • 60. Object Oriented Concepts & C++ Programming Prof. K Adisesha 60  Whenever if some variables are to treated as same value in both main( ) and in other functions, it is advisable to use global variables. Example: int a, b; // a and b are global variables void main( ) { int p, q; // p and q are local variables ……. } Program to find the LCM of two numbers: #include<iostream.h> #include<conio.h> int a,b; // a and b are global variables int gcd(int x, int y) { int r; // r is local variable while(b!=0) { r = a%b; a=b; b=r; } return a; } void main( ) { int gcd(int x, int y) //Function Prototype int product, lcm, g; clrscr( ); cout<<”enter two numbers:”; cin>>a>>b; produt= a *b; g = gcd(a, b); lcm = product/g; cout<<”GCD=”<<g<<endl; cout<<”LCM=”<<lcm<<endl; getch(); }  Scope of Variables:  Scope of variables refers to the part of the program where the value of the variable can be used.  The scope of the variables begins from where the variable declared.  If the declaration is inside a function, the scope extends to the end of the innermost block that contains the declaration.  Example: To illustrate scope of variables #include<iostream.h> #include<conio.h> void f( ); void g( );
  • 61. Object Oriented Concepts & C++ Programming Prof. K Adisesha 61 int x=10; void main( ) { int x = 20; { int x = 30; cout<<”In block inside main( ): x=”<<x<<endl; } cout<<”In main(): x=”<<x<<endl; cout<<”In main(): ::x=””<<::x<<endl; f( ); g( ); } void f() { cout<<”In f(): x=”<<x<<endl; } void g() { int x=40; cout<<”In g(): x=”<<x<< endl; }  Types of Function:  There are different types of functions: a. Function with no arguments and no return values. b. Function with arguments and with no return values. c. Function with no arguments and with return values. d. Function with arguments and with return values. e. Recursive function.  Function with no arguments and no return values: In this method, the simply performs independent task. The function does not receive or send any arguments. General Form Example void function-name( ) { Statements; } void natural( ) { for(int i=1; i<=10; i++) cout<<”t”<<I; }     
  • 62. Object Oriented Concepts & C++ Programming Prof. K Adisesha 62 Function with arguments and with no return values: In this method, the function receives some arguments and does not return any value. General Form Example void function-name(argument list) { Statements; }  void sum(int x, int y, int z ) { int sum; sum= x + y+ z; cout<<”Sum =”<<sum; }   Function with no arguments and with return values: In this method, the function receives no arguments but return a value. General Form Example return-type function- name() { Statements; return(value) }  int greatest( ) { if(a>b); return(a); else return(b); }  Function with arguments and with return values:  In this method, the function receives some arguments and returns a value. General Form Example return-type function-name(argument-list) { Statements; return(value) }  float interest(float p, float t, float r) { si = (p * t * r)/100; return(si); }   Recursive function: Recursive function is a function that calls itself. The process of calling function by itself is called as recursion. General Form return-type function-name(argument-list) { Statements; return(function-name(argument-list)) } 
  • 63. Object Oriented Concepts & C++ Programming Prof. K Adisesha 63 Passing default arguments to functions:  In C++, to call a function we need not pass all the values for the arguments to a function from the calling function.  It allows us to assign default values to the formal arguments.  Default values can be assigned to the argument which does not have a matching argument int the function call.  Default values are assigned in the function prototype.  The default values are assigned to the arguments as we initialize variables.  Example: float interest(float amt, int time, float rate =0.15) si = interest(5000,5) //third argument is missing si=interest(5000, 5, 0.2) //No missing arguments  Uses of default values:  Default arguments are useful in situations where some arguments always have the same value.  Default arguments provide flexibility to the programmer.  Default arguments are used to add new arguments to the existing functions.  Default arguments are used to combine similar functions into one.  Passing Constant arguments:  In C++, we can declare some arguments as constants. The compiler cannot modify the arguments marked as constants.  Example: int strlen(const char *p); int total(const int x, const int y);  Pass by value or Call by Value:  A function can be called by passing arguments from the calling function into the called function.  Thus data is transferred through argument list.  The calling function sends the data to the called function through actual parameters.  The called function receives the data into its corresponding formal parameters.  In pass by value, a copy of data sent by calling function stored in temporary locations,  The called function uses these values as the initial values of the formal parameters.  The formal parameters are processed or changed to generate the required result.  However these changes are affected to the original values stored in the actual parameters.  Example: void main( ) { void swap(int, int); //Function prototype {
  • 64. Object Oriented Concepts & C++ Programming Prof. K Adisesha 64 int a, b; clrscr( ); cout<<”Enter two numbers”; cin>>a>>b; cout<<”Before calling the function: a=”<<a<<””and b=”<<b<<endl; swap(a, b); //Actual Arguments cout<<”After calling the function: a=”<<a<<””and b=”<<b<<endl; getch(); } void swap(int x, int y) //Formal Arguments { int temp; temp = x; x = y; y= temp; }  Pass by reference or call by reference:  Sometimes we need to change the values of the actual arguments in the calling function. This is not possible in the passing by value method.  C++ allows us to pass arguments to the function by using reference variables.  When we pass arguments by reference, the formal arguments int the called function become the aliases to the actual arguments of the calling function i.e. the called function is actually uses the original data with a different name.  Example: void main( ) { void swap(int &, int &); //Function prototype { int a, b; clrscr( ); cout<<”Enter two numbers”; cin>>a>>b; cout<<”Before calling the function: a=”<<a<<””and b=”<<b<<endl; swap(a, b); //Actual Arguments cout<<”After calling the function: a=”<<a<<””and b=”<<b<<endl; getch(); } void swap(int &x, int &y) //Formal Arguments { int temp; temp = x; x = y; y= temp; }
  • 65. Object Oriented Concepts & C++ Programming Prof. K Adisesha 65 STRUCTURES Introduction: A structure is a collection of simple variables. The variables in a structure can be of same or different types: some can be int, some can be float and so on.  The data items in a structure are called the members of the structure.  For C++ programmers, structures are one of the two important building blocks in the understanding of objects and classes.  The syntax of a structure is almost identical to that of a class.   Defining a structure: A structure is a collection of various data elements under one name.  The process of defining a structure includes giving the structure a name called the tag and telling the compiler the name and the data type of each piece of data you want to be included in a structure.  Syntax: Struct structure-name { datatype member-name-1; datatype member-name-2; …………………….. datatype member-name-n; }; o The keyword struct introduces the structure definition. o Next comes the structure name or tag, which is part. o The declarations of the structures members are enclosed in braces. o The list of all structure members is called template. o A semicolon follows the closing braces, terminating the entire structure. Example: A structure definition to hold employee information. struct employee { int idno; // 2 bytes char name[15]; // 15 bytes char designation[10]; // 10 bytes float salary; // 4 bytes };   This structure is named employee. It contains four members: an integer named idno, a character array to hold 15 characters for a name, another character array to hold 10 characters for designation and float named salary.  The structure requires an area in memory, which is 31 bytes long.  Declaring a structure or defining a structure variable:  A structure can be declared (or a structure variable can be defined) as we defined a basic built-in data type.  The general form is structure-name variable; Example 1: student old_student, new_student;
  • 66. Object Oriented Concepts & C++ Programming Prof. K Adisesha 66 old_student and new_student are the two structure variables declared as we declare built-in data types. Example 2: employee emp1, emp2; emp1and emp2 are the two structure variables declared as belong to the user-defined data type employee.  We can combine the definition of the structure and definition of structure variables. Example: struct employee { int idno char name[15]; char designation[10]; float salary; } emp1, emp2; Accessing the elements of a structure  After the structure variables are defined, we should know how the member of a structure variable is accessed.  A member of a structure is always part of a structure and it is not possible to refer the member directly.  The member of a structure can be accessed using dot operator.  The syntax of dot operator is as follows: structure_variable-name.member_name  The structure member is written in three parts: o The name of the structure variable (part1); o The dot operator, which consists of a period (.) o The member name (part3).  Note: The real name of the dot operator is member access operator.  Example 1: To access the name of the member emp1 of the tag employee, we write  emp1.name;  Example 2: To access the salary of the member emp2 of the tag employee, we write  emp2.salary Sample Program: To input and display the information of a student #include<iostream.h> #include<iomanip.h> #include<string.h> void main ( ) { struct student { int regno; char name[15]; char comb[4]; float perc; } st; cout<<”Enter the register number of the student:”; cin>>st.regno; cout<<”Enter the name of the student:”; cin>>st.name;
  • 67. Object Oriented Concepts & C++ Programming Prof. K Adisesha 67 cout<<”Enter the combination of the student:”; cin>>st.comb; cout<<”Enter the percentage of the student:”; cin>>st.perc; cout<<”Register No:”<<st.regno<<endl; cout<<”Name: ”<<st.name<<endl; cout<<”Combination:”<<st.comb<<endl; cout<<”Percentage:”<<st.perc<<endl; getch(); } Sample run: Enter the register number of the student: 1234 Enter the name of the student: Adisesha Enter the combination of the student: PCMC Enter the percentage of the student: 90.05 Register no: 1234 Name: Adisesha Combination: PCMC Percentage:90.05 Initializing a structure:  Like any other data type, it is also possible to initialize the structure members of a structure variable.  Structures members are initialized when they are declared.  Example: A program may contain the following initialization of the structure. Employee emp1= { 1234, “Lakshmi”, “Manager”, 10500.00 };  This initialization initializes idno field to 1234, the name field to ”Lakshmi”, the designation field to “Manager” and the salary field to 10500.00.  A structure variable can be assigned to another structure variable. Example: std2 = std1;  Here, std1 and std2 are the structure variables of the structure std.  The value of each member of std1 is assigned to the corresponding member of std2.  Since a large structure can have dozens of members, such an assignment statement can require the computer to do a considerable amount of work. Note that one structure variable can be assigned to another only when they are of the same structure type. If you try to assign a variable of one structure type to variable of another type, the compiler will complain.  Nested structures: A structure can be defined as a member of another structure. Such structure where one structure is embedded within another structure is called as a nested structure.
  • 68. Object Oriented Concepts & C++ Programming Prof. K Adisesha 68  During the declaration of nested structure, the definition of the embedded structure must appear before the definition of outer structure.  Example: consider the definition of the following structure. struct distance { int feet; float inches; }; struct room { distance length; distance breadth; };  The structure room contains another structure distance as one of its members.  Whenever nested structures are used, the definition of the internal structure should precede the definition of the outer structure.  In the above example, the definition of the structure distance precedes the definition of the structure room.  Example: consider the definition of structure student. struct date { int dayno; char month[10]; int year; }; struct student { int regno; date doa, dob; int marks; }std; To access the field regno of the structure std, we write std.regno. To access the day number of the date of admission of the structure std, we write std.doa.dayno. To access the year of date of birth of the student std, we write std.dob.year.  Array of structures: An array of structure is an array in which each element of the array is a structure. Thus it is a collection of structures put together as an array.  A single variable that represents a structure creates memory space to store one set of information.  If we want to create memory space for more instances then we may have to increases the number of variables or use the facility called arrays.  For example, let us consider that there are 10 students studying in a college. We have defined the structure so that it could maintain information about students of the college. If we have to store data of 10 students, we need to use arrays rather than a single variable.  When create an array of the structure, we are creating an array of the entire template. This can be done as follows. struct student { int regno; char name [15]; char comb; float fees; } s [10];