C++ Arrays - I

October 08, 2015 Posted by WithU Technologies
Generally, arrays are used to store a collection of data in a sequential format, but here we use array to store multiple values with a single variable and with a same data type.

Format:

int variable[number of element];

Example:

int age[6];

Here we declare a data type first which is common for all the values and then declare a variable which is declared as an array of six integer values specified within a square bracket [].

int age[6] = {2,6,4,8,9,2};

Then, the values are declared sequentially with commas within curly braces {}.

Here the values separated by comma maintain a sequence which pinpoints the index location of those elements.

As here the first element is 2 which pinpoints 0 as its index location thus the rest of all are sequenced as shown below:


Index


0


1


2


3


4


5


Elements


2


6


4


8


9


2



Zero always took the first index position and then it goes on consequently.

Accessing an Array

To access any particular array, we have to know its index location. Thus, if we need to access 8 value which is stored as the 3rd location in the sequence, then we need to write:

#include <iostream>
using namespace std;

int main(){

int age[6] = {2,6,4,8,9,2};

cout<<age[3]<<endl;// 3 refers to the third location in the sequence of elements, which is 8

age[3] = 54;

cout<<age[3];// Outputs 54 which is assigned as the new value

}

You can also assign a new value to that array element. Here we assign a value of 54 to the array’s 3rs element.

Arrays used in Loops

#include <iostream>
using namespace std;

int main(){

int age[6];

for(int x=0;x<6;x++){//Acts as the index location which starts from 0 and ends before 6

      cout<<"Enter a new number"<<endl; // Took an input from user during every loop

      cin>>age[x];   // store each input in each location of x

      cout<<"Value of x in this loop instance "<<age[x]<<endl; // Display that input which is provided by user within that instance of loop

 }

}

Output:
Enter a new number 2

Value of x in this loop instance 2

Enter a new number 75

Value of x in this loop instance 75

Enter a new number 86

Value of x in this loop instance 86

Enter a new number 56

Value of x in this loop instance 56

Enter a new number 78

Value of x in this loop instance 78

Enter a new number 25

Value of x in this loop instance 25

·         Here we use a for loop to create the index locations for the array elements.

·         After creating an array index point, it took an input from user which is saved within that index point or storage.

·         Then it displays the value which is stored within that instance of loop in x.