Arrays
Lesson 13Author : Afrixi
Last Updated : November, 2022
In C++, an array is a collection of elements of the same data type, stored in contiguous memory locations. Here’s an example of how to create and use an array:
#include <iostream>
int main() {
int numbers[5];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
std::cout << "The first number is: " << numbers[0] << std::endl;
std::cout << "The third number is: " << numbers[2] << std::endl;
return 0;
}
In this code, an integer array called numbers is created with 5 elements. The values of each element are then set individually using the index notation numbers[index] = value
.
To access the values stored in the array, we use the index notation numbers[index]
. In this example, we print the first and third numbers in the array to the console using std::cout
.
We can also use a loop to iterate over the array and perform some operation on each element. Here’s an example of how to sum up the elements in the array:
#include <iostream>
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += numbers[i];
}
std::cout << "The sum of the numbers is: " << sum << std::endl;
return 0;
}
In this code, we initialize the numbers
array with values using the brace initialization syntax {10, 20, 30, 40, 50}
. We then use a for
loop to iterate over the array and add each element to a variable called sum
. Finally, we print the sum of the elements to the console using std::cout
.