C++ Arrays

Arrays

An array is a group of consecutive memory locations with same name and types.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 these memory locations have one collective name and type.The memory locations in the array are known as elements of array.
The total number of elements in array is called its length.

Each element in the array is accessed with reference to its position of location in the array.The position is called index or subscript.Each element in the array has a unique index. The index of first element is 0 and index of last element is length -1.The value of the index is written in brackets along with the name of array.Arrays are used to store a large amount of similar kind of data.



Advantages / Uses of Array

some advantages of arrays are as follows:
  • Array can store a large number of values with single name.
  • Arrays are used to process many values easily and quickly.
  • The Value stored in an array can be stored easily.
  • A Search process can be applied on array easily.



Declaring One-Dimensional Array

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

Syntax:

Data_type Identifier[length];

int marks[5];

The above example declares an integer array marks of five elements. It allocates five consecutive location in memory.

Array Initialization

The process of assigning values to array elements at the time of array declaration is called array initialization.

int marks[5]={11,12,44,12,44};


The above statement declares an integer array marks with five elements. It also initializes the array with values given in the braces. In this declaration , marks[0] is initialized to 22 , marks[1] is initialized to 33 and so on.


An array size can be omitted when it is initialized in the declaration as follows:



int age[]={22,33,44,55,22,55,33,34};

Example
Output Array values without loop

#include <iostream>
using namespace std;
int main()
{
//initialization array
    int prices[]={12,33,44,66};
// output array index 0 value
    cout<<prices[0];
    cout<<endl;
// output array index 1 value
    cout<<prices[1];
    cout<<endl;
// output array index 2 value
    cout<<prices[2];
    cout<<endl;
// output array index 3 value
    cout<<prices[3];
    cout<<endl;
    return 0;

}
Output:


Example
Output Array values with loop

#include <iostream>
using namespace std;
int main()
{
//initialization array
    int prices[]={12,33,44,66};
// for loop with size as array
    for(int $i=0;$i<4;$i++)
    {
// output array value with array index using loop
    cout<<prices[$i];
    cout<<endl;
    }
    return 0;

}
Output:








<< C++ Functions        --        C++ Strings >>