Array Operations

Defining an array

1. Without specifying the size of the array:

int arr[] = {1, 2, 3};

Although the array cannot be left empty in this scenario, we can leave the square brackets empty. It must contain elements.

2. With specifying the size of the array:

int arr[3];
arr[0] = 1, arr[1] = 2, arr[2] = 3;

Accessing an array element

An array element can be easily retrieved by its index number.

An index number is a sort of number that allows us to access array variables. In a programme, index numbers provide a way to retrieve each element of an array. It should be noted that the index number begins with 0 and not one.

#include <iostream>
using namespace std;
 
int main()
{
    int arr[] = {1, 2, 3};
    cout << arr[1] << endl;
}

Output:

2

Changing an array element

An element in an array can be overwritten using its index number.

Example:

#include <iostream>
using namespace std;
 
int main()
{
    int arr[] = {1, 2, 3};
    arr[2] = 8; //changing the element on index 2
    cout << arr[2] << endl;
}

Output:

8

Shubhajna Rai
Shubhajna Rai

A Civil Engineering Graduate interested to share valuable information with the aspirants.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in