C ++ Arrays

C++ Arrays

In this article, you will learn to work with arrays. You will learn to declare, initialize and, access array elements in C++ programming.
In programming, one of the frequently arising problem is to handle numerous data of same type.
Consider this situation, you are taking a survey of 100 people and you have to store their age.
To solve this problem in C++, you can create an integer array having 100 elements.
An array is a collection of data that holds fixed number of values of same type. For example:
int age[100];

Accessing the values of an array

The values of any of the elements in an array can be accessed just like the value of a regular variable of the same type. The syntax is:
Following the previous examples in which foo had 5 elements and each of those elements was of type int, the name which can be used to refer to each element is the following:



Example

#include <iostream >
using namespace std;

int main() 
{
    int numbers[5], sum = 0;
    cout << "Enter 5 numbers: ";
    
    //  Storing 5 number entered by user in an array
    //  Finding the sum of numbers entered
    for (int i = 0; i < 5; ++i) 
    {
        cin >> numbers[i];
        sum += numbers[i];
    }
    
    cout << "Sum = " << sum << endl;  
    
    return 0;
}

Output

Enter 5 numbers: 3
4
5
4
2
Sum = 18





                << PREVIEW  >>


               <<   NEXT   >>

Comments