Arrays
In the world of programming, arrays are one of the most fundamental and widely used data structures. They allow us to store a collection of elements of the same type, such as integers, characters, or objects, in a contiguous block of memory.
Arrays in C++ have a fixed size, meaning the number of elements in the array is determined at the time of creation and cannot be changed later. This makes arrays efficient in terms of memory usage and provides fast random access to elements.
Let's take a look at an example of declaring and using an array in C++:
1#include <iostream>
2using namespace std;
3
4int main() {
5 // Declaring an array of integers
6 int arr[5] = {1, 2, 3, 4, 5};
7
8 // Accessing and modifying elements of the array
9 cout << "Element at index 2: " << arr[2] << endl;
10 arr[3] = 10;
11
12 // Looping through the array
13 cout << "Array elements: ";
14 for (int i = 0; i < 5; i++) {
15 cout << arr[i] << " ";
16 }
17 cout << endl;
18
19 return 0;
20}
This code declares an array arr
of integers with a size of 5. The elements of the array are initialized with values 1, 2, 3, 4, and 5. We can access elements of the array using the square bracket notation, such as arr[2]
to access the element with index 2. We can also modify the elements of the array using the same notation, like arr[3] = 10
to change the value at index 3.
To loop through the array and print its elements, we can use a for
loop. In this example, we loop from 0 to 4 (inclusive) and print each element of the array.
Arrays provide efficient storage and retrieval of elements, making them a popular choice for various programming tasks. They are used in many applications, such as storing a list of names, keeping track of scores in a game, and implementing algorithms that require indexed access to elements.
Understanding arrays and their usage is an essential foundation for working with more complex data structures and algorithms in C++.
xxxxxxxxxx
using namespace std;
int main() {
// Declaring an array of integers
int arr[5] = {1, 2, 3, 4, 5};
// Accessing and modifying elements of the array
cout << "Element at index 2: " << arr[2] << endl;
arr[3] = 10;
// Looping through the array
cout << "Array elements: ";
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}