info@tutsfinder.in



Arrays


An array is a group of elements forming a complete building block.

The following are characteristics of an array –

• An array is a collection of elements.

• All elements contained in an array are of same data type.

• This collection forms a complete set.

In C++, arrays enable you to store data elements of a type in the memory, in a sequential order.


Array Declaration and Initialization

If you want use array in your program then first declare variable and initialize the value to that variable.

Syntax: dataType array_name[]={ };

Example: int myarray [] = { 7,8,4,21};


Need for Arrays –

Imagine that you are writing a program to display the 5 different types of integers. Declaration would look like this –

int a=0;
int b=0;
int c=0;
int d=0;
int e=0;

If your user wants this program to store and display 100 integers value, now first you have to declare 100 integers using the preceding system. This would be very time consuming. So there in concept that is array.

Declaring an array of 5 integers –

Int arr[5]={0};

Program to declaring an array of integers and accessing its elements

#include <iostream>
using namespace std;

int main()
{
    int arr[5]={12,45,18,7,8};
    cout << "First element at index 0: " << arr[0] << endl;
    cout << "Second element at index 1: " << arr[1] << endl;
    cout << "Third element at index 2: " << arr[2] << endl;
    cout << "Fourth element at index 3: " << arr[3] << endl;
    cout << "Fifth element at index 4: " << arr[4] << endl;
}


Accessing elements by traversing –

#include <iostream>
using namespace std;

int main()
{
    int arr[5]={12,45,18,7,8};
    cout << "Elements of an array" << endl;
    for(int i=0;i<5;i++)
    cout << arr[i]<<"\n";
}