CodesJava

Easy learning with example program codes

CPP Arrays


An array is a single variable which can store multiple values at a time. Thus, CPP array is used to hold many values under a single name. These values can be accessed then by referring to their index number. There are mainly two types of arrays: 1D array and multidimensional array.

Syntax:

data_type arrayName [arraySize];

Or

data_type arrayName [arraySize] = array{value 1, value 2, …};

Advantages of using Array in CPP:

  • Single variable need to be declared, instead of multiple variable, making the code user friendly.
  • Less number of lines needed in a code.
  • Traversing of all the elements is easy.
  • Functions like sorting can be easily applied to all the elements.

Example : Printing Table of 5.

#include <iostream.h>
using namespace std;
 
int main()
{
int table[10] = {5,10,15,20,25,30,35,40,45,50};
int i;
for (i=1;i<11;i++)
cout << "5 * " << i << " = " << table[i-1] << endl;
return 0;
}

Output

5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
Please follow and like us:
Posted in CPP   


Copyright © 2019 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki