Arrays in C++
- ADVANTAGES AND DISADVANTAGES
- PROPERTIES OF AN ARRAY
- TYPES OF ARRAYS
- RELATIONSHIP BETWEEN ARRAY AND POINTERS IN C++
- ARRAYS OF STRING IN C++
In C++,
std::array is a container that encapsulates fixed-size arrays. In C++, the
array index starts at zero. A C++ array can only store a fixed set of elements.
A
collection of related data items stored in contiguous memory locations is
called an array in C/C++ or some other programming language. The elements of an
array can be accessed arbitrarily using its indexes. They can be used to store
collections of any primitive data type, including int, float, double, char,
etc. A C/C++ array can also store derived data types such as structures,
pointers, and other data types that are aggregates.
To
understand of array and its memory allocation let’s try to understand as given
below
Elements |
10 |
20 |
30 |
40 |
50 |
Index value |
0 |
1 |
2 |
3 |
4 |
Here we
created an array of 5 and the value is showing up to 4 only because it starts
allocating the memory from position 0 and ends as per allocated by the user.
Advantages
of array
- Random Access
- Easy to traverse data
- Easy to manipulate data
- Code optimization
- Easy to sort data
Disadvantages of array
There are no mere or many disadvantages of the array but it only stops up to a fixed size.
Properties of an array
· An array is a data structure or collection of data, it stores a similar type of data in a contiguous memory location.
·
Table
indexing starts from scratch. This means that the first element is stored at
the 0th index, and the second at the 1st index. index and so on.
·
Array
elements are accessed by their indexes.
·
Once
an array is declared, its size remains unchanged throughout the program.
·
A
table can have multiple dimensions.
·
The
number of elements in a matrix can be determined by the size of the operator.
·
We
find the type of elements stored in an array by subtracting adjacent addresses.
Array types
An array is basically two types
1) Single dimensional array
2) Multi-dimensional array
Single dimensional array
Let us understand this through a
program to understand the initialization and traversal.
#include <iostream>
using namespace std;
int main
()
{
int arr
[5] = {10, 0, 20, 0, 30};
//creating and initializing array
//traversing array
for (int i = 0; i < 5; i++)
{
cout<<arr[i]<<"\n";
}
}
Output
10
0
20
0
30
Traversal for using for each
loop in the array
#include <iostream>
using namespace std;
int main()
{
int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
//traversing array
for (int i: arr)
{
cout<<i<<"\n";
}
}
Output
10
20
30
40
Multidimensional Array
A table is a representation of each element from a multidimensional array; the table contains two indices, one for the row value or number and the other for the column value or number.
The array's parts are organized in a two-dimensional matrix, which contains rows and columns where i stands for the number of rows and j for the number of columns.
Two-dimensional arrays are the simplest multidimensional arrays. Dimensions of the table are unrestricted.
Let us understand how a
multidimensional array works
int mark[5] = {19, 10, 8, 17, 9}
// change 4th element to 9
mark[3] = 9;
// take input from the user
// Store the value at third position
cin >> mark[2];
// take input from the user the
// insert at ith position
cin >> mark[i-1];
// Print first element of the array
cout << mark[0];
// print ith element of the array
cout >> mark[i-1];
let
us try some C++ programs to display the sum and average of array elements
#include <iostream>
using namespace std;
int main()
{
// initialize an array without specifying the size
double numbers[] = {7, 5, 6, 12, 35, 27};
double sum = 0;
double count = 0;
double average;
cout << "The numbers are: ";
// print array elements
// use of range-based for loop
for (const double &n : numbers) {
cout << n << " ";
// calculate the sum
sum += n;
// count the no. of array elements
++count;
}
// print the sum
cout << "\n Their Sum = " << sum << endl;
// find the average
average = sum/count;
cout << "Their Average = " << average << endl;
return 0;
}
Output
The numbers are: 7 5 6 12 35 27
Their Sum = 92
Their Average = 15.3333
Let’s try a C++ program to display the elements of the array
#include <iostream>
using namespace std;
int main()
{
int numbers[5] = {7, 5, 6, 12, 35};
cout << "The numbers are: ";
// Printing array elements
// using range-based for loop
for (const int &n : numbers) {
cout << n << " ";
}
cout << "\n
The numbers are: ";
// Printing array elements
// using traditional for loop
for (int i = 0; i < 5; ++i) {
cout << numbers[i] << " ";
}
return 0;
}
Output
The numbers
are: 7 5
6 12 35
The numbers
are: 7 5
6 12 35
Important things to remember in
the array.
Important things to remember
when using arrays in C++Array indexes start from zero. This means that the
first item stored at index 0 is x[0].
The last element of a matrix of
size n is stored at index (n-1). This example and the last element is x[5].
The addresses of the matrix
elements are consecutive. Consider a scenario where x[0 beginning] address
is 2120.Next element x[1] has address 2124, followed by x[2], 2128, etc.
The size of each element is
quadrupled in this case. This is because the capacity of int is 4 bytes.
Let us try a C++ program to find
the size of the array
#include <iostream>
using namespace std;
int main()
{
int
arr[] = { 1, 2, 3, 4, 5 };
//
Size of one element of an array
cout
<< "Size of arr[0]: " << sizeof(arr[0]) << endl;
//
Size of array 'arr'
cout
<< "Size of arr: " << sizeof(arr) << endl;
//
Length of an array
int
n = sizeof(arr) / sizeof(arr[0]);
cout
<< "Length of an array: " << n << endl;
return
0;
}
Output
Size of arr[0]: 4
Size of arr: 20
Length of an array: 5
Relation between arrays and pointers in C++
Arrays and pointers are tightly connected in C++. An array name is interpreted as a pointer
value, representing the memory location of the array's initial element. As previously mentioned,
array elements are stored in contiguous memory locations; therefore, any array element can
be accessed via its name..
Let us understand this by a C++ program
#include <iostream>
using namespace std;
int main()
{
// Defining an array
int arr[] = { 1, 2, 3, 4 };
//
Define a pointer
int* ptr = arr;
//
Printing address of the arrary using array name
cout <<
"Memory address of arr: " <<
&arr << endl;
//
Printing address of the array using ptr
cout <<
"Memory address of arr: " <<
ptr << endl;
return 0;
}
Output
The memory address of arr: 0x7fff2f2cabb0
The memory address of arr: 0x7fff2f2cabb0
Explanation
Array "arr" is defined first in the code above, and then pointer "ptr" is declared and the array "arr" is assigned to it.. We are able to assign arr to ptr because arr is also a pointer. After that, we print the memory address of arr using reference operator (&) and also print the address stored in pointer ptr and we can see arr and ptr, both stores the same memory address
Passing an array to a function
To use arrays effectively, we
should know how to operate arrays. We can pass arrays as arguments to
functions, just like variables to functions, but we know that the array name is
treated as a pointer using this concept, we can pass an array as an argument to
functions, and then use the pointer to access all of them. elements of the
table.
So in the end arrays are always
passed as function pointers. Let's look at 3 ways to pass an array to a
function that is mainly used.
1) Passing array as a pointer
With this technique, the array's name and the address of its first element are supplied in the function call. If we want then we can can modify the array items of a function using this approach.
Syntax
return_type function_name ( data_type *array_name )
{
// set of statements
}
2) Passing array as an unsized array
In this method, the function accepts an array using a simple array declaration with no size as an argument.
Syntax
return_type function_name ( data_type array_name[] )
{
// set of statements
}
3) Passing array as a sized array
In this method, the function accepts an array using a simple array declaration with size as its argument. We use this method specifying the size of the array only to indicate the size of the array.
Syntax
return_type function_name(data_type array_name[size_of_array])
{
// set of statements
}
Now illustrating different ways to pass the array to function
#include <iostream>
using namespace std;
// passing array as a sized array argument
void printArraySized(int arr[3], int n)
{
cout << "Array as Sized Array Argument: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
// passing array as an unsized array argument
void printArrayUnsized(int arr[], int n)
{
cout << "Array as Unsized Array Argument: ";
for (int i = 0; i < n; i++) {
cout << *(arr + i) << " ";
}
cout << endl;
}
// Passing array as a pointer argument
void printArrayPointer(int* ptr, int n)
{
// Print array elements using pointer ptr
// that store the address of array passed
cout << "Array as Pointer Argument: ";
for (int i = 0; i < n; i++) {
cout << ptr[i] << " ";
}
}
// driver code
int main()
{
int arr[] = { 10, 20, 30 };
// Call function print Array and pass
// array and its size to it.
printArraySized(arr, 3);
printArrayUnsized(arr, 3);
printArrayPointer(arr, 3);
return 0;
}
Output
Array as Sized Array Argument: 10 20 30
Array as Unsized Array Argument: 10 20 30
Array as Pointer Argument: 10 20 30
The C++ Program to Illustrate the
Two-Dimensional Array
#include <iostream>
using namespace std;
int main()
{
// Declaring 2D array
int arr[4][4];
// Initialize 2D array using loop
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++)
{
arr[i][j] = i + j;
}
}
// Printing the element of 2D array
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
cout << arr[i][j]
<< " ";
}
cout << endl;
}
return 0;
}
Output
0 1 2 3
1 2 3 4
2 3 4 5
3 4 5 6
Three-dimensional array
The three-dimensional array is represented by a 3D table. If we imagine or think about this array, we can see represents it as many 2D arrays are stacked over each other. We use array depth, row, and column indices to select a specific element from this 3D array.
To declare a 3D array in C++ we need to specify both its third dimension and
its 2D dimensions.
Let us try a C++ program to
illustrate the 3-D array
#include <iostream>
using namespace std;
int main()
{
// declaring 3d array
int arr[3][3][3];
// initializing the array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
for (int k =
0; k < 3; k++) {
arr[i][j][k]
= i + j + k;
}
}
}
// printing the array
for (int i = 0; i < 3; i++) {
cout << i <<
"st layer:" << endl;
for (int j = 0; j < 3; j++) {
for (int k =
0; k < 3; k++) {
cout
<< arr[i][j][k] << " ";
}
cout <<
endl;
}
cout << endl;
}
return 0;
}
Output
0st layer:
0 1 2
1 2 3
2 3 4
1st layer:
1 2 3
2 3 4
3 4 5
2st layer:
2 3 4
3 4 5
4 5 6
Arrays of
string in C++
There are 5
different ways to create an array
In C++, a string is often simply a string (or a reference/pointer to one) ended by the NULL character \0. A string is an array of one dimension or a two-dimensional array in which certain strings are contained in each row.
Below are
five different ways to create an array of strings in C++:
Using
pointers
2-D array
Using the
String class
Using the
Vector class
Using the
Array class.
1)
1) Using pointers
Pointers are a symbolic representation of an address. Simply put, a pointer is something that stores the address of a variable in it. This method creates an array of string literals along with an array of pointers, where each pointer points to a specific string.
For ex.
// pointers
character array
#include
<iostream>
// Driver
code
int main()
{
//
Initialize array of pointer
const char*
colour[4]
= { "Blue",
"Red", "Orange", "Yellow" };
// Printing
Strings stored in 2D array
for (int i
= 0; i < 4; i++)
std::cout << colour[i]
<< "\n";
return 0;
}
Output
Blue
Red
Orange
yellow
Explanation:
The number of strings is fixed, but does not have to be. 4 can be omitted and the compiler will calculate the correct size.
These strings are permanent and cannot be changed. Since string literals (strings literally quoted) are read-only, we need to specify "const" here to avoid unwanted uses that could crash the program.
2) Using a 2-D array
The simplest form of a multidimensional array is a 2D array in this type of array we store the data in tabular manner. This method is useful when the length of all strings is known and a certain memory space is desired. Space is reserved for languages in one block.
For ex.
// 2D character array
#include <iostream>
// Driver code
int main()
{
// Initialize 2D array
char colour[4][10]
= { "Blue", "Red", "Orange", "Yellow" };
// Printing Strings stored in 2D array
for (int i = 0; i < 4; i++)
std::cout << colour[i] << "\n";
return 0;
}
Output
Blue
Red
Orange
yellow
Explanation:
Both the number of strings
and the size of strings are fixed. 4 can again be omitted and the compiler will
calculate the appropriate size. However, a second dimension (in this case 10)
must be provided so that the compiler can choose the appropriate memory layout.
Each string is editable, but
it takes up all the space provided by the second dimension. Each is arranged
next to each other in memory and cannot be resized.
Sometimes it is desirable to
manage memory capacity and allocate memory space in a fixed, regular
arrangement.
3) 3) Using the
string class
An STL String or String class can be used to create an array of mutable strings. In this method, the string size is not fixed and the strings can be changed, making it a bit more dynamic in nature. However, a string can be created from std::string using built-in functions.
For ex.
// string class
#include <iostream>
#include <string>
// Driver code
int main()
{
// Initialize String Array
std::string colour[4]
= { "Blue", "Red", "Orange",
"Yellow" };
// Print Strings
for (int i = 0; i < 4;
i++)
std::cout << colour[i] << "\n";
}
Output
Blue
Red
Orange
Yellow
Explanation: The array is a
fixed size, but it doesn't have to be. Again, the 4 can be omitted here and the
compiler will determine the appropriate array size. Strings are also
adjustable, so they can be changed.
4) 4)Using the
vector class
A vector is a dynamic array that doubles in size every time a new character is added that exceeds its limit. An STL container vector can be used to dynamically allocate an array of different sizes. This can only be used in C++ because C has no classes. Note that the initialize list syntax requires a compiler that supports the 2011 C++ standard, and although your compiler is likely to be, it is worth considering.
For ex.
// vector class
#include <iostream>
#include <string>
#include <vector>
// Driver code
int main()
{
// Declaring Vector of
String type
// Values can be added here
using
// initializer-list
// syntax
std::vector<std::string>
colour{"Blue", "Red","Orange"};
// Strings can be added at
any time
// with push_back
colour.push_back("Yellow");
// Print Strings stored in
Vector
for (int i = 0; i <
colour.size(); i++)
std::cout << colour[i] << "\n";
}
Output
Blue
Red
Orange
yellow
Explanation:
Vectors are dynamic arrays
and allow you to add and remove items at any time. Vectors can use any type or
class, but a given vector can contain only one type.
5) 5) Using the
array class
An array is a homogeneous mixture of data that is permanently stored in memory space. An STL container array can be used to allocate a fixed-size array. It can be used very similarly to a vector, but the size is always fixed.
For ex.
// array of string using STL array
#include <array>
#include <iostream>
#include <string>
// Driver code
int main()
{
// Initialize array
std::array<std::string,
4> colour{"Blue", "Red","Orange",
"Yellow"};
// Printing Strings stored
in array
for (int i = 0; i < 4;
i++)
std::cout << colour[i] << "\n";
return 0;
}
Output
Blue
Red
Orange
Yellow
There are other ways to make ribbons. In C++ we have many container classes, to make it but each class has its own tradeoffs and features, we need to select from them as per our project's requirements.
Explore and enjoy!
Conclusion: Out of all the
methods, Vector seems to be the best way to create an array in C++.
Let us try a C++ program to
print minimum number from the array
#include <iostream>
using namespace std;
void printMin(int arr[5]);
int main()
{
int arr1[5] = { 30, 10, 20, 40, 50 };
int arr2[5] = { 5, 15, 25, 35, 45 };
printMin(arr1);//passing array to function
printMin(arr2);
}
void printMin(int arr[5])
{
int min = arr[0];
for (int i = 0; i > 5; i++)
{
if (min > arr[i])
{
min = arr[i];
}
}
cout<< "Minimum element is: "<< min <<"\n";
}
Output:
Minimum element is:
10
Minimum element is:
5
Let us try a C++ program to
print maximum number from the array
#include <iostream>
using namespace std;
void printMax(int arr[5]);
int main()
{
int arr1[5] = { 25, 10, 54, 15, 40 };
int arr2[5] = { 12, 23, 44, 67, 54 };
printMax(arr1); //Passing array to function
printMax(arr2);
}
void printMax(int arr[5])
{
int max = arr[0];
for (int i = 0; i < 5; i++)
{
if (max < arr[i])
{
max = arr[i];
}
}
cout<< "Maximum element is: "<< max <<"\n";
}
Output:
The maximum element
is: 54
The maximum element
is: 67
No comments:
Post a Comment