DSA Lab 01 - Arrays in C++
DSA Lab 01 - Arrays in C++
Outcomes
● Array data structure in C++
● Static and Dynamic Arrays
1. Introduction
In C++ arrays are used to store such items whose data type is same.
Normally arrays are used to represent lists, trees and graphs; which are types of
data structure. We can perform different operations on arrays such as: inserting an
item, removing an item, finding a value in array, performing mathematical
operations on elements of array etc. If we want to initialize any global or local
array by assigning some values to its element we can do so. We can access value of
an element of array in our program as it was a normal variable. We are allowed to
read and modify the values of these elements.
Static arrays are allocated memory at compile time and their size is fixed, it
means it cannot be changed latter during program execution. If we want to change
the size of array at program execution time, we will need to declare dynamic
arrays. A dynamic array is allocated memory using new operator and is used in the
same way as a static array. Dynamic arrays are accessed using pointers.
1
Sometimes data to be represented is based on more than two dimensions, for
example if we need to represent the sales of some departmental stores by product,
year of sale and location wise, it can be easily represented by a three dimensional
structure, which may be logically represented as a cube. To represent such data we
will use three dimensional arrays.
2. Concept Map
This concept map will help students to understand the main concepts of topic
covered in lab.
Figure 1 represents the logical representation of this array, which shows elements
of the array are located consecutively:
2
Example:
int Numbers [5] = { 16, 2, 77, 40,
12071 }
OR
int Numbers [] = { 16, 2, 77, 40, 12071 };
Figure 2 represents the above initialized array with values.
pointer = new
int;
*pointer = 5;
delete pointer;
Above code will create a pointer variable named “pointer” which is pointing
to a dynamic variable of int type created by new operator. After the creation of
variable a constant value 5 is assigned to this variable using the pointer variable,
because a dynamic variable does not have a name to be referenced. When dynamic
variable is used and is no more required, we can de allocate its memory by using
delete operator. With delete operator we use name of pointer variable which is
pointing to that dynamic variable required to be de allocated.
We may allocate and de allocates memory space dynamically to an array
of integers.
Following example illustrates this
concept.
int size;
cout<< "Enter size of
array: ";cin>> size;
delete [] array;
new and delete operators can be used with a user defined type or class/struct as
well. Assume following is a class definition for which we need to create a
dynamic object.
Class
Rectangle {
private: int
x, y; public:
void set_values
(int,int); int area
() {return (x*y);}
};