cpp / beginner
Snippet
Understanding Arrays: Storing Multiple Values
Arrays allow you to store multiple values of the same type in a single variable. Think of an array like a row of mailboxes, each with its own index number. The first element is always at index 0, not 1. You can access and modify any element using its index.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>using namespace std;int main() {int scores[5] = {95, 87, 92, 78, 88};cout << "First score: " << scores[0] << endl;cout << "Third score: " << scores[2] << endl;for(int i = 0; i < 5; i++) {scores[i] = scores[i] + 1;}cout << "Updated first score: " << scores[0] << endl;return 0;}
Breakdown
1
int scores[5]
Declares an array that can hold 5 integer values
2
= {95, 87, 92, 78, 88}
Initializes the array with 5 specific values
3
scores[0]
Accesses the first element using index 0
4
scores[i] = scores[i] + 1
Modifies an element by adding 1 to it
5
i < 5
Loop condition ensures we stay within array bounds