Arrays in C/C++?


The array is a sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.

All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

Declaring Arrays

To declare an array specifies the type of the elements and the number of elements required by an array as follows −

type arrayName [ arraySize ];

Array declaration by specifying the size

This is called a single-dimension array. The arraySize must be an integer constant greater than zero and type can be any valid C++ data type. For example, to declare a 10-element array called balance of type double, use this statement −

double balance[10];

Elements of an Array and How to access them?

An individual data in an array is the element of the array. You can access elements of an array by using indices.

Suppose you declared an array mark as above. The first element is mark[0], the second element is mark[1] and so on. The array starts with 0 index.

How to initialize an array in C++ programming?

Array declaration by specifying size and initializing elements

int mark[5] = {19, 10, 8, 17, 9};

Array declaration by initializing elements

int mark[] = {19, 10, 8, 17, 9};

Here,

mark[0] is equal to 19; mark[1] is equal to 10; mark[2] is equal to 8; mark[3] is equal to 17; mark[4] is equal to 9

How to insert and print array elements?

int mark[5] = {19, 10, 8, 17, 9}

// change 4th element to 9
mark[3] = 9;
// take input from the user and insert in third element
cin >> mark[2];
// take input from the user and insert in (i+1)th element
cin >> mark[i];
// print first element of the array
cout << mark[0];
// print ith element of the array
cout >> mark[i-1];

Example: C++ Array

C++ program to store and calculate the sum of 5 numbers entered by the user using arrays

Input

Enter 5 numbers:
3
4
5
4
2

Output

Sum = 18

Example

#include <iostream>
using namespace std;

int main() {
   int numbers[5], sum = 0;
   cout << "Enter 5 numbers: ";
   for (int i = 0; i < 5; ++i) {
      cin >> numbers[i];
      sum += numbers[i];
   }
   cout << "Sum = " << sum << endl;
   return 0;
}

Updated on: 16-Aug-2019

354 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements