Home | Computer | Array in C++ | Declaring One-Dimensional Array

Array in C++ | Declaring One-Dimensional Array

August 28, 2022

An array is a group of consecutive memory locations with the same name and type. A simple variable is a single memory location with a unique name and a type. But an array is a collection of different adjacent memory locations.

All memory locations in the array have one collective name and type. The memory location in the array is known as the element of the array. The total number of elements in the array is known as its length.

Each element in the array is accessed with reference to its position located in the array. This position is called index and subscript. Each element in the array has a unique index. The index of the first element is 0 and the index of the last element is length -1. The values of the index are written in brackets along with the name of the array.

Uses of Arrays

Some advantages of arrays are as follows:

  • Arrays can store a large number of values with a single name.
  • Multiple values are processed easily and quickly by arrays.
  • The values stored in an array can be stored easily.
  • A search process can be applied to an array easily.

Declaring One-Dimensional Array

A type of array in which all elements are arranged in the form of a list is known as a one-dimensional array. It is also called a single-dimensional array or linear list. It consists of one column or one row. This process of specifying the array name length and data type is called array declaration.

Syntax Declaring One-Dimensional Array

The syntax of declaring a one-dimensional array is as follows:

Data_Type Identifier[length]

Data_Type: It indicates the data types of the values to be stored in the array.

Identifier: It indicates the name of the array.

Length: It indicates the total number of elements in the array. It must be a literal constant or symbolic constant.

Example:

int marks[5];

image showing an array marks with 5 elements

Array Initialization

The process of assigning the value to the array at the time of declaration is known as array initialization. The initialization process provides a list of the initial value for array elements.

Syntax of array initialization

Data_ Type Identifier[Length] = {List of the value};

List of values: It indicates the values to initialize the array. These values must be constant

Example

int marks[5] = {60, 65, 72, 75, 87};

image showing the array initilization

Accessing individual elements

Each individual element of an array is accessed by specifying the following:

  • Name of array
  • Index of element

Syntax of accessing individual elements

Array_ Name [Index];

Array_Name: It indicates the name of the array.

Index: It indicates the index of the element to be accessed.

Example:

int marks[5];

marks[0]= 20;

marks[1]= 50;

marks[2]= 70;

marks[3]= 80;

marks[4]= 90;