unit 1 introduction - bamu engine · enumeration i) an enumerated data type is another user defined...
TRANSCRIPT
UNIT 1
Introduction
1
PROCEDURE-ORIENTED PROGRAMMING
� Procedure-oriented programming basically
consists of writing a list of instructions for the
computer to follow and organizing these
instructions into groups known as functions.
� Uses flowchart to organize these actions and
represent the flow of control from one action torepresent the flow of control from one action to
another.
� More importance to functions very little
attention to data that are being used by the
functions.
2
PROCEDURE-ORIENTED PROGRAMMING
� In multi-function program many important
data items are placed as global so that they may
be accessed by all the functions.
� Each function may have its own local data.
� In large program it is very difficult to identify� In large program it is very difficult to identify
what data is used by which function.
� To revise an external data structure needs to
revise all function that access it.
3
OBJECT-ORIENTED PROGRAMMING
� OOP is an approach to program
organization and development
� It attempts to eliminate some of the pitfalls
of conventional programming methods
� Incorporates the best of structured� Incorporates the best of structured
programming features with several
powerful new concepts.
4
OBJECT ORIENTED PROGRAMMING
� Developments in software technology
continue to be dynamic.
� This made the software industry and
software engineers to continuously look for
new approaches to software design andnew approaches to software design and
development.
� Rapid advances appear to have created a
situation of crisis within the industry.
5
OBJECT ORIENTED PROGRAMMING
� Major issues need to resolved:
� How to represents real-life entities
� How to ensure reusability and extensibility of
modules
� How to develop modules that are tolerant to� How to develop modules that are tolerant to
any changes in future
� How to improve software productivity and
decrease software cost
� How to improve the quality of software
� How to manage time schedules
6
PROCEDURE ORIENTED AND OBJECT
ORIENTED PROGRAMMING APPROACH
� procedure and object oriented are both strategies
of information processing and knowledge ordering,
used in a variety of fields and management.
� Actually, they can be seen as a style of thinking and
teaching.teaching.
� These are the ways to implement the core logic of a
system.
7
PROCEDURAL PROGRAMMING
� In procedural programming our code is organized into
small "procedures" that use and change the data.
� These functions typically take some input, do
something, then produce some output.
� The key idea here is that our functions have no� The key idea here is that our functions have no
intrinsic relationship with the data they operate on.
� Sometimes functions need to access data that is not
provided as a parameter, i.e. data that is outside the
function.
� Data accessed in this way is considered "global" or
"shared" data.8
OBJECT ORIENTED PROGRAMMING
� In object oriented programming, the data and
related functions are bundled together into an
“classes".
� The data inside a class can only be manipulated
by calling that class’s functions.by calling that class’s functions.
� The procedural systems make use of shared and
global data, while object oriented systems lock
their data privately.
� All variables are inside class body
� Only with an object of that class the variables
can be accessed or changed.9
COMPARISON
Procedure oriented approach
� Emphasis is on doing things (algorithms)
� Large Programs are divided into smaller programs known as functions.
Object oriented approach
� Emphasis is on data rather than on procedure
� Programs are divided into objects
� Data structures are characterized with independent variables
� Most of the functions share global data.
� Data structures are designed in such a way that it characterizes the object
� Functions that operate on data are ties together in a data structure called class
10
Procedure oriented approach
� Data move openly around the system and can be accessed by any function
� Functions transform data from one form to another.
Object oriented approach
� Data is hidden and cannot be accessed by external functions.
� Objects may communicate to each other with the help of functions.
11
� Difficult to add new functions after specific phases.
� Employs top down approach in program design.
� New data and functions can be easily added whenever necessary
� Follows bottom-up approach.
Object oriented approach
� Replaces many manual
processes .
� Implementation cost is less.
� Reusability is maximum.
Difficult to modify primitive
Procedure oriented
approach
� Manual work is more.
� Implementation cost is
more.
Reusability is less. � Difficult to modify primitive
requirements at the end.
� Modular dependency is more.
� Less consistent.
12
� Reusability is less.
� Not that much difficult.
� Modular dependency is less.
� More consistent.
SUMMARY
� It is meant to address the difficulties with
procedural programming.
� The main modules in a program are classes,
rather than procedures.
� This approach create classes and objects that� This approach create classes and objects that
model real world objects.
13
Features of C++
� Emphasis on data rather than procedure
� Programs are divided into what are known as objects
� Data is hidden and cannot be accessed by external
functions
� Object may communicate with each other through� Object may communicate with each other through
functions
� Follows bottom up approach in program design
� New data and functions can be easily added
14
C++ PROGRAMS
� A C++ program is a collection of one or more
subprograms, called functions
� A subprogram or a function is a collection of
statements that, when activated (executed),
accomplishes somethingaccomplishes something
� Every C++ program has a function called main
� The smallest individual unit of a program written in
any language is called a token
15
Sample C++ Programs
Program1
#include<iostream.h>
int main()
{
int i;
// input a number //
// square of the
number is //
cout<< i<<“square is
<< i*i<<“\n”;
return 0;// input a number //
cout<<“enter a number:”;
cin >> i;
return 0;
}
16
program 2
#include<iostream.h>
void main()
{
int s1,s2,s3,s4,s5,sum;
float avg;
cout<<“enter marks of student:” ;
sum=s1+s2+s3+s4+s5;
avg=sum/5;
cout<<“sum of marks” <<sum;student:” ;
cin>>s1;
cin>>s2;
cin>>s3;
cin>>s4;
cin>>s5;
<<sum;
cout<<“avg”<< avg;
}
17
ASSIGNMENT PROGRAMS
� Write a C++ program to display personal
information i.e. name, age ,cellno.
� Write a C++ program to calculate simple interest
using formula si=p*n*r/100.using formula si=p*n*r/100.
18
C++ CONCEPTS
� C++ has following tokens:
� Keywords
� Symbols
� Identifier
Constants� Constants
� Strings
� Operators
19
KEYWORDS
� Class
� Friend
� Inline
� Public
Private � Private
� Protected
� New
� Virtual
� Delete
� Template etc.20
SYMBOLS
� Special symbols
+
-?
,-
*
/
.
;
,
<=
!=
==
>=
21
SYMBOLS (CONTINUED)
� Word symbols
� Reserved words, or keywords
� Include:
� int
float� float
� double
� char
� void
� return
22
IDENTIFIERS
� Consist of letters, digits, and the underscore character (_)
� Must begin with a letter or underscore
� C++ is case sensitive
� Some predefined identifiers are cout and cin
� Unlike reserved words, predefined identifiers may be redefined, but it is not a good idea
23
DATA TYPES
� Data Type: set of values together with a set of
operations is called a data type
� C++ data can be classified into three categories:
� Simple data type� Simple data type
� Structured data type
� Pointers
24
SIMPLE DATA TYPES
� Three categories of simple data
� Integral: integers (numbers without a decimal)
� Floating-point: decimal numbers
� Enumeration type: user-defined data type also
structures, unions classes and enumerated data
types with keyword enum.
25
26
INT DATA TYPE
� Examples:
-6728
0
78
� Positive integers do not have to have a + sign in � Positive integers do not have to have a + sign in
front of them
� No commas are used within an integer
� Commas are used for separating items in a list
27
BOOL DATA TYPE
� bool type
� Has two values, true and false
� Manipulate logical (Boolean) expressions
� true and false are called logical values
� bool, true, and false are reserved words
28
CHAR DATA TYPE
� The smallest integral data type
� Used for characters: letters, digits, and special symbols
� Each character is enclosed in single quotes
� Some of the values belonging to char data type are: � Some of the values belonging to char data type are:
'A', 'a', '0', '*', '+', '$', '&'
� A blank space is a character and is written ' ', with a
space left between the single quotes
29
FLOATING-POINT DATA TYPES
� C++ uses scientific notation to represent real
numbers (floating-point notation)
30
FLOATING-POINT DATA TYPES
(CONTINUED)
� float: represents any real number
� Range: 3.4E-38 to 3.4E+38
� Memory allocated for the float type is 4 bytes
� double: represents any real number
� Range: -1.7E+308 to 1.7E+308� Range: -1.7E+308 to 1.7E+308
� Memory allocated for double type is 8 bytes
� On most newer compilers, data types double and long double are same
31
FLOATING-POINT DATA TYPES
(CONTINUED)
� Maximum number of significant digits (decimal
places) for float values is 6 or 7
� Float values are called single precision
� Maximum number of significant digits for double
is 15is 15
� Double values are called double precision
� Precision: maximum number of significant digits
32
ARITHMETIC OPERATORS
� C++ Operators
+ addition
- subtraction
* multiplication
/ division/ division
% remainder (mod operator)
� +, -, *, and / can be used with integral and floating-point data types
� Unary operator - has only one operand
� Binary Operator - has two operands
33
ORDER OF PRECEDENCE
� All operations inside of () are evaluated first
� *, /, and % are at the same level of precedence and
are evaluated next
and have the same level of precedence and are � + and – have the same level of precedence and are
evaluated last
� When operators are on the same level
� Performed from left to right
34
EXPRESSIONS
� If all operands are integers
� Expression is called an integral expression
� If all operands are floating-point
� Expression is called a floating-point expression
� An integral expression yields integral result
� A floating-point expression yields a floating-point
result
35
MIXED EXPRESSIONS
� Mixed expression:
� Has operands of different data types
� Contains integers and floating-point
� Examples of mixed expressions:� Examples of mixed expressions:
2 + 3.5
6 / 4 + 3.9
5.4 * 2 – 13.6 + 18 / 2
36
EVALUATING MIXED EXPRESSIONS
� If operator has same types of operands
� Evaluated according to the type of the operands
� If operator has both types of operands
� Integer is changed to floating-point � Integer is changed to floating-point
� Operator is evaluated
� Result is floating-point
37
EVALUATING MIXED EXPRESSIONS
(CONTINUED)
� Entire expression is evaluated according to
precedence rules
� Multiplication, division, and modulus are evaluated
before addition and subtraction
� Operators having same level of precedence are
evaluated from left to right
� Grouping is allowed for clarity
38
TYPE CASTING (CONVERSION)
� Value must be compatible with the variable.
� If not, we have to make a type conversion.
� Converting an expression of a given type into another type is known as type-casting.
� Types of Type Casting
� There are two ways of achieving the Type Casting.
� There are two ways of achieving the Type Casting.
Implicit Conversion : Numeric Numeric
� Explicit Conversion : Numeric Character
� Character Numeric
� A cast is a special operator that forces one data
type to be converted into another.
� As an operator, a cast is unary and has the same
precedence as any other unary operator.
� The most general cast supported by most of the� The most general cast supported by most of the
C++ compilers is as follows:
� <data type name> (expression)
40
PROPERTIES OF IMPLICIT TYPE CASTING
� Occurs between compatible types.
� Transfers data from a smaller type to a bigger
type.
� No data loss.
� No extra operation.
� Automatic type conversion.
COMPATIBLE TYPES
EXAMPLE
Implicit Conversion
No data loss
44
� #include <iostream.h>
� main()
� {
� double a = 21.09399;
� float b = 10.20;
� int c ;
� c = (int) a;
cout << "Line 1 - Value of (int)a is :" << c << endl ; � cout << "Line 1 - Value of (int)a is :" << c << endl ;
� c = (int) b;
� cout << "Line 2 - Value of (int)b is :" << c << endl ;
� return 0;
� }
� Line 1 - Value of (int)a is :21
� Line 2 - Value of (int)b is :10 45
PROPERTIES OF EXPLICIT TYPE CASTING
� Occurs between incompatible types.
� May lose data.
Extra coding needed.� Extra coding needed.
� Use with caution.
EXAMPLE
TYPES OF EXPLICIT TYPE CASTING
� const_cast<type> (expr): The const_cast operator
is used to explicitly override constant values.
� dynamic_cast<type>(expr): The dynamic_cast
performs a runtime cast that verifies the validity of
the castthe cast
� reinterpret_cast<type>(expr):The
reinterpret_cast operator changes a pointer to any
other type of pointer.
� static_cast<type>(expr): The static_cast operator
performs a nonpolymorphic cast. For example, it
can be used to cast a base class pointer into a
derived class pointer. 48
STRING DATA TYPE
� Programmer-defined type supplied in standard
library
� Sequence of zero or more characters
� Enclosed in double quotation marks
Null: a string with no characters� Null: a string with no characters
� Each character has relative position in string
� Position of first character is 0, the position of the
second is 1, and so on
� Length: number of characters in string
49
ALLOCATING MEMORY
� Named Constant: memory location whose content
can’t change during execution
� The syntax to declare a named constant is:
� In C++, const is a reserved word
50
51
DECLARING & INITIALIZING VARIABLES
� Variables can be initialized when declared:
int first=13, second=10;
char ch=' ';
double x=12.6, y=123.456;
� first and second are int variables with the � first and second are int variables with the
values 13 and 10, respectively
� ch is a char variable whose value is empty
� x and y are double variables with 12.6 and
123.456, respectively
52
INPUT
� Data must be loaded into main memory before it can be
manipulated
� Storing data in memory is a two-step process:
Instruct the computer to allocate memory1. Instruct the computer to allocate memory
2. Include statements to put data into allocated
memory
53
INPUT (READ) STATEMENT
� cin is used with >> to gather input
cin >> variable >> variable. . .;
� The extraction operator is >>
� For example, if miles is a double variable
cin >> miles;
� Causes computer to get a value of type double
� Places it in the memory cell miles
54
INPUT STATEMENT (CONTINUED)
� Using more than one variable in cin allows more than
one value to be read at a time
� For example, if feet and inches are variables of type
int a statement such as:
cin >> feet >> inches;
� Inputs two integers from the keyboard
� Places them in locations feet and inches respectively
55
OUTPUT
� The syntax of cout and << is:
cout<< expression or manipulator
<< expression or manipulator
<< ...;
�Called an output (cout) statement
� The << operator is called the insertionoperator or the stream insertion operator
�Expression evaluated and its value is printedat the current cursor position on the screen
56
OUTPUT (CONTINUED)
� Manipulator: alters output
� endl: the simplest manipulator
� Causes cursor to move to beginning of the next � Causes cursor to move to beginning of the next
line
57
ENUMERATION
i) An enumerated data type is another user defined type which provides a way of attaching names to numbers to increase simplicity of the code.
ii) It uses enum keyword which automatically enumerates a list of words by assigning them values 0, 1, 2,..etc.
Syntax:-
enum shape
{
circle,
square,
triangle
}
Now shape become a new type name & we can declare new variables of this type.
EX . shape oval;
58
CONTD…
iv) In C++, enumerated data type has its own separate type.
Therefore c++ does not permit an int value to be automatically
converted to an enum value.
Ex. shape shapes1 = triangle, // is allowed
shape shape1 = 2; // Error in c++
shape shape1 = (shape)2; //okshape shape1 = (shape)2; //ok
v) By default, enumerators are assigned integer values starting with 0,
but we can over-ride the default value by assigning some other value.
EX:- enum color {red, blue, pink = 3};
� it will assign red to o, blue to 1, & pink to 3 or
� enum color {red = 5, blue, green};
� it will assign red to 5, blue to 6 & green to 7.59
PROGRAM TO IMPLEMENT ENUMERATED DATA TYPES
#include <iostream.h>
#include <stdlib.h>
enum RomanNum {I=1, V=5, X=10, L=50, C=100, M=1000};
void main()
{
cout << "Welcome to the world of Roman numerals!" cout << "Welcome to the world of Roman numerals!"
<< endl;
int num = (int)(M + C + L + X + V + I);
cout << "MCLXVI=" << num << endl;
num = (int)((L-X) + (V-I));
cout << "XLIV=" << num << endl;
getch();
} 60
OPERATORS IN C++
INCREMENT & DECREMENT OPERATORS
� Increment operator: increment variable by 1
� Decrement operator: decrement variable by 1
� Pre-increment:++variable
Post-increment: variable++ � Post-increment: variable++
� Pre-decrement: --variable
� Post-decrement: variable--
61
CONTD…
Input / Output operator
1. Input Operator cin :- The identifier cin is a predefined object in c++
that corresponds to the standard input stream.
This stream represents keyboard.
Syntax:- cin>>variable;
The operator >> is known as extraction or get from operator &
assigns it to the variable on its right.assigns it to the variable on its right.
2. Output operator cout :-The identifier cout is predefined object that
represents the standard output stream in c++.
Here standard output stream represents the screen.
Syntax:- cout<<string;
The operator << is called the insertion or put to operator.
It inserts the contents of the variable on its right to the object on its left.62
CONTD…
C++ had rich set of operators. Some of the new operators in C++
are-
1 :: - Scope resolution operators.
2 ::* - pointer to member declaration.
3 *-pointer to member operator.
4 .* - pointer to member operator.4 .* - pointer to member operator.
5 delete - memory release operator.
6 new - Memory allocation operator.
7 endl - Line feed operator
8 setw - Field width operator.
63
SCOPE RESOLUTION OPERATOR
� In C, the global version of a variable cannot be accessed from
within the inner block.
� C++ resolves this problem by using scope resolution operator
(::), because this operator allows access to the global version of
a variable.
� C++ is a block - structured language.� C++ is a block - structured language.
� The scope of the variable extends from the point of its
declaration till the end of the block containing the declaration.
� A major application of the scope resolution operator is in the
classes to identify the class to which a member functions
belongs.
64
MEMBER DEREFERENCING OPERATORS
� C++ permits us to define a class containing various types of
data & functions as members.
� C++ also permits us to access the class members through
pointers.
� C++ provides a set of three pointer to member operators.
1) ::* - To access a member of a class.� 1) ::* - To access a member of a class.
� 2) .* - To access a member using object name & a pointer to
that member.
� 3) * - To access a member using a pointer in the object
& a pointer to the member.
65
MEMORY MANAGEMENT OPERATORS.
1) C++ supports two unary operators new and delete that
perform the task of allocating & freeing the memory.
2) An object can be created by using new and destroyed by using
delete.
A data object created inside a block with new, will remain
existence until it is explicitly destroyed by using delete.
3) It takes following form.
variable = new data type
The new operator allocated sufficient memory to hold a data
object of type data-type & returns the address of the object.
EX - p = new int.
Where p is a pointer of type int.66
CONTD…
4) New can be used to create a memory space for any data type
including user defined type such as array, classes etc.
Ex- int * p = new int [10]
Creates a memory space for an array of 10 integers.
5) When a data object is no longer needed, it is destroyed to5) When a data object is no longer needed, it is destroyed to
release the memory space for reuse. The general form is
delete variable.
If we want to free a dynamically allocated array, we must use
following form.
delete [size] variable.
The size specifies the no of elements in the array to be freed67
CONTD…
6) The new operator has following advantages over the
function malloc() in c -.
i) It automatically computes the size of the data object.
ii) No need to use sizeOf().
iii) If automatically returns the correct pointer type, so thatiii) If automatically returns the correct pointer type, so that
there is no need to use a type cast.
iii) new and delete operators can be overloaded.
iv) It is possible to initialize the object while creating the
memory space.
68
MANIPULATORS
� Manipulators are operators that are used to format the data
display. There are two important manipulators.
� 1) endl 2) setw
� 1) endl : - This manipulator is used to insert a linefeed into an
output. It has same effect as using “\n” for newline.
Ex- cout<< “a” << a << endl <<“n”= <<n;Ex- cout<< “a” << a << endl <<“n”= <<n;
<< endl<<“p”=<<p<<endl;
� The output is
a = 2568
n = 34
p = 27569
� 2) Setw : With the setw, we can specify a common field
width for all the numbers and force them to print with
right alignment.
EX . cout<<setw (5) <<sum<<endl;
� The manipulator setw(5) specifies a field width of 5 for� The manipulator setw(5) specifies a field width of 5 for
printing the value of variable sum the value is right
justified.
70
3 5 6
// setw example
#include <iostream.h>
#include <iomanip.h>
void main ()
{
cout << setw(10); cout << setw(10);
cout << 77 << endl;
getch( ) ;
}
Output:
71
7 7
// setfill example
#include <iostream.h>
#include <iomanip.h>
void main ()
{
cout << setfill ('x') << setw (10); cout << setfill ('x') << setw (10);
cout << 77 << endl;
getch();
}
� Output:
xxxxxxxx77 72
ASSIGNMENT STATEMENT
� The assignment statement takes the form:
variable = expression;
� Expression is evaluated and its value is assigned to the
variable on the left sidevariable on the left side
� In C++ = is called the assignment operator
73
CONTROL STRUCTURES
� Three control structures
�Sequence structure
�Programs executed sequentially by default
�Selection structures
if, if…else, switch �if, if…else, switch
�Repetition structures
�while, do…while, for
74
1.IF STATEMENT
� The if statement is implemented in two forms
� 1. Simple if statement
� 2. if …else statement
� Both are used for decision making tasks
75
CONTD…
� Form1
� if (expression is true)
{
action1;
}}
action2;
76
CONTD…
� Form2
if (expressions is true)
{
action1;
}
elseelse
{
action2;
}
action3;
77
2. SWITCH STATEMENT
� Multiple-branching statement.
� Based on condition, control is transferred to one of many
possible points.possible points.
78
� Format:- switch(expression)
{ case1:
{
action1;
}case2:
{
action2;
}}
case3:
{
action3;
}
default:
{
action4;
}
} action5;
79
3.DO-WHILE STATEMENT
� It is an exit controlled loop.
� Based on a condition, control is transferred back to a
particular point in the program
do
{
action1;action1;
}
while(condition is true)
action2;
80
4.WHILE STATEMENT
� Entry-controlled loop structure.
While(condition is true)
{
action1;
}}
action2;
81
5.FOR STATEMENT
� Entry-controlled loop.
� Used when action is to be repeated for a predetermined
number of times.
for( initial value; test; increment)
{{
action1;
}
action2;
82
ARRAYS
� Array
� Group of consecutive memory locations
� Same name and type
� To refer to an element, specify
� Array name
Name of array (Note
that all elements
of this array have
the same name, c)
-
456
0
7
2154
c[0]
c[1]
c[2]
c[3]
c[4]
� Position number
� Format:
Array name[ position number ]
� First element at position 0
� n element array named c:
c[ 0 ], c[ 1 ]...c[ n – 1 ]Position number of
the element within
array c
c[6]
2154
3-
890
6
2-
31
645
3 7
8
c[11]
c[10]
c[9]
c[8]
c[7]
c[5]
c[4]
83
DECLARINGARRAYS
� When declaring arrays, specify
� Name
� Type of array
� Number of elements
array Type array Name[number of elements];
� Examples:
int c[ 10 ];
float myArray[ 3284 ];
� Declaring multiple arrays of same type
� Format similar to regular variables
� Example:
int b[ 100 ], x[ 27 ]; 84
ARRAY INITIALIZATION
� Initializers
int n[ 5 ] = { 1, 2, 3, 4, 5 };
� If size omitted, initializers determine it
int n[ ] = { 1, 2, 3, 4, 5 };
� 5 initializers, therefore 5 element array
85
CONTD…
� Character arrays
� String “first” is really a static array of characters
� Character arrays can be initialized using string literals
char string1[ ] = "first";
�Null character '\0' terminates strings
� string1 actually has 6 elements
� It is equivalent to
char string1[ ] = { 'f', 'i', 'r', 's', 't', '\0' };
� Can access individual characters
string1[ 3 ] is character ‘s’
86
PASSINGARRAYS TO FUNCTIONS
� Passing arrays
� To pass an array argument to a function, specify the name of
the array without any brackets
int myArray[ 24 ];
myFunction( myArray, 24 );
Array size usually passed to function �Array size usually passed to function
� Arrays passed call-by-reference
� Name of array is address of first element
� Passing array elements
� Passed by call-by-value
� Pass subscripted name (i.e., myArray[ 3 ]) to function
87
CONTD…
� Function prototype
void modifyArray( int b[], int arraySize );
� Parameter names optional in prototype
int b[] could be written int []�int b[] could be written int []
�int arraySize could be simply int
88
SORTINGARRAYS
� Sorting data
� Important computing application
� Virtually every organization must sort some data
� Bubble sort
� Several passes through the array
� Successive pairs of elements are compared � Successive pairs of elements are compared
�If increasing order (or identical ), no change
�If decreasing order, elements exchanged
� Repeat
89
� Example:
� original: 3 4 2 6 7
� pass 1: 3 2 4 6 7
� pass 2: 2 3 4 6 7
� Small elements "bubble" to the top� Small elements "bubble" to the top
� Like bubble sort we can use quick and
90
SEARCHING ARRAYS
� Search an array for a key value
� Linear search
� Simple
� Compare each element of array with key value
� Useful for small and unsorted arrays
� Binary search � Binary search
� For sorted arrays
� Compares middle element with key
� If equal, match found
� If key < middle, looks in first half of array
� If key > middle, looks in last half
�Repeat91
TWO DIMENSIONALARRAYS
� Two Dimensional Arrays contains
� Tables with rows and columns (m by n array)
� Like matrices: specify row, then column
Column 0 Column 1 Column 2 Column 3
Row 0Row 1Row 2
Column 0 Column 1 Column 2 Column 3
a[ 0 ][ 0 ]
a[ 1 ][ 0 ]
a[ 2 ][ 0 ]
a[ 0 ][ 1 ]
a[ 1 ][ 1 ]
a[ 2 ][ 1 ]
a[ 0 ][ 2 ]
a[ 1 ][ 2 ]
a[ 2 ][ 2 ]
a[ 0 ][ 3 ]
a[ 1 ][ 3 ]
a[ 2 ][ 3 ]
Row subscriptArray name
Column subscript
92
CONTD…
� Initialization
� int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
� Initializers grouped by row in braces
� If not enough, unspecified elements set to zero
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
1 2
3 4
1 0int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
� Referencing elements
� Specify row, then column
printf( "%d", b[ 0 ][ 1 ] );
1 0
3 4
93
STRINGS
� A string is a sequence of characters
� A null terminated <char> arrays to store and manipulate
strings.
� ANSI C++ provides a class called string.
� Include <string.h> in our program.
94
STRINGS
� In C, a string can be a specially terminated char array or char pointer� a char array, such as char str[ ]=“high”;
� a char pointer, such as char *p = “high”;
� If a is char array, the last element of the array must be equal to ‘\0’, signaling the end
� For example, the above str[ ] is really of length 5:
str[0]=‘h’ str[1]=‘i’ str[2]=‘g’ str[3]=‘h’ str[4]=‘\0’str[0]=‘h’ str[1]=‘i’ str[2]=‘g’ str[3]=‘h’ str[4]=‘\0’
� The same array could’ve been declared as: � char str[5] = {‘h’,’i’, ‘g’,’h’,’\0’};
� If you write char str[4] = {‘h’,’i’, ‘g’,’h’};, then str is an array of chars but not a string.
� In char *p=“high”; the system allocates memory of 5 characters long, stores “high” in the first 4, and ‘\0’ in the 5th.
95
DECLARATION OF STRINGS
� The following instructions are all equivalent.
� They declare x to be an object of type string, and
assign the string “high school” to it:
� string x(“high school”);� string x(“high school”);
� string x= “high school”;
� string x;
� x=“high school”;
96
THE STRING CLASS IN C++
� C++ has a <string> library
� Include it in your programs when you wish to use
strings:
#include <string.h>
In this library, a class string is defined and� In this library, a class string is defined and
implemented
� It is very convenient and makes string processing
easier than in C
97
AVAILABLE OPERATIONS
� Creating string objects.
� Reading string objects from keyboard.
� Displaying string objects to the screen.
� Finding a substring from a string.
� Modifying string objects.
� Adding string objects.
� Accessing characters in a string.
� Obtaining the size of string.
� And many more.
98
OPERATIONS ON STRINGS
(CONCATENATION)
� Let x and y be two strings
� To concatenate x and y,
� write: x+y
string x= “high”;string x= “high”;
string y= “school”;
string z;
z=x+y;
cout<<“z=“<<z<<endl;
z =z+“ was fun”;
cout<<“z=“<<z<<endl;
Output:
z=highschool
z= highschool was fun
99
CONCATENATION OF MIXED-STYLE STRINGS
� In
� where s is of type string,
� u can be
�A string object, or
�a C-style string (a char array or a char
s=u+v+w;
�a C-style string (a char array or a char pointer),
�a C-style char
�or a double-quoted string,
�or a single-quoted character.
� Same with v and w.
� At least u or v or w must be a string object
100
THE CONCAT-ASSIGN OPERATOR +=
� Assume x is a string object.
� The statement
x += y;
is equivalent to
x=x+y;x=x+y;
where y can be a string object, a C-style stringvariable, a char variable, a double-quoted string, or asingle-quoted char.
101
COMMONLY USED STRING FUNCTIONS
� String();
� // For creating an empty string.
� String(const char *str);
� // For creating a string object from a null-terminated
string.string.
� String(const string &str);
� // For creating a string object from other string object.
102
CREATING STRING OBJECTS
string s1, s3; //creates two strings with no arguments.
string s2(“xyz”); // string with one-argument
s1 = s2; // Assigning string objects
s3 = “abc” + s2; // Concatenating strings
cin >> s1; // Reading from keyboard (one word)cin >> s1; // Reading from keyboard (one word)
cout << s2; // Display the content of s2
getline(cin, s1) // Reading from keyboard a line of text
s3 += s1; // s3 = s3 + s1;
s3 += “abc”; // s3 = s3 + “abc”;
103
MANIPULATING STRING OBJECTS
� insert()
� erase()
replace()� replace()
� append()
104
MANIPULATING STRING OBJECTS
� string s1(“12345”);
� string s2(“abcde”);
� s1.insert(4, s2); // s1 = 1234abcde5
� s1.erase(4, 5); // s1 = 12345
� s2.replace(1, 3, s1); // s2 = a12345e
105
RELATIONAL OPERATIONS
Operator Meaning
== Equality
!= Inequality
< Less than
<= Less than or equal
� string s1(“ABC”); string s2(“XYZ”);
� int x = s1.compare(s2);
� x == 0 if s1 == s2
� x > 0 if s1 > s2
� x < 0 if s1 < s2
> Greater than
>= Greater than or equal
106
STRING CHARACTERISTICS
Function Task
size() Number of elements currently
stored
length() Number of elements currently
stored
capacity() Total elements that can be capacity() Total elements that can be
stored
max_size() Maximum size of a string
object that a system can
support
empty() Return true or 1 if the string is
empty otherwise returns false
or 0
resize() Used to resize a string object
(effects only size and length)107
STRING CHARACTERISTICS
void display(string &str)
{
cout << “Size = ” << str.size() << endl;
cout << “Length = ” << str.length() << endl;
cout << “Capacity = ” << str.capacity() << endl;cout << “Capacity = ” << str.capacity() << endl;
cout << “Max Size = ” << str.max_size() << endl;
cout << “Empty: ” << (str.empty() ? “yes” : “no”)
<< endl;
cout << endl << endl;
}108
ACCESSING CHARACTERS IN STRINGS
Function Task
at() For accessing individual characters
substr() For retrieving a substring
find() For finding a specific substring
find_first_of( ) For finding the location of first occurrence of the find_first_of( ) For finding the location of first occurrence of the
specific character(s)
find_last_of( ) For finding the location of last occurrence of the
specific character(s)
[ ] operator For accessing individual character.
Makes the string object to look like an array.
109
POINTERS
� Pointers
� Powerful feature of the C++ language
� One of the most difficult to master
� Essential for construction of interesting data � Essential for construction of interesting data
structures
110
ADDRESSES AND POINTERS
� C++ allows two ways of accessing variables
� Name
� Address
� Symbol & gets the address of the variable that � Symbol & gets the address of the variable that
follows it
� Addresses/Pointers can be displayed by the cout
statement
� Addresses displayed in HEXADECIMAL
111
EXAMPLE
#include <iostream.h>
void main( )
{
int data = 100;
float value = 56.47;
cout << data << &data << endl;
56.47
100
FFF1
FFF0
FFF2
FFF3
FFF4
FFF5
FFF6
value
data
cout << data << &data << endl;
cout << value << &value << endl;
}
Output:
100 FFF4
56.47 FFF0
FFF6
112
DECLARATION OF POINTER VARIABLES
� A pointer variable is declared by:
dataType *pointerVarName;
� The pointer variable pointerVarName isused to point to a value of type dataType
� The * before the pointerVarNameindicates that this is a pointer variable,not a regular variablenot a regular variable
� Example
int *ptr1;
float *ptr2;
� ptr1 is a pointer to an int
� ptr2 is a pointer to a float value113
DECLARATION OF POINTER VARIABLES
(CONT ..)
� Whitespace doesn’t matter and each of thefollowing will declare ptr as a pointer (to a
float) variable and data as a float
variable
float *ptr, data;
float* ptr, data;
float (*ptr), data;
float data, *ptr;
114
ASSIGNMENT OF POINTER VARIABLES
� A pointer variable has to be assigned a valid memory address before it can be used in the program
� Example:
float data = 50.8;float data = 50.8;
float *ptr;
ptr = &data;
� This will assign the address of the memorylocation allocated for the floating point variabledata to the pointer variable ptr.
115
ASSIGNMENT OF POINTER VARIABLES
(CONT ..)
float data = 50.8;
FFF1
FFF0
FFF2float data = 50.8;
float *ptr;
ptr = &data; 50.8
FFF3
FFF4
FFF5
FFF6
data
116
ASSIGNMENT OF POINTER VARIABLES
(CONT ..)
float data = 50.8;
FFF1
FFF0
FFF2
ptr
float data = 50.8;
float *ptr;
ptr = &data; 50.8
FFF3
FFF4
FFF5
FFF6
data
117
ASSIGNMENT OF POINTER VARIABLES
(CONT ..)
float data = 50.8;
FFF4
FFF1
FFF0
FFF2
ptr
float data = 50.8;
float *ptr;
ptr = &data; 50.8
FFF3
FFF4
FFF5
FFF6
data
118
INITIALIZING POINTERS
�A pointer can be initialized duringdeclaration by assigning it the address of anexisting variable
float data = 50.8;
float *ptr = &data;float *ptr = &data;
� If a pointer is not initialized duringdeclaration, it is wise to give it a NULL (0)value
int *ip = 0;
float *fp = NULL;
119
OPERATIONS ON POINTER VARIABLES
�Assignment – the value of one pointervariable can be assigned to anotherpointer variable of the same type
�Relational operations - two pointervariables of the same type can bevariables of the same type can becompared for equality, and so on
�Some limited arithmetic operations� integer values can be added to and subtracted from apointer variable
� value of one pointer variable can be subtracted fromanother pointer variable
120
POINTERS TO ARRAYS
� A pointer variable can be used to access the elements of an array of the same type.
#include <iostream.h>
int main()
{ //array
int intarray[5] = { 31, 54, 77, 52, 93 };
for(int j=0; j<5; j++) //for each element,
cout << intarray[j] << endl; //print valuecout << intarray[j] << endl; //print value
return 0;}
31
54
77
52
93
121
#include <iostream.h>
#include<conio.h>
void main()
{ //array
int intarray[5] = { 31, 54, 77, 52, 93 };int intarray[5] = { 31, 54, 77, 52, 93 };
for(int j=1; j<5; j++)
cout << *(intarray) << endl;
getch();
}
O/p :-31 31 31 31122
int gradeList[8] =
{92,85,75,88,79,54,34,96};
int *myGrades = gradeList;
cout << gradeList[1];
cout << *myGrades;
cout << *(myGrades + 2);cout << *(myGrades + 2);
cout << myGrades[3];
� Note that the array name gradeList acts like
the pointer variable myGrades.
� O/P = 85 92 75 88123
POINTERS AS ARGUMENTS TO FUNCTIONS
� Pointers can be passed to functions just like other
types.
� Just as with any other argument, verify that the
number and type of arguments in functionnumber and type of arguments in function
invocation match the prototype (and function
header).
124
EXAMPLE OF POINTER ARGUMENTS
(PASS BY VALUE)
void Swap(int *p1, int *p2);
void main (){
int x, y;cin >> x >> y;cin >> x >> y;cout << x << " " << y << endl;Swap(&x,&y); // passes addresses of x and y
explicitlycout << x << " " << y << endl;
}void Swap(int *p1, int *p2){
int temp = *p1;*p1 = *p2;*p2 = temp;
}
125
EXAMPLE OF REFERENCE ARGUMENTS
(PASS BY REFERENCE)
void Swap(int &a, int &b);
void main (){
int x, y;cin >> x >> y;cin >> x >> y;cout << x << " " << y << endl;
Swap(x,y); //passes addresses of x and y implicitlycout << x << " " << y << endl;
}void Swap(int &a, int &b){
int temp = a;a = b;b = temp;
}
126
SAMPLE PROGRAMS ON POINTERS
#include <iostream.h>
#include<conio.h>
void main ()
{
int firstvalue, secondvalue;
int * mypointer;
cout << "firstvalue is " <<
firstvalue <<'\n';
cout << "secondvalue is "
<< secondvalue <<‘\n';
getch();
}
127
mypointer = &firstvalue;
*mypointer = 10;
mypointer = &secondvalue;
*mypointer = 20;
}
firstvalue is 10
secondvalue is 20
FUNCTIONS IN C++� Experience has shown that the best way to develop and maintain large programs is to construct it from smaller pieces(Modules)
� This technique Called “Divide and Conquer”
main()
{
Bad Development ApproachEaser To
�Design
�Build
Wise Development Approach
main()
{
----------
-----
-----
-----
.
.
.
----
-----
-----
Return 0;
}
�Build
�Debug
�Extend
�Modify
�Understand
�Reuse
�Better Organization
-----
----
}
function f1()
{
---
---
}
function f2()
{
---
---
}128
FUNCTION DEFINITION
�Syntax format for function definitionreturned-value-type function-name (parameter-list)
{
Declarations of local variables and Statements
}
� Parameter list� Parameter list
�Comma separated list of arguments
�Data type needed for each argument
�If no arguments, use void or leave blank
� Return-value-type
�Data type of result returned (use void if nothing returned)
129
FUNCTION DEFINITION
�Example function
int square( int y )
{
return y * y;
}
�return keyword
� Returns data, and control goes to function’s caller
�If no data to return, use return;
� Function ends when reaches right brace
�Control goes to caller
� Functions cannot be defined inside other functions130
USER-DEFINED C++ FUNCTIONS
� C++ provides its users with a way to define their
own functions (or user-defined function)
� For example, the <math.h> library does not include
a standard function that allows users to round a
real number to the ith digits, therefore, we must
declare and implement this function ourselvesdeclare and implement this function ourselves
131
EXAMPLE OF USER-DEFINED
C++ FUNCTION
double computeTax(double income)
{
if (income < 5000.0) return 0.0;if (income < 5000.0) return 0.0;
double taxes = 0.07 * (income-5000.0);
return taxes;
}
132
EXAMPLE OF USER-DEFINED
C++ FUNCTION
double computeTax(double income)
{
if (income < 5000.0) return 0.0;
Function
headerFunction
body
if (income < 5000.0) return 0.0;
double taxes = 0.07 * (income-5000.0);
return taxes;
}
133
FUNCTION CALL METHODS� Call by value
• A copy of the value is passed
� Call by reference
• The caller passes the address of the value
� Call by value
� A copy of the value (known) is passed from the caller-function to the called-function
� Any change to the copy does not affect the original value inthe caller function
� Advantages, prevents side effect, resulting in reliablesoftware
134
� Call By Reference
� reference-parameter is used to perform call byreference.
�The caller gives the called function the ability todirectly access the caller’s value, and to modify it.
�A reference parameter is an alias for it’s correspondingargument, it is stated in c++ by “flow the parameter’stype” in the function prototype by an ampersand(&)also in the function definition-header.
�Advantage: performance issue
135
void function_name (type &);// prototype
main()
{{
-----
------
}
void function_name(type ¶meter_name)
136
PROGRAM TO FIND FACTORIAL
� #include<iostream.h>
� #include<conio.h>
void main()
{
int num, factorial=1;
cout<<" Enter Number To Find Its Factorial: ";
cin>>num;cin>>num;
for(int a=1;a<=num; a++)
{ factorial=factorial*a;
}
cout<<"Factorial of Given Number is
="<<factorial<<endl;
getch();
} 137
PROGRAM FOR PRIME NUMBER
#include<iostream.h>
#include<conio.h>
void main()
{
int number,count=0;
cout<<"Enter number ;
cin>>number;
for(int a=1;a<=number;a++)
if(count==2)
{
cout<<" Prime number;
}
else
{
cout<<" Not a prime
138
for(int a=1;a<=number;a++)
{
if(number%a==0)
{ count++;
}
}
cout<<" Not a prime
number \n";
}
getch();
}
BUBBLE SORT
#include<iostream.h>
void main(){
//declaring array
int array[5];
cout<<"Enter 5 numbers
randomly : "<<endl;
for(int i=0; i<5; i++)
{
for(int j=0; j<5; j++) {
//Displaying Arraycout<<Value at "<<j<<" Index: “<<array[j]<<endl;
}cout<<endl;
// Bubble Sort Starts Hereint temp;
for(int i2=0; i2<=4; i2++){for(int j=0; j<4; j++)
139
{
cin>>array[i];
}
cout<<endl;
cout<<"Input array is: "<<end
l;
for(int j=0; j<4; j++){
if(array[j]>array[j+1]){temp=array[j];array[j]=array[j+1];array[j+1]=temp;}}}
� // Displaying Sorted array
� cout<<" Sorted Array is: "<<e
ndl;
for(int i3=0; i3<5; i3++)
{
cout<<"\t\t\tValue at "<<i3<
<" Index: "<<array[i3]<<endl;
}
140
}
getch();
}
RECURSION AND RECURSIVE FUNCTIONS
� Main calls another function…..normal
� A function calls another function2….normal
� A function calls itself ?! Possible?? YES
����A recursive function is one that call itself.
141
CONCEPT OF RECURSION
� A recursive function is called to solve a problem
� The function knows to solve only the simplest cases or so-called base-cases.
� Thus if the function called with a base-case, it simplyreturns a result. But if it is called with more complexproblem, the function divides the problem into tworeturns a result. But if it is called with more complexproblem, the function divides the problem into twoconceptual pieces, one knows how to do, and anotherdoesn't know what to do.
� The second case/piece must resemble the original problem,but be a slightly simpler/smaller version of the originalproblem
142
CONCEPT OF RECURSION (CONT.)
� Thus the function calls a fresh copy of itself to work onthe smaller problem –this is related as a Recursive-call/recursive step.
� The function keeps dividing each new sub problem intotwo conceptual pieces until eventually terminates aftertwo conceptual pieces until eventually terminates afterconverging on the base-case.
� The function thus recognize the base-case and returns aresult to the previous copy of the way up the line untiloriginal call of the function returns the final result tomain.
143
FINDING FACTORIAL RECURSIVELY
5!
5*4!
4*3!
5!
5*4!
Final value=120
4!=4*6=24 returned
5!=5*24=120 returned
4*3!
3*2!
2*1!
1
4*3!
3*2!
2*1!
1
1
2!=2*1=2 returned
3!=3*2=6 returned
144
FINDING FACTORIAL RECURSIVELY//Recursive factorial Function
#include<iostream.h>long factorial(long);//prototype
int main(){
long factorial(long n){if ( n <= 1)
//the base casereturn 1;
else
145
{int num;cout<<“enter a positive integer:”;cin>>num;cout<<“factorial=“
<<factorial(num);return 0;
}
elsereturn n *
factorial (n - 1);}
RECURSIVE FUNCTION TO PRINT THE NUMBERS
1-10 TO THE SCREEN
#include <iostream.h>
int rec(int num);
void main()
{
int n=10;
int rec(int num)
{
int val;
if(num==10)
146
int n=10;
cout << rec(n);
}
if(num==10)
return num;
val = rec(num) - 1;
return(val);
}
FIBONACCI NUMBERS
#include <iostream.h>
int fib(int n)
// 1, 1, 2, 3, 5, 8, 13,
{
if (n == 0 || n == 1)
return 1;
void main()
{
int n;
cout << "Enter an
integer: ";
cin >> n;
147
return 1;
return
fib(n-1) + fib(n-2);
}
cin >> n;
cout << "Fib = " << fib(n)
<< endl;
return 0;
}
� Function overloading
� Functions with same name and different parameters
� Should perform similar tasks
� i.e., function to square ints and function to square floats
int square( int x) {return x * x;}
float square(float x) { return x * x; }
FUNCTION OVERLOADING
float square(float x) { return x * x; }
� A call-time c++ complier selects the proper function by
examining the number, type and order of the parameters
148
FUNCTION OVERLOADING
� Two or more functions can have the same
name but different parameters
� Example:
int max(int a, int b) float max(float a, float b)int max(int a, int b)
{
if (a>= b)
return a;
else
return b;
}
float max(float a, float b)
{
if (a>= b)
return a;
else
return b;
}
149
SAMPLE PROGRAM
#include <iostream>
// abs is overloaded three ways
int abs(int i);
double abs(double d);
long abs(long l);
int main()
{
int abs(int i)
{
cout << "Using integer abs()\n";
return i<0 ? -i : i;
}
double abs(double d)
{
cout << "Using double abs()\n";
150
{
cout << abs(-10) << "\n";
cout << abs(-11.0) << "\n";
cout << abs(-9L) << "\n";
return 0;
}
abs()\n";
return d<0.0 ? -d : d;
}
long abs(long l)
{
cout << "Using long abs()\n";
return l<0 ? -l : l;
}
The output from this program is shown here.
Using integer abs() 10
Using double abs() 11
Using long abs() 9Using long abs() 9
151