Arrays - DSA #02

What is an Array?

An array is just a collection of variables stored at contiguous locations in the memory. 

Explanation:
It is the simplest data structure in which we store data as a collection in memory and then the data can be read from anywhere in the collection using indexes.
Where the indexes are simply offsets to the base value or the memory location of first item. 
 

 
 As we can see in the image above showing how arrays are stored in the memory. All the items of an array has an incrementing index value that is used as reference.
 
Basic Terminologies of Array:
  • Array Index: The array index is the reference used to access values stored in the array. Every item in an array has a unique index attached to it. While some languages allow arrays with non-numeric indexes also referred as keys, In C++ the array index is only numeric, starting from 0.
  • Array Element: An array element is a value stored in an array. So by this definition, an array is a collection of array elements with each element having unique index.
  • Array Length: The array length or size of an array simply represents the number of elements in an array.
Creating Array:
// declaration
int foo[5];
// initialization
int bar[3] = {25,58,14};
 
Accessing Array Elements:
// accessing array elements
int foo[3] = {34,68,94};
std::cout << foo[2]; // outputs 94

Getting Array Size:
// getting integer array size
int foo[3] = {25,58,14};
std::cout << sizeof(foo) / 4; // outputs 3
As you can see we used a C++'s built-in unary operator sizeof desgined to calculate the size of an array. You are probably wondering why did we divide the output of sizeof operator with 4. The reason is because sizeof operator returns the size in bytes so we have to divide it by 4 because integer is usually 4 bytes long.

A much simpler example would be using a char array instead of integer. Each character only takes one byte so we don't need to divide by any value.
// getting character array size
char foo[5] = {'a','s','d','f','g'};
std::cout << sizeof(foo); // outputs 5







 
 
 
Arrays - DSA #02 Arrays - DSA #02 Reviewed by Tayyab Mughal on September 02, 2023 Rating: 5

No comments:

Thanks For Your Comment!

Powered by Blogger.