0% found this document useful (0 votes)
63 views92 pages

Chapter - 3

C++ is a middle-level programming language developed in 1980 at Bell Labs. It was designed to support C features like efficiency and low-level system coding while also including object-oriented features like classes and inheritance. To use C++, a text editor and compiler are needed. A simple "Hello World" program is presented that outputs text using cout. The document then discusses C++ data types, variables, constants, operators, and keywords.

Uploaded by

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

Chapter - 3

C++ is a middle-level programming language developed in 1980 at Bell Labs. It was designed to support C features like efficiency and low-level system coding while also including object-oriented features like classes and inheritance. To use C++, a text editor and compiler are needed. A simple "Hello World" program is presented that outputs text using cout. The document then discusses C++ data types, variables, constants, operators, and keywords.

Uploaded by

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

CHAPTER - 3

INTRODUCTION TO C++
INTRODUCTION TO C++
• C++ is a middle-level programming language developed by
Bjarne Stroustrup starting in 1980 at Bell Labs.
• It was designed to support the features of C such as efficiency
and low-level support for system level coding.
• Some additional features such as classes with Inheritance,
Virtual functions, Operator overloading.
• C++ is superset of C with full support for object oriented
programming.
• C++ programs are fast and efficient which makes this language
as popular programming language.
C++ Get Started
• To start using C++, you need two things:
• A text editor, like Notepad, to write C++ code
• A compiler, like GCC, to translate the C++ code into a language that
the computer will understand.
• There are many text editors and compilers to choose from.
• Turbo C++ and Borland C++ provide an integrated program
development environment (IDE) under MS-DOS.
• They provide a built-in editor and a menu bar, which includes options
such as file, edit, compile and run.
• We can create and save the source files under the file option and
edit them under the edit option.
• C++ programs are saved using file extension .cpp
Write a simple C++ program
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
cout<<“Hello World ”;
getch();
}

Output: Hello World


Data types in C++
Data types in C++
Name Bytes Description
char 1 Stores a single character/letter/number, or ASCII values.
short 2 16 bits integer
long 4 32 bits integer
int 2 Stores whole numbers, without decimals
float 4 Stores fractional numbers, containing one or more
decimals. Sufficient for storing 7 decimal digits
double 8 Stores fractional numbers, containing one or more
decimals. Sufficient for storing 15 decimal digits
boolean 1 Stores true or false values
Variables in C++
• Variables are containers for storing data values.
• Variables can be declare any where before the are used
• In C++, there are different types of variables (defined
with different keywords), for example:
Variables in C++
• Syntax: data_type var1;
Example: int a;

• They are optionally initialized by the assignment 0 literal value


data_type variable = value;
Example: float a = 1.0;
• A valid variable of the name may consists of alphabet, digits,
underscore, but it can’t start with a digit.
Example: int 75av ; not valid
float f = 14.2 69 ; not valid
Variables in C++
• In C++ uppercase and lowercase variables are treated as different
variables.
• Variables have 2 types of scope:
1. If it is declare outside function then they have global scope i.e. it
can be referenced from anywhere in the program.
2. If it is declare inside the function then they have local scope i.e. it
can be referenced only within that function.
COMPILER TOKENS
• A token is the smallest element of a C++ program that is
meaningful to the compiler.
COMPILER TOKENS
C++ Keywords
• A keyword is a reserved word. You cannot use it as a variable
name, constant name etc. A list of 32 Keywords in C++
Language which are also available in C language are given
below.
C++ Identifiers
• A C++ identifier is a name used to identify a variable, function,
class, module, or any other user-defined item.
• An identifier starts with a letter A to Z or a to z or an underscore
(_) followed by zero or more letters, underscores, and digits (0
to 9).
• C++ does not allow punctuation characters such as @, $, and
% within identifiers.
• C++ is a case-sensitive programming language.
Thus, Apple and apple are two different identifiers in C++.
CONSTANTS
• Constants refer to fixed values that the program may not alter
and they are called literals.
• They are declare with const keyword.
• Constants can be of any of the basic data types and can be
divided into Integer Numerals, Floating-Point Numerals,
Characters, Strings and Boolean Values.
• Constants are treated just like regular variables except that their
values cannot be modified after their definition.
Syntax : const data_type const_name = value;
Example : const float pi = 3.14;
TYPES OF CONSTANTS
1. Numeric Constants:
They are further divided into:
a) Integer Constant:
It is declare with const keyword and has fixed integer value.
Example : const int a = 5;

b) Character Constant:
It is declare with const keyword and has fixed character value.
Example : const char a = ‘\t’;
When C++ compiler encounters character constant, that translates it into
corresponding ASCII value and stores that number.
TYPES OF CONSTANTS
• Character escape sequence
There are certain characters in C++ when they are preceded by a
backslash they will have special meaning and they are used to
represent like newline (\n) or tab (\t).
Backslash Character Meaning
\a (alert) Produces an available or visible signal.
\b (backslash) Moved the cursor bar one space.
\f (Form feed) Moves ….. To the next page.
\n (new line) Prints a new line.
\r (Carriage return) Prints a Carriage return.
\t (horizontal tab) Prints a horizontal tab space.
\v (vertical tab) Prints a vertical tab space.
TYPES OF CONSTANTS
c) Floating point constant:
Floating point constants are also called as real constant.
It has an integer part, a decimal point, a fractional part, and an
exponent part.
Example : const float pi = 3.14;
d) String Constant:
String constants are enclosed in double quotes. It has sequence
of 2 or more characters. This can be also defined as an array of
character constants.
Example : const char arr[4] = “abcd”;
TYPES OF CONSTANTS
e) Hexadecimal and octal constants:
We use decimal constants having base 10. Numbers can be also
specified using base 8 and 16.
Numbers represented using base 8 Octal number systems (uses 0 – 7
digits) while having base 16 Hexadecimal number system (uses 0 – 9
and letters A to F).
The octal number begins with letter 0 and hexadecimal number begins
with 0x.
Example : 0xAB is Hexadecimal number.
0123 is Octal number.
TYPES OF CONSTANTS
2. Defined Constants:
• There are two simple ways in C++ to define constants −
• Using #define preprocessor.
• Using const keyword.
#define Directive( PREPROCESSOR directive)
It causes macro or symbolic name to be defined as a macro i.e. it sets
up an equivalence between identifier and text phares.
Syntax: #define macro_name replacement_list
#define identifires text_pharse
Example: #define PI 3.14159
TYPES OF CONSTANTS
3. Symbolic Constants:-- Enumerations
Along with pre-defined datatypes C++ allows you to define your own
datatypes. The one way of this to use enumeration.
Enumeration of symbolic constant is introduced by an enum declaration,
which is useful for declaring a set of closely related constants.
Syntax : enum TypeName {enumeration –list};
Example: enum { north, south, east, west}
OPERATORS IN C++
• An operator is a symbol that tells the compiler to perform
specific mathematical or logical manipulations.
• C++ is rich in built-in operators. They are classified as unary
operators, working on single operand and binary operators,
working on 2 operands.
• Although C++ allows us to multiple meanings to the operators,
yet their association and precedence remain same. Eg. (*)
multiplication operator is having high precedence than (+) add
operator.
OPERATORS IN C++
1. Arithmetic Operators
• Arithmetic operators are used to perform common mathematical
operations.
• An arithmetic expression is made up of constants, variables, a combination
if both or a function call, connected by arithmetic operators. Following are
the subtypes.
a. Unary Arithmetic Operators
Needs only one operand.
Example : +a, -b uses unary operators namely + (positive) and – (negative).
b. Ternary Arithmetic operators
Needs 3 operands. This is one of the special features of C++ language.
OPERATORS IN C++
c. Binary Arithmetic Operators
Needs 2 operands
OPERATORS IN C++
2) Increment and decrement operators

• C++ provides special operators ++ and --.


• These operators are unary i.e. working on a single operand.
• The incrementing and decrementing can be of 2 types:
a. Prefix: first increment/decrement the value of variable and then take this
new value for processing. E.g. ++a, --b.
b. Postfix: first take the value of the increment/decrement the variable.
E.g. a++, b--.
OPERATORS IN C++
3) Relational Operators:
• This are used to test the relation between 2 values.
• A relational expression is made up of 2 arithmetic expression connected by a
relational operator. It writes 0 when relation is false while 1 when it is true.
OPERATORS IN C++
4. Logical operators (Boolean operators):
• They combine the results of one or more expression and the output
expression is called as logical expression.
• After testing conditions, they return logical values as true or false.
• They may be unary or binary operators and operands may be
constants, variables or expression.
• The operands may be integers/floating point numbers.
OPERATORS IN C++
OPERATORS IN C++
5. Conditional operator (?:)
• It is ternary operator that takes 3 arguments.
• The value at an expression using conditional operator is the value of either
2nd or 3rd operand, depending on the value of the first operand.
• It is same as if….. Else statement.

Operator Symbol Form Result


Conditional ?: a?b:c If a is nonzero result is b otherwise result is c.

• In this , the first operand is the test condition while 2nd and 3rd represents
final value.
OPERATORS IN C++
6. Assignment operator (=)
• Assignment operators are used to assign values to
variables.
• = operator causes the value of the right hand operand to be assigned
to the left hand operand.
• The left hand operand, is also called as Ivalue, must always refers to a
memory location.
• Example : int x = 10;
int x = y = z = 5;
7. Shorthand (Compound) operators:
C++ supports additional assignment operators combining assignment
with each of the arithmetic operations.
Operator Symbol Description Form Operation

Add- += Add AND assignment operator, It adds right operand to C += A equivalent to C = C + A


assign the left operand and assign the result to left operand.
Subtract – -= Subtract AND assignment operator, It subtracts right C-=A equivalent to C = C - A
assign operand from the left operand and assign the result to
left operand.
Multiply- *= Multiply AND assignment operator, It multiplies right C*=A equivalent to C = C * A
assign operand with the left operand and assign the result to
left operand.
Divide- /= Divide AND assignment operator, It divides left operand C/=A equivalent to C = C / A
assign with the right operand and assign the result to left
operand
Remainde %= Modulus AND assignment operator, It takes modulus C%=A equivalent to C = C % A
r – assign using two operands and assign the result to left
operand.
OPERATORS IN C++
8. Bitwise Operators :
Bitwise operator works on bits and perform bit-by-bit operation.
They are used to manipulate or modify the individual bits of the piece of data.

Operator Description Form

& Bitwise AND Operator a&b

| Bitwise OR Operator a|b

^ Bitwise XOR Operator a^b

~ Bitwise Complement Operator ~a

a << b
<< Bitwise Shift Left Operator

a >> b
>> Bitwise Shift Right Operator
OPERATORS IN C++
a. one’s complement
In this number is complemented means all the 1’s are replaced by 0’s and vice
versa.
Eg. 1010 1’s complement is 0101

b. Shift Right Operator


Binary Right Shift Operator. The left operands value is moved right by the
number of bits specified by the right operand.
Eg. X is 10110010 then X>>2 gives 00101100
c. Shift Left Operator
Binary Left Shift Operator. The left operands value is moved left by the
number of bits specified by the right operand.
Eg. X is 10110010 then X<<1gives 01100100
OPERATORS IN C++
d. Bitwise AND operators
It works on 2 operands and both should be of same data type.
The purpose of AND (&) is to clear given bit.

e. Bitwise OR operators
Binary OR (|) Operator copies a bit if it exists in either operand.

f. Bitwise XOR operators


Binary XOR(^) Operator copies the bit if it is set in one operand but
not both.
OPERATORS IN C++
p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100 11000011
B = 0000 1101 11110010
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
OPERATORS IN C++
9. Operators dealing with streams:
C++ is able to input and output the built-in data types using the stream
extraction operator >> and the stream insertion operator <<.
Dealing with input output is called as iostream.
a. Insertion operator (<<)
It is a put to operator. The operators dealing with output stream is called insertion
operator.
Eg. cout<<a;
a. Extraction operator (>>)
It is a get from operator. It extracts the value from standard input device and assign
variable at its right. It is related to input stream.
Eg. cin>>a;
OPERATORS IN C++
10. Comma operator
The purpose of comma operator is to string together several expressions. The value of a
comma-separated list of expressions is the value of the right-most expression. Essentially,
the comma's effect is to cause a sequence of operations to be performed.
• The values of the other expressions will be discarded. This means that the expression on
the right side will become the value of the entire comma-separated expression. For
example −
var = (count = 19, incr = 10, count+1);

• Here first assigns count the value 19, assigns incr the value 10, then adds 1 to count, and
finally, assigns var the value of the rightmost expression, count+1, which is 20. The
parentheses are necessary because the comma operator has a lower precedence than
the assignment operator.
OPERATORS IN C++
11. The sizeof operator
• The sizeof is a keyword, but it is a compile-time operator that
determines the size, in bytes, of a variable or data type.
• The sizeof operator can be used to get the size of classes,
structures, unions and any other user defined data type.
• The syntax of using sizeof is as follows −
sizeof(data_type)
• Where data type is the desired data type including classes,
structures, unions and any other user defined data type.
• The outcome is totally depended on machine.
OPERATORS IN C++
12. Scope resolution operator
• The scope resolution operator is used for several reasons. For
example: If the global variable name is same as local variable
name, the scope resolution operator will be used to call the
global variable. It is also used to define a function outside the
class and used to access the static variables of class.
OPERATORS IN C++
13. Type cast operator
• 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.
• Syntax : type_name(expression)
eg. Avg= sum/float(i);
• A value in any built-in types can convert to any of other types.
• Example: (int)3.14 //converts 3.14 to an int to give 3.
(double)2 //converts 2 to double to give 2.0
OPERATORS IN C++
14. Stream manipulation operator
• Manipulators are helping functions that can modify the input/output stream. It
does not mean that we change the value of a variable, it only modifies the I/O
stream using insertion (<<) and extraction (>>) operators. The most important
manipulators defined by the IOStream library

dec Sets the base 10 integer.


endl This manipulator has the same functionality as ‘\n’(newline character). But this also
flushes the output stream.
ends Sends null character.
flush It is also defined in iostream and it flushes the output stream, i.e. it forces all the output
written on the screen or in the file. Without flush, the output would be the same, but
may not appear in real-time.
setw(int) Sets field width.
COMMENTS IN C++
• Comments are important part of any program even though they are
not mandatory to be given.
• Program comments are explanatory statements that you can
include in the C++ code. These comments help anyone reading
the source code. All programming languages allow for some
form of comments.
• C++ supports single-line and multi-line comments. All
characters available inside any comment are ignored by C++
compiler.
• They are written as // or /* */
• Single-line comments start with two forward slashes (//).
Any text between // and the end of the line is ignored by the
compiler (will not be executed).
Example
// This is a comment
cout << "Hello World!";

• Multi-line comments start with /* and ends with */.


Any text between /* and */ will be ignored by the compiler:
Example
/* The code below will print the words Hello World!
to the screen, and it is amazing */
cout << "Hello World!";
SCOPE AND VISIBILITY
• The scope or visibility of a variable determine where it can be
accessed from other functions in the same source file or in other files.
• The position of an identifier within a block is also called a factor in
determining scope.
Static Variables: Internal Static variables are defined as those having
static variables which are declared inside a function and extends up to
the end of the particular function.
External Variables: External Static variables are those which are
declared outside a function and set globally for the entire file/program.
SCOPE AND VISIBILITY
SCOPE AND VISIBILITY
• The example above , moreover than the function main() another
function existed, the local variables declared in main could not be in
the other function and vice versa.
• In C++, the scope of a local variable is give by the block in which it is
declared (a block is a group of instructions grouped together within
curly brackets {} signs). If it is declared within a function it will be a
variable with function scope, if it is declared in a loop its scope will be
only loop, etc…
• In addition to local and global scopes exists the external scope, that
causes variable to v visible not only in the same source file bit in all
other files which will be linked together with.
CONTROL STATEMENTS
• Control statements, are ways for programmer to control what pieces
of the program are to be executed at certain times.
• There are two types of control statements:
BRANCHING STATEMENTS
1. if – else statement
BRANCHING STATEMENTS
• Syntax:
if (condition)
{
Statement 1; //Code to be executed if condition is true
}
else
{
Statement 2; //Code to be executed if condition is false
}
BRANCHING STATEMENTS
2. Compound Conditions in if(multiple if’s)
BRANCHING STATEMENTS
• Nested selection statements (nested if else)
BRANCHING STATEMENTS
• Syntax:-
if(test-condition 1)
{
if(test-condition 2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
statement-x;
BRANCHING STATEMENTS
• Replacing if…. else by conditional operator(? :)
BRANCHING STATEMENTS
• else-if ladder
BRANCHING STATEMENTS
SWITCH STATEMENT
• A switch statement is used in place of many if statements.
• The switch statement allows a programmer to compound a group of if
statements(else-if ladder),provided that the condition being tested is an integral
constant.
• It is also called as multiple branch selection statement.
• Syntax:
switch(expression)
{
case x: // code block
break;
case y: // code block
break;
default: // code block
}
SWITCH STATEMENT
This is how it works:
•The switch expression is evaluated once
•The value of the expression is compared with the values of each case
•If there is a match, the associated block of code is executed
•The break and default keywords are optional

The break Keyword


• When C++ reaches a break keyword, it breaks out of the switch block.
• This will stop the execution of more code and case testing inside the block.
• When a match is found, and the job is done, it's time for a break. There is no need
for more testing.
• A break can save a lot of execution time because it "ignores" the execution of all the
rest of the code in the switch block.
UNCONDITIONAL CONTROL STRUCTURE (goto)
• The goto statement is a jump statement which is sometimes also
referred to as unconditional jump statement. The goto statement can
be used to jump from anywhere to anywhere within a function.
UNCONDITIONAL CONTROL STRUCTURE (goto)
• In the above syntax, the first line tells the compiler to go to or jump to
the statement marked as a label.
• Here label is a user-defined identifier which indicates the target
statement.
• The statement immediately followed after ‘label:’ is the destination
statement.
• The ‘label:’ can also appear before the ‘goto label;’ statement in the
above syntax.
ITERATIVE CONTROL STRUCTURES (LOOPS)
• Loops can execute a block of code as long as a specified condition is
reached.
• Loops are handy because they save time, reduce errors, and they
make code more readable.
ITERATIVE CONTROL STRUCTURES (LOOPS)
1. for statement
• When you know exactly how many times you want to loop through a block
of code, use the for loop.
• Syntax
for (statement 1; statement 2; statement 3)
{
// code block to be executed
}

• Statement 1 is executed (one time) before the execution of the code block.
• Statement 2 defines the condition for executing the code block.
• Statement 3 is executed (every time) after the code block has been executed.
ITERATIVE CONTROL STRUCTURES (LOOPS)
2. Nested for loop
• A loop can be nested inside of another loop.
Syntax
ITERATIVE CONTROL STRUCTURES (LOOPS)
3. While statement
The while loop loops through a block of code as long as a specified
condition is true.
Syntax
while (condition)
{
// code block to be executed
}
ITERATIVE CONTROL STRUCTURES (LOOPS)
4. do…. While statement
The do/while loop is a variant of the while loop. This loop will execute
the code block once, before checking if the condition is true, then it will
repeat the loop as long as the condition is true.
Syntax
do {
// code block to be executed
}
while (condition);
USE OF break and continue
• You have already seen the break statement used in switch case.
• It was used to "jump out" of a switch statement. The break
statement can also be used to jump out of a loop.
• The continue statement breaks one iteration (in the loop), if a
specified condition occurs, and continues with the next iteration in
the loop.
• Exit Success is indicated by exit(0) statement which means successful
termination of the program, i.e. program has been executed without
any error or interrupt.
Functions in C++
• A function is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a function.
• Functions are used to perform certain actions, and they are important
for reusing code: Define the code once, and use it many times.
• This divides the complexity of one program into sub programs, which
are easy to wite and debug.
• Standard C++ library is a collection of pre-defined functions called as
library or built in functions, which are access through header file.
• While users can also define his/her own functions called as user
defined functions.
Functions in C++

• myFunction() is the name of the function


• void means that the function does not have a return value.
• inside the function (the body), add code that defines what the function should do
Functions in C++
Call a Function
• Declared functions are not executed immediately. They are "saved for
later use", and will be executed later, when they are called.
• To call a function, write the function's name followed by two
parentheses () and a semicolon ;
• Eg: myFunction();
Default arguments
• Functions taking values are called as arguments or parameters.
• They are mandatory to be given.
• When programmer initializes value while specifying arguments, it is
said that functions take default arguments.
• They even can be specified in the prototype.
Techniques used to pass variables into C++
Functions
1. Pass by value
2. Pass by reference with the pointer
3. Pass by reference using a reference
Pass by value
• the function receives a copy of the variable. This local copy has scope, that is,
exist only within the function.
• Any changes to the variable made in the function are not passed back to the
calling routine.
• The advantage of passing by values are simplicity and that is guaranteed that
the variable in the calling routine will be unchanged after returned from the
function.
• There are two main disadvantages.
1. It is insufficient to make a copy of a variable, particularly if it is large such as
an array, structure our class.
2. Since the variable in the calling routine will not be modified even if that's
what is desired, only way to pass information back to the calling routine is via
return value of the function. only one value may be passed back this way.
Pass by reference with pointer
• A pointer to the variable is passed to the function.
• The pointer can then be manipulated to change the value of the
variable in the calling routine.
• The function cannot change the pointer itself it gets local copy of
the pointer.
• However, the function change the contents of memory, the variable,
which the pointer refers.
• Advantage of passing by reference are that any changes to the
variable will be passed back to the calling routine and that multiple
variables can be changed
Pass by reference using a reference
• A reference in C++ is an alias to a variable.
• Any changes made to the reference will also be made to the original
variable.
• When variables are passed into a function by a reference, the modification
made by the function will be seen in calling routine.
• Since no local copies variable are made in the function, this technique is
efficient. additionally, passing multiple references into the function modify
multiple variables.
Function overloading

• Overloading is one of the features of Object-oriented language.


• C++ allows you to specify more than one definition for a function name or
an operator in the same scope, which is called function
overloading and operator overloading respectively.
• Function overloading is a feature in C++ where two or more functions can
have the same name but different parameters.
• When a function name is overloaded with different jobs it is called Function
Overloading.
• In Function Overloading “Function” name should be the same and the
arguments should be different.
• Function overloading can be considered as an example of polymorphism
feature in C++.
Inline function

• C++ inline function is powerful concept that is commonly used with classes. If a function is
inline, the compiler places a copy of the code of that function at each point where the
function is called at compile time.

• Like a #define macro, inline functions improve the performance by avoiding the overhead of
the call thus inline functions are new design approach to speed up the program execution.

• They save memory space, as the calls to the same code needed not to be duplicate in
memory. when you declare an inline function, it looks just like a normal function:

void function(int a, int b)


Inline function

• But when you define an inline function, you prepared the functions definition with the
keyword inline, and you put the definition into the header file:
inline void function(int a, int b)
{
// function code.......
}

• But note that overuse of inline function should be avoided since it can cause the size of code
getting larger and that might cause the operating system to trash, i.e. use of inline function
can cause the negative side effect also, like it can limit the portability of your code across the
platform
Recursion
• When function is called within the same function, it is known as recursion in C++.
The function which calls the same function, is known as recursive function.

• A function that calls itself, and doesn't perform any task after function call, is
known as tail recursion. In tail recursion, we generally call the same function with
return statement.

• Recursion is also called as circular definition.

• *Note that all the functions can’t be made recursive.


Tracing of factorial program
Arrays in c++
• an array consists of set of objects( call its elements), all of which are of
the same type and arrange contiguously in memory.
• Each element is identified by an index, which denotes the position of
the element in the array.
• The number of elements in an array is called as its dimension.
• The dimension of an array is a fixed and predetermined; it cannot be
changed during the program execution.
• Arrays are declared with the number of storage location indicated, but
array elements start at 0.
Arrays in c++
• Arrays are suitable for representing composite data, which consists of
many similar, individual items. example include: list of names, tables of
students roll number, or the monthly transaction of bank account.
• Note that data types of all the elements in the array is same.
• An array that is Defined by specifying its dimension and the type of its
element.
example: int num[1];
• Indexing the error access is the individual elements of the array. the first
array element always has the index 0. attempting to access non existent
array element lead to serious runtime error( called' index out of bound
error')
Array of characters(string)
• A C + + string is a simply an array of characters( string literal).
Example: char str[]="HELLO";
• Defines str an array of 6 characters: 5 letters an anal character. the compiler inserts the
terminating null character.
• Alternately it can be also defined as
char str[] ={'H', 'e', 'l', 'l', 'o', '\0’};
• Following is the memory presentation of above defined string in C++

• Actually, you do not place the null character at the end of a string constant. The C++
compiler automatically places the '\0' at the end of the string when it initializes the array.
Array of characters(string)
• A string literal is a sequence of characters enclosed within the double
quotes. A storage class of a string literal is static.
• The compiler initialise the memory occupied by a string literal with the
specified character sequence.
• A null Terminator ( denotes the end of the string) is also included. The
size of the string literal is the number of characters enclosed within the
double quotes plus one for the null Terminator.
• It is easy to calculate the dimension of an array using the sizeof operator.
for example: given an array arr
• So the dimension of arr is: sizeof(arr)/sizeof(datatype)
string processing functions
• There were number of string processing functions provided as a
part of standard library declare in the header file ' string.h’
• C++ supports a wide range of functions that manipulate null-
terminated strings. These are:
1. strcpy(str1, str2): Copies string str2 into string str1.
2. strcat(str1, str2): Concatenates string str2 onto the end of string
str1.
3. strlen(str1): Returns the length of string str1.
4. strcmp(str1, str2): Returns 0 if str1 and str2 are the same; less than
0 if str1<str2; greater than 0 if str1>str2.
Passing array to the function

• Array can be passed to the function as a parameter.

• When array is passed to the function, in the call to the function, we


provide the name of the array, which is nothing but the address of
the first element in array, the function uses this address to access
the array contents. the size of the array can be also specified
Multidimensional array
• An array of arrays is referred as a multidimensional array.
• An array may have more than one dimensions (i.e. two, three or higher). the
organisation of the array in the memory is still the same (a contiguous
subsequence of elements), but the programmers perceived organisation of the
element is different.
• example: int twoD[3][2]={{1,2},{3,4},{5,6}};
• The above declared is 2-D are that is viewed as a one dimensional array of one
dimensional array.
POINTRS IN C++

• A pointer is a variable whose value is the address of another variable. Like any variable or
constant, you must declare a pointer before you can work with it. A pointer variable is defined
to ‘point to’ data of specific type. The general form of a pointer variable declaration is −
type *var;
• Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name
of the pointer variable.
eg. int *a; //pointer to an int
char *b; //pointer to char
• The value of a pointer variable is the address to which it points(i.e. address of the memory
location where the variable is stored)
eg. Int variable1;
a=&variable1;
POINTRS IN C++
• The symbol & is the address operator; it takes a variable as a argument
and return the memory address of that variable.
• The effect of the above assignment is that the address of the variable1 is
assigned to ptr1. therefore, we say that ptr1 points to value of variable1.

ptr1 variable1
• Given that ptr1 points to variable 1.
• *ptr1 dereferences ptr1 to get to what it points to, is therefore
equivalent to variable1.
• The symbol * is the dereference operator; it takes a pointer as
argument and returns the content of the location to which it points.
POINTRS IN C++
• In general, the type of pointer must the type of the data it is set to point to.

• A pointer may be cast to another type

for example ptr2= (char*)ptr1;

• Converts ptr1 two character pointer before assigning it to ptr2.

• Regardless of its type, pointer may be assigned the value 0( called as the null
pointer).
reference variable in C++
• Reference variable in C++ allows two variable names to address the same memory
location.
• Reference does not create a copy of a variable, but merely a symbolic alias for it.
• A reference must always be initialised when it is defined: it should be an alias for
something. It will be illegal to define a reference and initialize it later
double &var1; // illegal: reference without an initializer
var1=num2;
• You can also initialise a reference to a constant. in this case a copy of a constant is
made ( after any necessary type conversion) and the reference is set to refer to the
copy.
int &n=1; // n refers to a copy of 1
• The most common use of reference is for function parameters. reference
parameters facility at the pass- by- reference style of arguments, as opposed to
the pass -by -Value style
Arrays and pointers
• Arrays and pointers are very closely related C++ compiler interprets
the name of the array as an address of the 1st element.
• You can reverse the whole array with the help of pointers.
• Once pointer is initialized to the starting address of the array, it works
like an index of the array.
Dynamic allocation
• C++ provides the way to allocate memory dynamically at run time by
2 memory management operators namely, new and delete.
• The new operator returns a pointer to allocated memory.
• Syntax: ptr_var= new datatype(initializer);
• You can initialize the allocated memory to some known value by using
an initializer.
• The delete operator frees memory.
• Warning : In C++ it is possible to access and modify the unallocated
memory locations, but it should be avoided.
Functions, returning the reference
• A function may return a reference.
• A function’s return type may be a reference provided that the value
returned is a lvalue, which is not local to the function, which gives us
a facility for treating functions as lvalue on left side of the assignment
of operator.
Thank you

You might also like