c-plus-plus
  1. c-plus-plus-c-arrays

C++ Arrays

Syntax

data_type array_name[array_size];
  • data_type: Type of data stored in the array.
  • array_name: Name of the array.
  • array_size: Size of the array, i.e., the number of elements it can store.

Example

#include <iostream>
using namespace std;

int main() {
   int numbers[5] = {10, 20, 30, 40, 50};

   for(int i = 0; i < 5; i++) {
      cout << numbers[i] << endl;
   }
   
   return 0;
}

Output

10
20
30
40
50

Explanation

In the above example, we have declared an array numbers of size 5 and type int. We initialize this array with some values and then use a for loop to print out each value in the array.

Use

Arrays are used to store multiple values of the same type in a single variable. They allow us to access individual elements of the array using index numbers.

Important Points

  • The index of the first element in an array is always 0.
  • The last element in an array has an index of array_size - 1.
  • Arrays in C++ are fixed size, which means the size of an array cannot be changed once it is declared.
  • It is possible to initialize an array with fewer elements than its size. The remaining elements will be set to 0.

Summary

Arrays are an important data structure in C++. They allow us to store multiple values of the same type in a single variable, and access individual elements using index numbers. When declaring an array, we must specify the type of data it will store, its size, and a name for the array variable. While arrays in C++ are fixed size, we can still initialize them with fewer elements than their size.

Published on: