C++ Unit3 Chapter1
C++ Unit3 Chapter1
UNIT 3
Arrays:
An array in C or C++ is a collection of items stored at contiguous memory locations and elements can be
accessed randomly using indices of an array. They are used to store similar types of elements as in the
data type must be the same for all elements. They can be used to store the collection of primitive data
types such as int, float, double, char, etc of any particular type. To add to it, an array in C or C++ can
store derived data types such as the structures, pointers, etc.
There are two types of arrays:
One Dimensional Array: A one dimensional array is a collection of same data types. 1-D array is
declared as:
data_type variable_name[size]
Note: The location of the array elements depends upon the data type we use.
// of the array
#include "iostream"
// Driver Code
int main()
// Given array
int arr[] = { 1, 2, 3, 4 };
// Function call
traverseArray(arr, N);
OUTPUT:
1234
MultiDimensional Array: A multidimensional array is also known as array of arrays. Generally, we use
a two-dimensional array. It is also known as the matrix. We use two indices to traverse the rows and
columns of the 2D array. It is declared as:
data_type variable_name[N][M]
// of the 2D array
#include "iostream"
const int N = 2;
const int M = 2;
// Driver Code
int main()
{ // Given array
int arr[][M] = { { 1, 2 }, { 3, 4 } };
// Function call
traverse2DArray(arr, N);
return 0;
OUTPUT
12
34
Strings
C++ string class internally uses character array to store character but all memory management,
allocation, and null termination are handled by string class itself that is why it is easy to use. For example
it is declared as:
// traversal of string
#include "iostream"
// in string
int i = 0;
i++;
// Driver Code
int main()
// Given string
// Function call
traverseString(str);
return 0;
Output:
C++STRINGS
The string data_type in C++ provides various functionality of string manipulation. They are:
// of string manipulation
#include "iostream"
#include "string.h"
// Driver Code
int main()
int x = strlen(str1);
// are equals
if (result == 0) {
else {
strcpy(str1, str2);
return 0;
Output:
POINTERS
Introduction:
Pointers are a powerful concept in C++ and have the following advantages.\
i. It is possible to write efficient programs.
ii. Memory is utilized properly.
iii. Dynamically allocate and de-allocate memory.
Pointer:
A pointer is a variablethat holds amemory address ofanother variable.
The pointer has the following advantages.
o Pointers save memory space.
o Dynamically allocate and de-allocate memory.
o Easy to deal with hardware components.
o Establishes communication between program and data.
o Pointers are used for file handling.
Pointers are used to create complex data structures such as linkedlist, stacks, queues trees and
graphs.
Pointer Declaration:
Pointers are also variables and hence,they must be defined in a program like any other variable.
The general syntax of pointer declaration is given below.
Syntax: Data_Type*Ptr_Variablename;
Where,
o Data_Type is any valid data type supported by C++ or any user defined type.
o Ptr_Variable name is the name of the pointer variable. The presence of ‘*’ indicates that it
is a pointer variable.
Defining pointer variables:
o int *iptr; iptr is declared to be a pointer variable of int type.
o float *fptr; fptr is declared to be a pointer variable of float type.
o char*cptr; cptr is declared to be a pointer variable of character type.
Pointer Initialization:
Once we declare a pointer variable, we must make it to point to something.
We can do this by assigning or initializing to the pointer the address of the variable you want
topoint to as in: iptr = #
The„&’ is the address operator and it represents address of the variable.
Example: A program to display the content of num and the address of the variable num using a
pointer variable.
#include<iostream.h>
void main( )
{
int num; //normal integer variable
int *iptr; //Pointer declaration, pointing to integer data
Pointer Arithmetic:
We can perform arithmetic operations on a pointer just as you can a numeric value.
There are four arithmetic operators that can be used on pointers:
o Increment ++
o Decrement --
o Addition +
o Subtraction -
Example: iptr 1200 9
in tnum,*iptr; 1201
iptr++ 1202
Sushma B | JSSCACS| 2024-25
1203
C++ Programing Language 12
num = 9;
iptr=#
iptr++;
cout<<iptr;
The following operation can be performed on pointers.
o We can add integer value to a pointer.
o We can subtract an integer value from a pointer.
o We can compare two pointers, if they point the elements of the same array.
o We can subtract one pointer from another pointer if both point to the same array.
o We can assign one pointer to another pointer provided both are of same type.
The following operations cannot be performed on pointers.
o Addition of two pointers.
o Subtraction of one pointer from another pointer when they do not point to the same array.
o Multiplication of two pointers.
o Division of two pointers.
A program to illustrate the pointer expression and pointer arithmetic.
#include<iostream.h>
#include<conio.h>
void main( )
{ OUTPUT:
int a, b, x,
Addressofa=65524
y;int*ptr1,*ptr2
; Addressofb=65522 a
a=30; = 30 b=6
b =6; x=30 y=6
ptr1 = &a
a=100 b =12
ptr2 =&b;
x=*ptr1 +*ptr2 – 6;
y=6-*ptr1 / *ptr2 +30;
cout<<”Addressofa=“<<ptr1<<endl;
cout<<”Addressofb=“<<ptr2<<endl;
cout<<”a = “<<a<<”b = “<<b<<endl;
cout<<”x = “<<x<<”y = “<<y<<endl;
nt a[10],i,n;
cout<<”Entertheinputforarray”;
cin>>n;
cout<<”Enterarrayelements:”; OUTPUT:
for(i=0; i<n; i++)
cin>>*(a+i); Entertheinputforarray5 Enter
cout<<Thegivenarrayelementsare:”; for(i=0; array elements
i<n; i++)
1 2 3 4 5
cout<<”\t”<<*(a+i);g
etch( ); Thegiven arrayelementsare:
} 1 2 3 4 5
Array of Pointers:
There is an array of integers;array of float, similarly there can be an array of pointers.
“An array of pointer means that it is a collection of address”.
The general form of array of pointers declaration is:
int*pint[5];
The above statement declares an array of 5 pointers where each of the pointer to integer variable.
Example: Program to illustrate the array of pointers of isolatedvariables.
#include<iostream.h>
#include<conio.h>
void main( )
{
int *pint[5];
OUTPUT:
inta=10, b =20, c=30,d=40, e=50;
pint[0]=&a; Value10storedat17500
pint[1]=&b;
Value20storedat17502
pint[2]=&c;
pint[3]=&d; Value30storedat17504
pint[4]=&e; Value40storedat17506
Value50storedat17508
for(inti=0;i<=4;i++)
cout<<”Value“<<*pint[i]<<“storedat“<<pint[i]<<endl;
}
charstr1[ ] =“HELLO”;
Whena string is declared using an array,the compiler reserves one element longer than the
Number of characters in the string to accommodate NULLcharacter.
The string str1[] is 6 bytes longto initialize its first 5characters HELLO\0.
Method2:
char*str2=“HELLO”;
C++ treats string constants like other array and interrupts a string constant as a pointer to the first
character of the string.
This means that we can assign a string constanto a pointer that point to a char.
Example:A program to illustrate the difference between strings as arrays and pointers.
#include<iostream.h>
#include<conio.h>
void main( )
{
charstr1[]=“HELLO”; OUTPUT:
char *str2 = “HELLO”;
HELLO
cout<<str1<<endl;
cout<<str2<<endl; HELLO
str2++; ELLO
cout<<str2<<endl;
}
int temp;
temp=*m;
*m = *n;
*n =temp;
}
voidswap(&num1, &num2);
voidswap(int&,int&); int
a = 5, b = 6;
cout<<“\nValueofa:”<<a<<“andb:”<<b; swap(a, b);
cout<<“\nAfter swappingvalueofa:”<< a<< “and b:” <<b;
}
voidswap(int&m,int&n)
{
OUTPUT:
int temp;
temp =m; Value of a: 5 and b : 6
m = n; After swapping value of a: 6 and b : 5
n =temp;
}
void main()
{
voidswap(int*m,int*n); int
a = 5, b = 6;
cout<<“\nValueofa:”<<a<<“andb:”<<b; swap(&a, &b);
cout<<“\nAfter swappingvalueofa:”<< a<< “and b:” <<b;
}
These operators allocate memory for objects from a pool called the freestore.
The new operator calls the special function operator new and delete operators call the special
function operator delete.
new operator:
We can allocate storage for a variable while program is running by using new operator.
It is used to allocate memory without having to define variables and then make pointers point to
them.
The following code demonstrate show to allocate memory for different variables.
To allocate memory type integer
int *pnumber;
pnumber=newint;
The first line declares the pointer, pnumber. The second line then allocates memoryfor an integer
and then makes pnumber point to this new memory.
To allocate memory for array, double*dptr=newdouble[25];
To allocates dynamic structure variables orobjects, student sp =new student;
Delete Operator:
The delete operator is used to destroy the variables space which has been created by using the
new operator dynamically.
Use delete operator to free dynamic memoryas : delete iptr;
To free dynami carray memory: delete[]dptr;
To free dynamic structure, delete structure;
Freestore (Heapmemory):
Free store is a pool of memory available to allocated and de-allocated storage for the objects
during the execution of the memory.
MemoryLeak:
If the objects, that are allocated memory dynamically, are not deleted using delete, the
memoryblock remains occupied even at the end of the program.
Such memoryblocksare known as orphaned memoryblocks.
These orphaned memory blocks when increases in number, bring adverse effect on the system.
This situation is called memory leak.