C++ arrays
Created By: chatGPT
Arrays in C++ are a collection of elements of the same type stored in contiguous memory locations. They allow you to store multiple items in a single variable, rather than declaring separate variables for each value. You can define an array using the following syntax:
data_type array_name[array_size];
For example, to create an array of integers to store five numbers, you would write:
int numbers[5];
You can also initialize an array at the time of declaration by providing a list of values in curly braces. Here's how you can initialize the above array with values:
int numbers[5] = {1, 2, 3, 4, 5};
Accessing elements in an array is done using the index, which starts at 0. To access the first element of the above array, you would use:
int firstNumber = numbers[0];
You can also use a loop to iterate through arrays. A simple for loop to print all elements of the array looks like this:
for(int i = 0; i < 5; i++) {
std::cout << numbers[i] << " ";
}
Here's a complete example demonstrating declaration, initialization, and iteration over an array.
#include <iostream>
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
for(int i = 0; i < 5; i++) {
std::cout << numbers[i] << " ";
}
return 0;
}
In situations where the size of the array is not known at compile-time, you can use the
std::vector
from the Standard Template Library (STL). Vectors are dynamic arrays that can change size during runtime. Here’s how you can declare and use a vector:#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
for(int i = 0; i < numbers.size(); i++) {
std::cout << numbers[i] << " ";
}
return 0;
}