• “High-level"
programming languages are those languages whose syntax is relatively close to
natural language.
• C++
was developed by Bjarne Stroustrup of AT&T Bell Laboratories in the early
1980‘s.
• C++
is based on the C language.
• The
name C++ :- "++" is a
syntactic construct used in C (to increment a variable), and C++ is intended as
an incremental improvement of C.
• Most
of C is a subset of C++, so that most C programs can be compiled using a C++
compiler.
ANSI C++
• The
American National Standards Institution (ANSI) provides "official"
and generally accepted standard definition of C++.
• A
program written only in ANSI C++ is guaranteed to run on any computer whose
supporting software conforms to the ANSI standard.
• In
other words, the standard guarantees that ANSI C++ programs are portable.
Writing C++ Programs
You
will require:
• An
editor with which to write and modify the C++ program components or
source code,
• A
compiler with which to convert the source code into machine
instructions which can be executed by the computer directly,
• A
linking program with which to link the compiled program
components with each other and with a selection of routines from existing
libraries of computer code, in order to form the complete machine-executable
object program,
• A
debugger to help diagnose problems, either in compiling programs
in the first place, or if the object program runs but gives unintended results.
EXAMPLE
#include <iostream>
void main() {
int a;
cout <<
"Enter the value of a";
cin >> a;
cout << “The
vaue of a is:“+a;
};
FEATURES OF C++
• Classes
• Inheritance
• Data
abstraction and encapsulation
• Polymorphism
• Dynamic
Binding
• Message
Passing
Classes and Objects
• CLASS:
A class is a definition of an object. A class is a way to bind data and its
associated functions together.
• Classes
are generally declared using the keyword class, with the following
format:
class class_name
{
// data members
// member
functions
};
• Data
items within a class are called data members.
• Functions
that included within a class are called member functions.
• There
can be any number of data members and member functions within a class.
• OBJECT: An object is an
instance of a class.
• Objects
are used to access data and functions defined in a class.
• When
the object is physically created, space for that object is allocated in RAM.
• It
is possible to have multiple objects created from one class.
• Example:
• class_name obj1, obj2, obj3;
•
INHERITANCE
• Inheritance
is the process of creating new classes from existing classes.
• The
new class is called derived class.
• The
existing class is called base class.
• The
derived class contains the features of base class and can add new features of
its own.
• This
provides the idea of reusability that means we can add the new features to an
existing class without modifying it.
DATA ABSTRACTION
• Data
abstraction refers to providing only essential information to the outside
word and hiding their background details, ie. to represent the needed
information in program without presenting the details.
• C++
classes provides great level of data abstraction.
• They
provide sufficient public methods to the outside world to manipulate object
data without actually knowing how class has been implemented internally.
• For
example, cout can be used to display text.
• Here
you don't need to understand how cout displays the text on the user's
screen.
• Any
C++ program where you implement a class with public and private members is an
example of data abstraction.
DATA ENCAPSULATION
• Encapsulation
is an Object Oriented Programming concept that binds together the data and
functions that manipulate the data.
• Using
the method of encapsulation, the programmer cannot directly access the data.
Data is only accessible through the functions existing inside the class.
• Encapsulation
makes maintenance of applications easier, and improves security.
• Data
encapsulation leads to data abstraction, data hiding and friend functions.
• Data
encapsulation is a mechanism of bundling the data, and the functions that
use them and data abstraction is a mechanism of exposing only the
interfaces and hiding the implementation details from the user.
POLYMORPHISM
• ‘poly’
means many, and ‘morph’ means form or shape.
• The
word polymorphism means having many forms.
• Using
operators or functions in different ways depending upon what they are operating
on, is called polymorphism.
• Example:
• 4 + 5 <-- integer addition
• 3.14 + 2.0
<-- floating point addition
• s1 + "bar" <-- string concatenation!
• Here,
a single operator + behaves differently in different contexts such as
integer, float or strings referring the concept of polymorphism.
• Polymorphism
includes the concepts of:
• Virtual
functions
• Function
name overloading
• Operator
overloading
• Types
of polymorphism:
• compile-time
polymorphism (or static polymorphism) -- exhibited by overloaded functions.
• run-time
polymorphism (or dynamic polymorphism)
-- exhibited by using late binding.
DYNAMIC BINDING
• Also
called "late binding“.
• Binding
refers to the linking of a procedure call to the code to be executed in
response to the call.
• Dinamic
binding means that the code associated with a given procedure call is not known
until the time of call at run-time.
• It
is the linking of a routine or object at runtime based on the conditions at
that moment. The property of object-oriented programming languages where the
code executed to perform a given operation is determined at run time from the
class of the operand(s) (the receiver of the message).
• In case of dynamic binding, the
decision is made at run-time based upon the actual object.
• C++
implements dynamic binding using "virtual member functions",
e.g.,
class
Base {
virtual
int fun ()
{
cout << "hello";
}
};
MESSAGE PASSING
• A
message for an object is a request for execution of a procedure, and therefore will
invoke a function in the receiving object that generates the desired results.
• An
object oriented program consists of the set of objects that communicate with
each other. Objects communicate with one another by sending and receiving
information much the same way as people pass messages to one another.
• The concept of message passing makes it easier
to direct model or simulate their real world counterparts.
• Following
are the basic steps in message passing.
– Creating
classes that define objects and its behaviour.
– Creating
objects from class definitions
– Establishing
communication among objects
• In
OOPs, Message Passing involves specifying the name of objects, the name of the
function, and the information to be sent.
Differences between C and C++
C
|
C++
|
It is a
procedural language.
|
It is an
object-oriented programming (OOP) language.
|
Follows a
top-down approach.
In case of
C, the program is formulated step by step, each step is processed into
detail.
|
Follows a
bottom-up approach.
In C++, the
base elements are first formulated which then are linked together to give
rise to larger systems.
|
Developed
by Dennis Ritchie.
|
Developed
by Bjarne Stroustrup.
|
Data is not
secure.
|
Data is
secure (hidden) (using the concept of Data Hiding).
|
It is
function-driven.
Functions
are the building blocks of a C program.
|
It is
object-driven.
Objects are
building blocks of a C++ program.
|
Structures
cannot contain functions in C.
|
Functions
can be used inside a structure in C++.
|
C does not
support function overloading.
|
C++
supports function overloading.
|
NAMESPACE
feature is absent in case of C.
|
C++ uses
NAMESPACE which avoid name collisions.
|
C does not
have different visibility mode to store data. It stores data in a default
mode irrespective of the data type.
|
C++
provides different data visibility modes : Public, Private, and Protected.
|
C program
has extension .c
|
C++ program
has extension .cpp
|
C does not
allow the use of reference variables.
|
C++ allows
the use of reference variables. Reference variables allow two variable names
to point to the same memory location.
|
In c a
character constant is automatically elevated to an integer.
|
In c++,
this is not the case.
|
C does not
support inheritance, reusability, polymorphism
|
C++
supports inheritance, reusability, polymorphism.
|
C does not
support Exception Handling.
|
C++
supports Exception Handling.
|
Data Types
in C++
Type
|
Bytes
|
Range
|
char
|
1
|
-128
to 127
|
unsigned
char
|
1
|
0
to 255
|
signed
char
|
1
|
-128
to 127
|
int
|
2
|
-32768
to 32767
|
unsigned
int
|
2
|
0
to 65535
|
signed
int
|
2
|
-32768
to 32767
|
short
int
|
2
|
-32768
to 32767
|
unsigned
short int
|
2
|
0
to 65535
|
signed
short int
|
2
|
-32768
to 32767
|
long
int
|
4
|
-2147483648
to 2147483647
|
signed
long int
|
4
|
-2147483648
to 2147483648
|
unsigned
long int
|
4
|
0
to 4294967295
|
float
|
4
|
3.4E-38
to 3.4E+38
|
double
|
8
|
1.7E-308
to 1.7E+308
|
long
double
|
10
|
3.4E-4932
to 1.1E+4932
|
•
With the exception of void, the basic data types
may have several modifiers preceding them to serve the needs of various
situations.
•
The modifiers are: signed, unsigned, long, and short.
Uses of void
•
To specify the return type of a function when it
does not return any value.
•
To indicate an empty argument list to a function
•
void is used in the declaration of generic
pointers, example: void *gp;
Enumerated Data Type
•
An enumerated type is a data type
where every possible value is defined as a symbolic constant (called an enumerator).
•
Enumerated types are declared via the enum
keyword.
•
An enumerated type (also called enumeration
or enum) is a data type consisting of a set of named values called elements,
members or enumerators of the type.
•
For example, the four suits in a deck of playing
cards may be four enumerators named CLUB, DIAMOND, HEART, SPADE,
belonging to an enumerated type named suit. If a variable V is
declared having suit as its data type, one can assign any of those four
values to it.
•
It provides a way for attaching names to
numbers, thereby increasing comprehensibility of code.
•
The enum keyword automatically enumerates a list
of words by assigning them values 0,1,2 and so on.
•
This facility provides an alternative means for
creating symbolic constants.
Eg. enum shape { circle, square, triangle };
By default circle=0, square =1, triangle =2
We can override the default values by assigning integer values to the enumerators.
Eg. enum color { red, blue=4, green = 8 };
red=0 ( by default )
Eg. enum shape { circle, square, triangle };
By default circle=0, square =1, triangle =2
We can override the default values by assigning integer values to the enumerators.
Eg. enum color { red, blue=4, green = 8 };
red=0 ( by default )
Syntax:
•
enum identifier{v1,v2,v3,.......vn};
or
enum identifier{v1,v2,v3,.......vn}variable;
or
enum identifier{v1,v2,v3,.......vn}variable;
Example:
•
enum shape { circle, square, triangle };
•
enum shape s1 = circle;
•
enum shape s2 = triangle;
EXAMPLE
#include
<iostream.h>
#include <conio.h>
enum company_size
{
small=500,medium=1000,large=1500
};
enum company_size company1,company2;
void main()
{
company1=small;
cout << company1;
getch();
}
Output :
500
#include <conio.h>
enum company_size
{
small=500,medium=1000,large=1500
};
enum company_size company1,company2;
void main()
{
company1=small;
cout << company1;
getch();
}
Output :
500
===================================================================
The sizeof operator yields the size in bytes
of the operand, which can be an expression or the parenthesized name of a type.
It is a
unary operator.
The sizeof
operator applied to a type name yields the amount of memory that would be used
by an object of that type.
Example:
short
x; ... sizeof (x) /* the value of
sizeof operator is 2 */
short
x; ... sizeof (x + 1) /* value is 4,
result of addition is type int */
One of
the most common uses for the sizeof operator is to determine
the size of objects that are referred to during storage allocation, input, and
output functions.
====================================================================
C++ Operator Precedence
The following table lists the
precedence and associativity of C++ operators. Operators are listed top to
bottom, in descending precedence.
Precedence
|
Operator
|
Description
|
Associativity
|
1
|
::
|
Scope resolution
|
Left-to-right
|
2
|
++ --
|
Suffix/postfix increment and
decrement
|
|
()
|
Function call
|
||
[]
|
Array subscripting
|
||
.
|
Element selection by reference
|
||
−>
|
Element selection through pointer
|
||
3
|
++ --
|
Prefix increment and decrement
|
Right-to-left
|
+ −
|
Unary plus and minus
|
||
! ~
|
Logical NOT and bitwise NOT
|
||
(type)
|
Type cast
|
||
*
|
Indirection (dereference)
|
||
&
|
Address-of
|
||
sizeof
|
Size-of
|
||
new, new[]
|
Dynamic memory allocation
|
||
delete, delete[]
|
Dynamic memory deallocation
|
||
4
|
.* ->*
|
Pointer to member
|
Left-to-right
|
5
|
* / %
|
Multiplication, division, and
remainder
|
|
6
|
+ −
|
Addition and subtraction
|
|
7
|
<< >>
|
Bitwise left shift and right shift
|
|
8
|
< <=
|
For relational operators < and
≤ respectively
|
|
> >=
|
For relational operators > and
≥ respectively
|
||
9
|
== !=
|
For relational = and ≠
respectively
|
|
10
|
&
|
Bitwise AND
|
|
11
|
^
|
Bitwise XOR (exclusive or)
|
|
12
|
|
|
Bitwise OR (inclusive or)
|
|
13
|
&&
|
Logical AND
|
|
14
|
||
|
Logical OR
|
|
15
|
?:
|
Ternary conditional
|
Right-to-left
|
=
|
Direct assignment (provided by
default for C++ classes)
|
||
+= −=
|
Assignment by sum and difference
|
||
*= /= %=
|
Assignment by product, quotient,
and remainder
|
||
<<= >>=
|
Assignment by bitwise left shift
and right shift
|
||
&= ^=
|=
|
Assignment by bitwise AND, XOR,
and OR
|
||
16
|
throw
|
Throw operator (for exceptions)
|
|
17
|
,
|
Comma
|
Left-to-right
|
When parsing an expression, an
operator which is listed on some row will be bound tighter (as if by
parentheses) to its arguments than any operator that is listed on a row further
below it.
Operators that are in the same cell
(there may be several rows of operators listed in a cell) are evaluated with
the same precedence, in the given direction. For example, the expression a=b=c
is parsed as a=(b=c), and not as (a=b)=c because of right-to-left
associativity.
An operator's precedence is
unaffected by overloading.
=======================================================================
Manipulators
Manipulators
are functions specifically designed to be used in conjunction with the
insertion (<<) and extraction (>>) operators on stream objects.
Manipulators are used to change formatting
parameters on streams and to insert or extract certain special characters.
Manipulators are usable on both input and output
streams.
Show numerical base prefixes (manipulator function)
Show decimal point (manipulator function)
Show positive signs (manipulator function)
Skip whitespaces (manipulator function)
Generate upper-case letters (manipulator function)
Do not show numerical base prefixes (manipulator function)
Do not show decimal point (manipulator function)
Do not show positive signs (manipulator function)
Do not skip whitespaces (manipulator function)
Do not generate upper case letters (manipulator function)
Use decimal base (manipulator function)
Use hexadecimal base (manipulator function)
Use octal base (manipulator function)
Insert newline and flush (manipulator function)
Set basefield flag (manipulator function)
Set fill character (manipulator function)
Set decimal precision (manipulator function)
Set field width (manipulator function)
Example
1
2 3 4 5 6 7 8 9 10 11 12 13 14 |
// setprecision example
#include <iostream>
#include <iomanip>
using namespace std;
int main () {
double f
=3.14159;
cout <<
setprecision (5) << f << endl;
cout <<
setprecision (9) << f << endl;
cout <<
fixed;
cout <<
setprecision (5) << f << endl;
cout <<
setprecision (9) << f << endl;
return 0;
}
|
The execution of this example displays something similar to:
3.1416
3.14159
3.14159
3.141590000
|
Example
1
2 3 4 5 6 7 8 9 10 |
// setfill example
#include <iostream>
#include <iomanip>
using namespace std;
int main () {
cout <<
setfill ('x') << setw (10);
cout << 77
<< endl;
return 0;
}
|
This code uses setfill to set the fill character to 'x'. The output of this example is something similar to:
xxxxxxxx77
|
Example
1
2 3 4 5 6 7 8 9 10 11 12 |
// modify basefield
#include <iostream>
using namespace std;
int main () {
int n;
n=70;
cout << oct
<< n << endl;
cout << dec
<< n << endl;
cout << hex
<< n << endl;
return 0;
}
|
The execution of this example displays something similar to:
106
70
46
|
Example
1
2 3 4 5 6 7 8 9 10 11 12 13 14 |
// modify showpoint flag
#include <iostream>
using namespace std;
int main () {
double a,
b, pi;
a=30.0;
b=10000.0;
pi=3.1416;
cout.precision
(5);
cout << showpoint << a << '\t'
<< b << '\t' << pi << endl;
cout <<
noshowpoint << a << '\t' << b << '\t' << pi
<< endl;
return 0;
}
|
The execution of this example displays something similar to:
30.000 10000. 3.1416
30 10000 3.1416
|
Example
1
2 3 4 5 6 7 8 9 10 |
// modify uppercase flag
#include <iostream>
using namespace std;
int main () {
cout <<
showbase << hex;
cout <<
uppercase << 77 << endl;
cout <<
nouppercase << 77 << endl;
return 0;
}
|
The execution of this example displays something similar to:
0X4D
0x4d
|
================================================================
=================================================================
========================================================================
The indirection or dereference operator * gives the ``contents of an object pointed to by a pointer''.
To declare a pointer to a variable do:
datatype * identifier;
int *pointer;
In the example, minus is a pointer to a function that has two parameters of type int. It is immediately assigned to point to the function subtraction, all in a single line:
========================================================================
=================================================================
ARRAYS IN C++
Array is a
collection of elements of same type.
An individual element of an array is
identified by its own unique index (or subscript).
The index must be an integer
and indicates the position of the element in the array. Thus the elements of an
array are ordered by the index.
The first element in an array
in C++ always has the index 0, and if the array has
n
elements the last element will
have the index n-1
.
Declaration of Arrays
To declare an
array in C++, the programmer specifies the type of the elements and the number
of elements required by an array (within square brackets) as follows:
type arrayName [ arraySize ];
|
This is called a single-dimension
array. The arraySize must be an integer constant greater than
zero and type can be any valid C++ data type. For example, to declare a
10-element array called balance of type double, use this statement:
double balance[10];
|
For example, data
on the average temperature over the year for each of the last 100
years could be stored in an array declared as follows:
float annual_temp[100];
This declaration
will cause the compiler to allocate space for 100 consecutive float variables
in memory.
C++
can allocate arrays both at compile time and at runtime. A declaration that
allocates an array at compile time, also known as static allocation,
might look like:
int
a[50];
An
array can also be allocated at runtime, also known as dynamic allocation:
int*
b;
...
b =
new int[bLength];
The number of
elements in an array must be fixed at compile time. It is best to make the
array size a constant and then, if required, the program can be changed to
handle a different size of array by changing the value of the constant,
const int NE = 100;
float annual_temp[NE];
then
if more records come to light it is easy to amend the program to cope with more
values by changing the value of NE. This works because the compiler knows the
value of the constant NE at compile time and can allocate an appropriate amount
of space for the array.
Accessing Array Elements
An array element is accessed by writing the identifier of the array followed by the subscript in square brackets. Thus to set the 15th element of the array above to 1.5 the following assignment is used:annual_temp[14] = 1.5;
A value can be
read into an array element directly, using cin
cin >> count[i];
for statements
are the usual means of accessing every element in an array. Here, the first NE
elements of the array annual_temp are given values from the input stream cin.
for (i = 0; i < NE; i++)
cin >> annual_temp[i];
The initial
values are given as a list enclosed in curly brackets. For example initializing
an array to hold the first few prime numbers could be written as follows:
int primes[] = {1, 2, 3, 5, 7, 11,
13};
Note that the
array has not been given a size, the compiler will make it large enough to hold
the number of elements in the list. In this case primes would be allocated
space for seven elements. If the array is given a size then this size must be
greater than or equal to the number of elements in the initialisation list. For
example:
int primes[10] = {1, 2, 3, 5, 7};
would
reserve space for a ten element array but would only initialise the first five
elements.
EXAMPLE:
#include <iostream.h>
int main()
{
double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28};
cout << "2nd member = " << distance[1] << endl;
cout << "5th member = " << distance[4] << endl;
return 0;
}
This
would produce:2nd member = 720.52
5th member = 6.28
EXAMPLE:
#include <iostream>
int main()
{
const int numberOfItems = 5;
double distance[numberOfItems] = {44.14, 720.52, 96.08, 468.78, 6.28};
cout << "Members:\n";
cout << "Distance 1: " << distance[0] << endl;
cout << "Distance 2: " << distance[1] << endl;
cout << "Distance 3: " << distance[2] << endl;
cout << "Distance 4: " << distance[3] << endl;
cout << "Distance 5: " << distance[4] << endl;
return 0;
}
|
#include <iostream>
int main()
{
const int numberOfItems = 5;
double distance[numberOfItems] = {44.14, 720.52, 96.08, 468.78, 6.28};
cout << "Members:\n";
for(int i = 0; i < numberOfItems; ++i)
cout << "Distance " << i + 1 << ": " << distance[i] << endl;
return 0;
}
|
OUTPUT:
In
both cases, this would produce:Members:
Distance 1: 44.14
Distance 2: 720.52
Distance 3: 96.08
Distance 4: 468.78
Distance 5: 6.28
SIZE OF ARRAY:
C/C++ provides the sizeof operator that can be used to get
the dimension of an array. The syntax you would use is:
sizeof(ArrayName) / sizeof(DataType)
EXAMPLE:
#include <iostream.h>
int main()
{
double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28};
// Using the sizeof operator to get the dimension of the array
int index = sizeof(distance) / sizeof(double);
cout << "Array members and their values\n";
// Using a for loop to scan an array
for(int i = 0; i < index; ++i)
cout << "Distance : " << i + 1 << distance[i] << endl;
return 0;
}
OUTPUT:Array members and their values
Distance : 144.14
Distance : 2720.52
Distance : 396.08
Distance : 4468.78
Distance : 56.28
Multi-dimensional arrays
|
C++ supports
multidimensional arrays. The simplest form of the multidimensional array is
the two-dimensional array.
|
Pointer to an array
|
You can
generate a pointer to the first element of an array by simply specifying the
array name, without any index.
|
Passing arrays to
functions
|
You can pass to
the function a pointer to an array by specifying the array's name without an
index.
|
Return array from functions
|
C++ allows a
function to return an array.
|
MULTIDIMENSIONAL ARRAYS:
Multidimensional arrays can be
described as "arrays of arrays".
To access a particular element from
the array we have to use two subscripts on for row number and other for column
number the notation is of the form X [i] [j] where i stands for row subscripts
and j stands for column subscripts.
0
|
1
|
2
|
3
|
|||
|
||||||
1
|
||||||
2
|
int abc [3] [4];
Below given are some typical
two-dimensional array definitions
float table [50] [50];
char line [24] [40];
The first example defines tables as a floating
point array having 50 rows and 50 columns. the number of elements will be 2500
(50 X50).
The second declaration example
establishes an array line of type character with 24 rows and 40 columns. The
number of elements will be (24 X 40) 1920 consider the following two
dimensional array definition int values [3] [4] = {1, 2, 3, 4, 5, 6, 7, 8, 9,
10. 11, 12, };
Values [0] [0] = 1 Values [0] [1] = 2
Values [0] [2] = 3 Values [0] [3] = 4
Values [1] [0] = 5 Values [1] [1] = 6
Values [1] [2] = 7 Values [1] [3] = 8
Values [2] [0] = 9 Values [2] [1] = 10
Values [2] [2] = 11 Values [2] [3] = 12
Alternatively the above definition can
be defined and initialized as
int values [3] [4] = {
{ 1, 2, 3, 4 }
{ 5, 6, 7, 8 }
{ 9, 10, 11, 12 }
};
PROGRAMS
// Example of finding the minimum
member of an array
#include <iostream.h>
int main()
{
//
The members of the array
int
numbers[] = {8, 25, 36, 44, 52, 60, 75, 89};
int
minimum = numbers[0];
int
a = 8;
//
Compare the members
for
(int i = 1; i < a; ++i) {
if
(numbers[i] < minimum)
minimum
= numbers[i];
}
//
Announce the result
cout
<< "The lowest member value of the array is "
<< minimum << "."
<< endl;
return
0;
}
This would produce:
The lowest member value of the array
is 8.
ARRAYS AS STRINGS:
A string is a
sequence of characters.
A string in
C++ is simply an array whose base type is char.
The contents of the string is the
sequence of characters stored in its elements, up to but excluding the first
occurrence of the null character (corresponding to integer value 0). So, the
length of the string must be at least one more than the length of the character
sequence that it stores.
For example:
char myFirstName[6] =
"Henry";
In this case, the elements of
myFirstName are:
myFirstName[0]=’H’;
myFirstName[1] = ’e’;
myFirstName[2] = ’n’;
myFirstName[3] = ’r’;
myFirstName[4] = ’y’;
myFirstName[5] = ’\0’;
Note
that an individual character literal
is delimited by single quotes, while a string literal is delimited by double
quotes.
Some Predefined String Functions:
The library cstring contains a number
of useful functions for string operations.
#include<cstring.h>
·
strcpy(str1,
"You typed: ");
strcpy(str1,
str2);
·
strlen(str)
returns the length of the current string stored in another_string" (the character
"'\0'" is not counted).
·
The comparison
function "strcmp(str1, str2)" returns "False" (i.e. 0) if
its two string arguments are the same.
·
strcat(str1, str2)
concatenates its second argument onto the end of its first argument.
EXAMPLE:
#include
<iostream.h>
#include
<cstring.h>
const
int MAX_LENGTH = 80; //
declare a constant
int
main()
{
char
first_string[MAX_LENGTH];
char
second_string[MAX_LENGTH];
cout
<< "Enter first string: ";
cin.getline(first_string,MAX_LENGTH); // getline() function
cout
<< "Enter second string: ";
cin.getline(second_string,MAX_LENGTH);
cout
<< "Before copying the strings were ";
if
(strcmp(first_string,second_string))
cout
<< "not ";
cout
<< "the same.\n";
strcpy(first_string,second_string);
cout
<< "After copying the strings were ";
if
(strcmp(first_string,second_string))
cout
<< "not ";
cout
<< "the same.\n";
strcat(first_string,second_string);
cout
<< "After concatenating, the first string is: ";
cout
<< first_string;
return
0;
}
OUTPUT:
Enter
first string: Hello class.
Enter
second string: Hello Rob.
Before
copying the strings were not the same.
After
copying the strings were the same.
After
concatenating, the first string is: Hello Rob.Hello Rob.
========================================================================
POINTERS IN C++
A pointer is a
variable which contains the address in memory of another variable.
The
unary
operator & (reference operator) gives the ``address of a variable''. The indirection or dereference operator * gives the ``contents of an object pointed to by a pointer''.
To declare a pointer to a variable do:
datatype * identifier;
int *pointer;
Pointer can only point to variable of
the same data type.
They are mainly used in linked lists
and call by reference functions.
Address operator (&) is used to
get the address of the operand.
For example if variable x is stored at location
100 of memory; &x will return 100.
EXAMPLE:
int a = 5;
int *p;
p = &a; // p contains the
address of a
cout<<*p;
to print to the screen the integer
value stored at the address pointed to by p;.
EXAMPLE:
#include
<iostream.h>
int main ()
{
int firstvalue, secondvalue;
int * ptr;
ptr = &firstvalue;
* ptr = 10;
ptr = &secondvalue;
* ptr = 20;
cout << "first value is "
<< firstvalue << endl;
cout << "second value is "
<< secondvalue << endl;
return 0;
}
OUTPUT:
firstvalue
is 10
secondvalue
is 20
Pointers
to functions
C++ allows operations with pointers to functions. The
typical use of this is for passing a function as an argument to another
function, since these cannot be passed dereference.
In order
to declare a pointer to a function we have to declare it like the prototype of
the function except that the name of the function is
enclosed between parentheses () and an asterisk (*)
is inserted before the name.
// pointer to functions
#include <iostream>
int addition (int
a, int b)
{ return (a+b); }
int subtraction (int
a, int b)
{ return (a-b); }
int operation (int
x, int y, int (*functocall)(int,int))
{
int g;
g =
(*functocall)(x,y);
return (g);
}
int main ()
{
int m,n;
int
(*minus)(int,int) = subtraction;
m = operation (7,
5, addition);
n = operation (20,
m, minus);
cout <<n;
return 0;
}
|
In the example, minus is a pointer to a function that has two parameters of type int. It is immediately assigned to point to the function subtraction, all in a single line:
int (* minus)(int,int)
= subtraction;
|
========================================================================
FUNCTIONS
A function is a block of code that has a name
and it has a property that it is reusable i.e. it can be executed from as many
different points in a C++ Program as required.Function groups a number of program statements into a unit and gives it a name. This unit can be invoked from other parts of a program. A function is a self contained block of statements that perform a task of same kind.
The name of the function is unique in a C++ Program and is Global. It means that a function can be accessed from any location within a C++ Program. We pass information to the function called arguments specified when the function is called. And the function either returns some value to the point it was called from or returns nothing.
Structure
of a Function
There are two
main parts of the function. The function header and the function body.
int
sum(int x, int y) // Function
Header
{
int ans = 0; //holds the answer that will be returned
ans = x + y; //calculate the sum
return ans; //return the answer
}
|
Function
Body
|
Function
Header
In the first
line of the above code
int sum(int x, int y)
It has three
main parts
1.
The
name of the function i.e. sum
2.
The
parameters of the function enclosed in parenthesis
3.
Return
value type i.e. int
Function
Body
Whatever is
written with in { } in the above example is the body of the function.
Function
Prototypes
The
prototype of a function specifies how a function may be used. The prototype of
a function provides the basic information about a function which tells the
compiler that the function is used correctly or not. It contains the same
information as the function header contains. The prototype of the function in
the above example would be like
int sum (int
x, int y);
The only
difference between the header and the prototype is the semicolon ; there must
the a semicolon at the end of the prototype.
Why
Functions Are Used?
Two
reasons
1.
Writing
functions avoids rewriting the same code over and over.
2.
Using functions it becomes easier to write
programs and keep track of what they are doing. If the operation of a program
can be divided into separate activities, and each activity placed in a
different function, then each could be written and checked more or less
independently. Separating the code in to modular functions also makes the
pro-gram easier to design and understand.
Function
Declaration
void
starline ( );
Calling the Function
A function
call consists of the function name followed by the call operator brackets ‘()’,
inside which zero or more comma-separated arguments appear. The number
of arguments should match the number of function parameters.
A Function
call looks like:
starline (
);
Function Definition
The
definition contains the actual code for the function.
void
starline ( )
{
for ( intj=0, j < 45; j++ )
printf("*") ;
printf(‘/n’);
}
Another
Example:
#include
<iostream.h>
int Power
(int base, unsigned int exponent); // function declaration
main (void)
{
int p = Power(2,8); // Function
Calling
cout
<< "2 ^ 8 = " << p << '\n';
}
int Power
(int base, unsigned int exponent)
// Function Definition
{
int result =
1;
for (int i =
0; i < exponent; ++i)
result *=
base; // result = result * base
return
result;
}
There are basically two types of
functions
·
Library
functions Ex. getch ( ), clrscr ( ) etc.
·
User
defined function
Any function by default returns an int value.
Scope of variables
The scope of a variable can be local or global.
The scope of a variable can be local or global.
The scope of variables declared within a function or any
other inner block is only their own function or their own block and cannot be
used outside of them.
Therefore, the scope of local variables is limited to the same block level in which they are declared. However, we can also declare global variables; These are visible from any point of the code, inside and outside all functions. In order to declare global variables you simply have to declare the variable outside any function or block; that means, directly in the body of the program.
Categories:
Ø Functions with no return value and no
argument
Ø Functions with return value and no
argument
Ø Functions with no return value and
arguments
Ø Functions with return value and
arguments
Passing Parameters to a Function
There are
two ways to pass parameters to a function:
- Pass by Value mechanism is used when you don't want to change the value of passed parameters. When parameters are passed by value then functions in C++ create copies of the passed in variables and do required processing on these copied variables.
- Pass by Reference mechanism is used when you want a function to do the changes in passed parameters and reflect those changes back to the calling function. In this case only addresses of the variables are passed to a function so that function can work directly over the addresses.
Pass By Value:
EXAMPLE:
#include
<stdio.h>
/*
function declaration goes here.*/
void
swap( int p1, int p2 );
int
main()
{
int a = 10;
int b = 20;
cout<<”Before: Value of a = “<<a<<”
and value of b =”<<b<<” \n";
swap( a, b );
cout<<”After: Value of a = “<<a<<”
and value of b =”<<b<<” \n";
}
void
swap( int p1, int p2 )
{
int t;
t = p2;
p2 = p1;
p1 = t;
cout<<"Value of a (p1) = “<<p1<<”
and value of b(p2) = “<<p2<<” \n”;
}
OUTPUT:
Before: Value of a = 10 and value of b = 20
Value of a (p1) = 20 and value of b(p2) = 10
After: Value of a = 10 and value of b = 20
|
PASS BY
REFERENCE:
Example:
#include <stdio.h>
/* function declaration goes here.*/
void swap( int *p1, int *p2 );
int main()
{
int a = 10;
int b = 20;
cout<<”Before:
Value of a = “<<a<<” and value of b =”<<b<<” \n";
swap( &a, &b );
cout<<”After: Value of a = “<<a<<”
and value of b =”<<b<<” \n";
}
void swap( int *p1, int *p2 )
{
int t;
t = *p2;
*p2 = *p1;
*p1 = t;
cout<<"Value of a (p1) = “<<*p1<<”
and value of b(p2) = “<<*p2<<” \n”;
}
OUTPUT:
Before: Value of a = 10 and value of b = 20
Value of a (p1) = 20 and value of b(p2) = 10
After: Value of a = 20 and value of b = 10
|
CONSTANTS:
Preceding a
variable definition by the keyword const makes that variable read only (i.e.,
a symbolic constant). A constant must be initialized to some value when it is
defined. For example:
const int
maxSize = 128;
const double
pi = 3.141592654;
Once
defined, the value of a constant cannot be changed:
maxSize =
256; // illegal!
A
constant with no type specifier is assumed to be of type int.
const
maxSize = 128; // maxSize is of type int
A
function parameter may also be declared to be constant. This may be used to indicate that
the function does not change the value of a parameter:
int Power
(const int base, const unsigned int exponent)
{
//...
}
A function
may also return a constant result:
const char*
SystemVersion (void)
{
return
"5.2.1";
}
===========================================================
Default values in parameters.
When
declaring a function we can specify a default value for each of the last
parameters. This value will be used if the corresponding argument is left blank
when calling to the function.
To
do that, we simply have to use the assignment operator and a value for the
arguments in the function declaration.
If
a value for that parameter is not passed when the function is called, the
default value is used, but if a value is specified this default value is
ignored and the passed value is used instead.
For example:
// default values in functions
#include <iostream.h>
int
int
|
|
As we can see in the body of the program there are two calls to function divide. In the first one:
|
|
We have only specified one argument, but the function divide allows up to two. So the function divide has assumed that the second parameter is 2 since that is what we have specified to happen if this parameter was not passed (notice the function declaration, which finishes with int b=2, not just int b). Therefore the result of this function call is 6 (12/2).
In the second call:
|
|
There are two parameters, so the default value for b (int b=2) is ignored and b takes the value passed as argument, that is 4, making the result returned equal to 5 (20/4).
RECURSION
Recursion refers to the application or
use of a repeated function. A function which calls itself is said to be recursive.
Recursion is the process of repeating items in a
self-similar way.
A function is
said to be recursive when they have two
properties:
1.
A terminating condition
and
2.
A repeated procedure
Here, the terminating condition is the
condition to end the recursive loop.
Recursion is used when a function can
be defined in terms of simpler, often smaller versions of itself. The solution
to the problem is then devised by combining the solutions obtained from the
simpler versions of the problem.
The main advantage of recursion is its
simplicity. Recursion
simplifies the software design by dividing the bigger problem into sub problems
of the same type. It works on the technique of divide and conquer.
A recursive
procedure may call itself, or it may call another procedure that, in turn,
calls the first one.
RECURSION |
Example:
// Program
to find the factorial of a number
#include<iostream.h>
long
factorial(int);
int main()
{
int num = 5;
long f;
f =
factorial(num);
cout<<”Factorial of “<< num
<< “ is “<< f;
return 0;
}
long
factorial(int n)
{
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
============================================================
Overloaded
functions:
Function
overloading means having more than one function with the same name but
different number of parameters or different types in the parameters.
In C++, two
different functions can have the same name if their parameter types or number
are different.
For
example:
//
overloaded function
#include
<iostream.h>
int operate
(int a, int b)
{
return (a*b);
}
float operate
(float a, float b)
{
return (a/b);
}
int main ()
{
int x=5,y=2;
float n=5.0,m=2.0;
cout << operate (x,y);
cout << "\n";
cout << operate (n,m);
cout << "\n";
return 0;
}
In this
case, there are two functions with the same name, operate, but one of them
accepts two parameters of type int and the other one accepts them of type float.
The compiler
knows which one to call in each case by examining the types passed as arguments
when the function is called. If it is called with two ints as its arguments it
calls to the function that has two int parameters in its prototype and if it is
called with two floats it will call to the one which has two float parameters
in its prototype.
In the first call to operate the two arguments passed are of type int, therefore, the function with the first prototype is called; This function returns the result of multiplying both parameters. While the second call passes two arguments of type float, so the function with the second prototype is called. This one has a different behavior: it divides one parameter by the other. So the behavior of a call to operate depends on the type of the arguments passed because the function has been overloaded.
Note: A function cannot be overloaded only by its return type. At least one of its parameters must have a different type.
In the first call to operate the two arguments passed are of type int, therefore, the function with the first prototype is called; This function returns the result of multiplying both parameters. While the second call passes two arguments of type float, so the function with the second prototype is called. This one has a different behavior: it divides one parameter by the other. So the behavior of a call to operate depends on the type of the arguments passed because the function has been overloaded.
Note: A function cannot be overloaded only by its return type. At least one of its parameters must have a different type.
No comments:
Post a Comment