Array

C++BasicsInputArithmeticConditionsLoops → Array

The arrays in C++ Construction and Examples. The arrays are used when we have large data of same nature.

Construction: Array

type name [size];

For example, consider the array of type integer and size 5.

#include <iostream>
using namespace std;
int main()
{
int myarray[5] = {10, 13, 17, 20, 25}; //array size 5
cout << myarray[0] << endl; //show first element
cout << myarray[1] << endl; //show second element
cout << myarray[4] << endl; //show fifth element
return 0;
}

We can display all elements of the array using for loop.

#include <iostream>
using namespace std;
int main()
{
int myarray[5] = {10, 13, 17, 20, 25};
for (int i=0; i<5; i++)
{
cout << myarray[i] << endl;
}
return 0;
}

Arrays can also be created by taking input from the user. For example, the following program will take three inputs from the user, and after that it will end.

#include <iostream>
using namespace std;
int main()
{
int a[3];
cout << "Please input three numbers: " << endl;
cin >> a[0];
cin >> a[1];
cin >> a[2];
return 0;
}

The following program will take three inputs from the user and will return sum of the numbers.

#include <iostream>
using namespace std;
int main()
{
int sum = 0;
int a[3];
cout << "Please input three numbers: " << endl;
cin >> a[0];
cin >> a[1];
cin >> a[2];
sum = sum + a[0] + a[1] + a[2];
cout << sum << endl;
return 0;
}

To do these types of calculations, the easiest method is to use for loop. For example, the following program will take ten inputs from the user and will end after that.

#include <iostream>
using namespace std;
int main()
{
int a[10];
cout << "Please insert ten numbers: " << endl;
for (int i =0; i<10; i++)
{
cin >> a[i];
}
return 0;
}

The following program will take sales of ten items from the user using for loop, and will show the sum and the average of the sales.

#include <iostream>
using namespace std;
int main()
{
int sales[10];
int sum = 0; //initially sum is 0
cout << "Please insert the sales: " << endl;
for (int i =0; i<10; i++)
{
cin >> sales[i];
sum = sum + sales[i]; //add array values to the sum
}
cout << "Total Sales = " << sum << endl;
cout << "Average = " << static_cast< float>(sum)/10 << endl;
return 0;
}

As average can also take decimal value, so we have converted sum (which is integer) into float using static_cast< float>(sum) and then divided by 10 (to get average of 10 sales), so that it could show figure after decimal point.

The following program will ask user to input date and month, and will show the number of days from the beginning of the year.

#include <iostream>
using namespace std;
int main()
{
int date, month;
int year[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
cout << "Enter Date: ";
cin >> date;
cout << "Enter Month: ";
cin >> month;
int a = 0;
for (int i=0; i < month-1; i++)
{
a = a + year[i];
}
cout << "Number of Days = " << a+date << endl;
}

NEXT: Multidimensional arrays