Skip to content

Commit 7fab24e

Browse files
authored
Merge branch 'main' into ruby-gems
2 parents b2d3bb6 + 5634f45 commit 7fab24e

File tree

41 files changed

+4535
-789
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

41 files changed

+4535
-789
lines changed

content/cpp/concepts/arrays/arrays.md

Lines changed: 252 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,73 +1,294 @@
11
---
22
Title: 'Arrays'
3-
Description: 'Like a vector, an array is a data structure used in C++ to store a sequential collection of elements.'
3+
Description: 'Stores multiple values of the same data type in contiguous memory locations.'
44
Subjects:
55
- 'Computer Science'
6-
- 'Game Development'
6+
- 'Web Development'
77
Tags:
88
- 'Arrays'
9-
- 'Vectors'
9+
- 'Data Structures'
10+
- 'Memory'
11+
- 'Variables'
1012
CatalogContent:
1113
- 'learn-c-plus-plus'
1214
- 'paths/computer-science'
1315
---
1416

15-
Like a vector, an **array** is a data structure used in C++ to store a sequential collection of elements. Unlike vectors, its size cannot be changed.
17+
An **array** is a data structure that stores multiple values of the same [data type](https://www.codecademy.com/resources/docs/cpp/data-types) in contiguous memory locations. Arrays allow storing and accessing a collection of elements efficiently using a single variable name with indexed positions. Instead of declaring separate variables for each value, an array provides a way to manage multiple related values as a single entity.
1618

17-
Being able to store multiple pieces of related information in the same structure is very useful when writing C++ programs.
19+
Arrays are particularly useful when dealing with collections of similar data, such as storing student grades, temperature readings, or inventory items. The size of an array must be known at compile time and cannot be changed during program execution.
1820

19-
## Creating an Array
21+
## Create an Array
2022

21-
When creating an array, two pieces of information have to be kept in mind:
23+
### Syntax
2224

23-
- The type of data to be stored inside it.
24-
- How many items it should be able to hold (its size).
25+
```pseudo
26+
dataType arrayName[arraySize];
27+
```
28+
29+
The syntax consists of the data type, followed by the array name, and the size enclosed in square brackets. The size must be a positive integer constant.
30+
31+
### Example
2532

26-
An array can be created a lot like how normal variables are created: by specifying the data type, giving it a descriptive name, and also specifying its size:
33+
This example creates three arrays: `numbers` can store 5 integers, `prices` can store 10 double values, and `letters` can store 26 characters.
2734

2835
```cpp
29-
int favoriteNums[4];
36+
#include <iostream>
37+
using namespace std;
38+
39+
int main() {
40+
// Create an array of integers
41+
int numbers[5];
42+
43+
// Create an array of doubles
44+
double prices[10];
45+
46+
// Create an array of characters
47+
char letters[26];
48+
49+
return 0;
50+
}
51+
```
52+
53+
## Initialize Array with Values
54+
55+
### Syntax
56+
57+
```pseudo
58+
dataType arrayName[arraySize] = {value1, value2, value3, ...};
3059
```
3160

32-
In the above code example, an array is created with a size of `4`, meaning it can hold four integers (all four elements will initially have the default `int` value of `0`).
61+
Values are enclosed in curly braces and separated by commas. The number of values cannot exceed the array size but can be less.
62+
63+
### Example
3364

34-
In many cases, what data needs to go in the array will not be known until after it's created, but if the contents of the array are known ahead of time, it can be initialized with custom values upfront:
65+
In the following example, `scores` is fully initialized, `grades` has the first three elements set with the rest defaulting to 0, and `ages` automatically sizes to 5 elements.
3566

3667
```cpp
37-
int favoriteNums[] = {7, 9, 15, 16};
68+
#include <iostream>
69+
using namespace std;
70+
71+
int main() {
72+
// Initialize array with specific values
73+
int scores[5] = {85, 92, 78, 96, 88};
74+
75+
// Initialize with fewer values (remaining filled with 0)
76+
int grades[6] = {90, 85, 77};
77+
78+
// Let compiler determine size
79+
int ages[] = {25, 30, 35, 28, 33};
80+
81+
return 0;
82+
}
3883
```
3984

40-
This array would also have a size of `4`, but it does not need to be explicitly specified when initialized this way.
85+
## Access Array Elements
4186

42-
> **Note:** Even if an array `arr` has a length of `n`, it can be accessed and modified with `arr[n+1]`, which can overwrite other variables or cause undefined behaviour.
87+
Array elements are accessed using the **subscript operator** `[]` with an index number. Array indexing starts at 0, meaning the first element is at index 0, the second at index 1, and so on.
4388

44-
## Array Indices
89+
### Example
4590

46-
Like vectors, each element in an array is assigned a specific index starting at zero. To access or modify an element in the array it may be referred to by its index and operated on accordingly:
91+
The following code initializes an array of five integers and prints the first, third, and last elements:
4792

4893
```cpp
49-
char vowels[] = {'a', 'e', 'i', 'o', 'u'};
50-
// indexes: 0 1 2 3 4
94+
#include <iostream>
95+
using namespace std;
96+
97+
int main() {
98+
int numbers[5] = {10, 20, 30, 40, 50};
99+
100+
// Access and print array elements
101+
cout << "First element: " << numbers[0] << endl;
102+
cout << "Third element: " << numbers[2] << endl;
103+
cout << "Last element: " << numbers[4] << endl;
51104

52-
std::cout << vowels[0];
53-
// Output: a
105+
return 0;
106+
}
107+
```
54108

55-
vowels[0] = 'r';
109+
The output of the above code will be:
56110

57-
std::cout << vowels[0];
58-
// Output: r
111+
```shell
112+
First element: 10
113+
Third element: 30
114+
Last element: 50
59115
```
60116

61-
In the case above, an array of `chars` was initialized with all the vowels, and then the first element in the array at index `0` was printed out. Then the element at index `0` was modified by being assigned a new value of `'r'`, which was then printed out.
117+
## Update Array Elements
62118

63-
Arrays in C++ have a fixed size, meaning elements cannot be added or removed once the array has been created. Only existing elements may be modified without changing the total size or shape of the structure.
119+
Array elements can be modified by assigning new values to specific indices using the assignment operator.
64120

65-
## Uninitialized Elements
121+
### Example
66122

67-
Array elements that are not assigned a value when the array is created are known as uninitialized elements and should not be accessed during runtime. For example:
123+
The following code initializes an array of five integers, prints the original array, updates specific elements, and then prints the updated array:
68124

69125
```cpp
70-
int arr[5] = {0, 1, 2};
126+
#include <iostream>
127+
using namespace std;
128+
129+
int main() {
130+
int numbers[5] = {10, 20, 30, 40, 50};
131+
132+
cout << "Original array: ";
133+
for (int i = 0; i < 5; i++) {
134+
cout << numbers[i] << " ";
135+
}
136+
cout << endl;
137+
138+
// Update specific elements
139+
numbers[0] = 15;
140+
numbers[2] = 35;
141+
numbers[4] = 55;
142+
143+
cout << "Updated array: ";
144+
for (int i = 0; i < 5; i++) {
145+
cout << numbers[i] << " ";
146+
}
147+
cout << endl;
148+
149+
return 0;
150+
}
151+
```
152+
153+
The output of the above code will be:
154+
155+
```shell
156+
Original array: 10 20 30 40 50
157+
Updated array: 15 20 35 40 55
71158
```
72159

73-
This code initializes an array of five integers in which index `3` and `4` are empty and should not be accessed during the program's runtime.
160+
## Example 1: Student Grade Calculator
161+
162+
The following code initializes an array of student grades, calculates their total and average, and prints the results:
163+
164+
```cpp
165+
#include <iostream>
166+
using namespace std;
167+
168+
int main() {
169+
// Create and initialize array of student grades
170+
double grades[6] = {88.5, 92.0, 76.5, 85.0, 91.5, 89.0};
171+
double sum = 0.0;
172+
173+
cout << "Student Grades: ";
174+
175+
// Display grades and calculate sum
176+
for (int i = 0; i < 6; i++) {
177+
cout << grades[i] << " ";
178+
sum += grades[i];
179+
}
180+
181+
double average = sum / 6;
182+
183+
cout << endl;
184+
cout << "Total: " << sum << endl;
185+
cout << "Average: " << average << endl;
186+
187+
return 0;
188+
}
189+
```
190+
191+
The output of the above example will be:
192+
193+
```shell
194+
Student Grades: 88.5 92 76.5 85 91.5 89
195+
Total: 522.5
196+
Average: 87.0833
197+
```
198+
199+
## Example 2: Interactive Array Management
200+
201+
The following code takes 5 integers from the user, doubles every second element in the array, displays the original and updated arrays, and finds and prints the maximum value along with its index:
202+
203+
```cpp
204+
#include <iostream>
205+
using namespace std;
206+
207+
int main() {
208+
const int SIZE = 5;
209+
int numbers[SIZE];
210+
211+
// Input values from user
212+
cout << "Enter " << SIZE << " integers:" << endl;
213+
for (int i = 0; i < SIZE; i++) {
214+
cout << "Element " << (i + 1) << ": ";
215+
cin >> numbers[i];
216+
}
217+
218+
// Display original array
219+
cout << "\nOriginal array: ";
220+
for (int i = 0; i < SIZE; i++) {
221+
cout << numbers[i] << " ";
222+
}
223+
cout << endl;
224+
225+
// Update every second element
226+
cout << "\nUpdating every second element..." << endl;
227+
for (int i = 1; i < SIZE; i += 2) {
228+
numbers[i] = numbers[i] * 2;
229+
}
230+
231+
// Display updated array
232+
cout << "Updated array: ";
233+
for (int i = 0; i < SIZE; i++) {
234+
cout << numbers[i] << " ";
235+
}
236+
cout << endl;
237+
238+
// Find maximum value
239+
int max = numbers[0];
240+
int maxIndex = 0;
241+
for (int i = 1; i < SIZE; i++) {
242+
if (numbers[i] > max) {
243+
max = numbers[i];
244+
maxIndex = i;
245+
}
246+
}
247+
248+
cout << "\nMaximum value: " << max << " at index " << maxIndex << endl;
249+
250+
return 0;
251+
}
252+
```
253+
254+
The output of the above code will be:
255+
256+
```shell
257+
Enter 5 integers:
258+
Element 1: 1
259+
Element 2: 2
260+
Element 3: 5
261+
Element 4: 5
262+
Element 5: 2
263+
264+
Original array: 1 2 5 5 2
265+
266+
Updating every second element...
267+
Updated array: 1 4 5 10 2
268+
269+
Maximum value: 10 at index 3
270+
```
271+
272+
> **Note:** The output of this program will vary depending on the user’s input values.
273+
274+
## Frequently Asked Questions
275+
276+
### 1. Can array size be changed after declaration?
277+
278+
No, the size of an array is fixed at compile time and cannot be modified during program execution. If dynamic sizing is needed, consider using `std::vector` instead.
279+
280+
### 2. What happens if I access an array element beyond its bounds?
281+
282+
Accessing elements outside the valid index range (0 to size-1) leads to **undefined behavior**, which can cause program crashes or unpredictable results. Always ensure indices are within valid bounds.
283+
284+
### 3. How to find the length of an array?
285+
286+
Use the `sizeof` operator: `int length = sizeof(array) / sizeof(array[0]);`. This only works for statically declared arrays, not for arrays passed as function parameters.
287+
288+
### 4. Can arrays store different data types?
289+
290+
No, all elements in an array must be of the same data type. To store different types, consider using structures, classes, or `std::variant` (C++17).
291+
292+
### 5. How are array elements stored in memory?
293+
294+
Array elements are stored in contiguous memory locations, with each element directly adjacent to the next. This provides efficient memory access and enables pointer arithmetic.

0 commit comments

Comments
 (0)