An array is a sequential collection of elements of the same type. Arrays are used to store collections of data, but it is often more useful to think of arrays as collections of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ... and number99, you can declare an array variable (such as numbers) and use numbers[0], numbers[1] and ..., numbers[99] to represent each variable. Specific elements in the array are accessed through indexing.
All arrays are composed of contiguous memory locations. The lowest address corresponds to the first element, and the highest address corresponds to the last element.
Declaring an array requires specifying the type of elements and the number of required elements. An array is as follows -
type arrayName [ arraySize ];
This is called a one-dimensional array. arraySize must be an integer constant greater than zero, and the type can be any valid C data type. For example, to declare an array of 10 elements named balance and of type double, use the following statement -
double balance[10];
A single piece of data in an array is an element of the array. You can use indexing to access elements of an array.
Suppose you declare an array tag as above. The first element is mark[0], the second element is mark[1], and so on. The array starts at index 0.
Declare an array by specifying size and initializing elements
int mark[5] = {19, 10, 8, 17, 9};
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
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];
C program that uses an array to store and calculate the sum of 5 numbers entered by the user
Input
Enter 5 numbers: 3 4 5 4 2
Output
Sum = 18
#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; }
The above is the detailed content of Arrays in C/C++?. For more information, please follow other related articles on the PHP Chinese website!