In any programming, one of the frequently arising problem is to handle similar types of data. Consider this situation: You have to store marks of more than one student depending upon the input from user. These types of problem can be handled C++ programming(almost all programming language have arrays) using arrays.
An array is a sequence of variable that can store value of one particular data type. For example: 15 int type value, 105 float type value etc.
Defining Arrays
type array_name[size];
Consider this code.
int test[85];
The above code creates an array which can hold 85 elements of int type.
Array Elements
The maximum number of elements an array can hold depends upon the size of an array. Consider this code below:
int age[5];
This array can hold 5 integer elements.
Notice that the first element of an array is age[0] not age[1]. This array has 5 elements and notice fifth is age[4] not age[5]. C++ programmer should always keep this is mind as it may differ from other programming languages.
Array Initialization
Array can be initialized at the time of declaration. For example:
float test[5] = {12, 3, 4, -3, 9};
It is not necessary to write the size of an array during array declaration.
float test[] = {12, 3, 4, -3, 9};
I prefer writing size of array during array declaration because it quickly gives the information on size of an array while help me in debugging code.
Example 1: C++ Array
C++ Program to store 5 numbers entered by user in an array and display first and last number only.
#include <iostream>
using namespace std;
int main() {
int n[5];
cout<<"Enter 5 numbers: ";
/* Storing 5 number entered by user in an array using for loop. */
for (int i = 0; i < 5; ++i) {
cin>>n[i];
}
cout<<"First number: "<<n[0]<<endl; // first element of an array is n[0]
cout<<"Last number: "<<n[4]; // last element of an array is n[SIZE_OF_ARRAY - 1]
return 0;
}
Output
Enter 5 numbers: 4
-3
5
2
0
First number: 4
Last number: 0