Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

Arrays

Array

In C++, an array is a data structure that allows you to store multiple values of the same data type in a contiguous memory location. Here are some key points about arrays:

  1. Declaration of an Array:
    • You can declare an array by specifying the data type followed by the array name and its size.
    • For example:int arr[5]; // Declares an integer array with 5 elements
  2. Initialization of an Array:
    • You can initialize an array at the time of declaration or after declaration.
    • Examples:
      • Initialize with values:int arr[5] = {1, 2, 3, 4, 5};
      • Initialize without specifying size (size is determined by the number of elements):int arr[] = {1, 2, 3, 4, 5};
      • Initialize using a loop after declaration:const int N = 5; for (int i = 0; i < N; ++i) { arr[i] = value; // Modify 'value' according to your requirements }
  3. Accessing Array Elements:
    • Array indexing starts from 0. The first element is stored at index 0, the second at index 1, and so on.
    • You can access elements using their indices:int firstElement = arr[0]; int secondElement = arr[1];
  4. Properties of Arrays:
    • Once an array is declared, its size remains constant throughout the program.
    • An array can have multiple dimensions (e.g., 2D arrays).
    • The size of an array can be determined using the sizeof operator.

Arrays are powerful tools for managing collections of related data. They allow efficient storage and retrieval of elements. Remember that array indices start from 0, so the last element is at index  size - 1.

Example:

#include <iostream>

int main() {
    // Declare an integer array with 5 elements
    int arr[5];

    // Initialize the array with values
    arr[0] = 10;
    arr[1] = 20;
    arr[2] = 30;
    arr[3] = 40;
    arr[4] = 50;

    // Access and print array elements
    std::cout << "Array elements:" << std::endl;
    for (int i = 0; i < 5; ++i) {
        std::cout << "arr[" << i << "] = " << arr[i] << std::endl;
    }

    return 0;
}

Output:

Array elements:
arr[0] = 10
arr[1] = 20
arr[2] = 30
arr[3] = 40
arr[4] = 50

Change an Array Element

#include <iostream>
#include <string>
using namespace std;

int main() {
  string cars[4] = {"Mercedes", "Audi", "Ford", "Toyota"};
  cars[0] = "BMW";
  cout << cars[0];
  return 0;
}

Output:

BMW

Loop Through an Array

Certainly! In C++, there are several ways to loop through an array. Let’s explore a couple of them:

  1. Using a for loop:
    • The traditional way to loop through an array is by using a for loop. You can iterate over the array indices and access each element.
    • Example:
#include <iostream>
#include <string>
using namespace std;

int main() {
  string cars[5] = {"Audi", "Mustang", "Ford", "BMW", "Tesla"};
  for (int i = 0; i < 5; i++) {
    cout << cars[i] << "\n";
  }
  return 0;
}

Output:

Audi
Mustang
Ford
BMW
Tesla

2. Using a range-based for loop (C++11 and later):

  • The range-based for loop directly iterates over the elements of the array without needing an index.
  • Example:
#include <iostream>
using namespace std;

int main() {
  int myNumbers[5] = {1, 2, 3, 4, 5};
  for (int i : myNumbers) {
    cout << i << "\n";
  }
  return 0;
}

Output:

1
2
3
4
5

 Omit Array Size

In C++, you can omit the size of an array during initialization. Let me explain how it works:

  1. Declaring size during initialization: You can explicitly declare the size of an array while initializing it. For example:int arr[5] = {1, 2, 3, 4, 5}; In this case, an array of size 5 is created with the specified elements.
  2. Omitting array size during initialization: Alternatively, you can omit the size while initializing the array:int arr[] = {1, 2, 3, 4, 5}; The compiler will automatically determine the size of the array based on the number of elements provided. In this example, an array of size 5 is also created.

Both methods are correct, but specifying the size explicitly is considered better because it reduces the chances of errors. However, the second method is convenient when you want the compiler to infer the size based on the provided values.

Here’s a code snippet demonstrating both approaches:

#include <iostream>
using namespace std;

int main() {
    int arr1[] = {1, 2, 3, 4, 5}; // Omitting size
    for (int i = 0; i < 5; i++)
        cout << arr1[i] << " ";
    cout << "\n";

    int arr2[5] = {1, 2, 3, 4, 5}; // Declaring size
    for (int i = 0; i < 5; i++)
        cout << arr2[i] << " ";

    return 0;
}

Output:

1 2 3 4 5
1 2 3 4 5

Get the Size of an Array

 In C++, you can find the size (number of elements) of an array using different methods:

  1. Using sizeof operator: You can calculate the size of an array by dividing the total size of the array by the size of a single element. For example:
#include <iostream>
using namespace std;

int main() {
  int myNumbers[5] = {1, 2, 3, 4, 5};
  cout << sizeof(myNumbers);
  return 0;
}

Output:

5

Loop through an Array with sizeof()


In the Arrays and Loops Chapter, we previously used a specific size for the array in the loop condition (e.g., i < 5). However, this approach is limited because it only caters to arrays of fixed sizes.

Fortunately, we can enhance our loops to be more adaptable by leveraging the sizeof() function, as demonstrated earlier. This allows us to create loops that accommodate arrays of varying sizes, ensuring greater flexibility and sustainability in our code.

Example:

#include <iostream>
using namespace std;

int main() {
  int myNumbers[5] = {1, 2, 3, 4, 5};
  for (int i = 0; i < sizeof(myNumbers) / sizeof(int); i++) {
    cout << myNumbers[i] << "\n";
  }
  return 0;
}

Output:

1
2
3
4
5

Multi-Dimensional Array

A multi-dimensional array is a type of array in programming that contains elements organized in multiple dimensions or layers. Unlike a one-dimensional array, which consists of a single row or column of elements, a multi-dimensional array can have multiple rows and columns, forming a grid-like structure.

Example:

#include <iostream>

int main() {
    // Declaration and initialization of a 2D array
    int matrix[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    // Accessing and printing elements of the 2D array
    std::cout << "Elements of the 2D array:" << std::endl;
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            std::cout << matrix[i][j] << " ";
        }
        std::cout << std::endl;
    }

    return 0;
}

Output:

Elements of the 2D array:
1 2 3 
4 5 6 
7 8 9 

    Leave a Reply

    Your email address will not be published.

    Need Help?