Loops in Arrays
Initialize the array declaring every time the single element can take a lot of your code. To go through the array you can use for
loops. Let’s print each element of the array using loops:
1234int numbers[5] = {1, 2, 3, 4, 5}; for (int i = 0; i <= 4; i++) { cout << numbers[i] << " "; }
In this code, the for loop goes through each element by its index and print in such a way the whole array.
The last index of the array is 4 since we have 5 elements. Keep in mind that the first element’s index is 0 that’s why the for loop initialized the variable
i
to0
.
We can also define each element in the loops (for example, by its index):
12345int numbers[5]; for (int i = 0; i <= 4; i++) { numbers[i] = i; cout << numbers[i] << " "; }
Swipe to start coding
Print each element of the array with its index.
- Define the array.
- Use
for
loop to go through array. - In output define the element and index in the gaps.
Ratkaisu
Kiitos palautteestasi!
single
Kysy tekoälyä
Kysy tekoälyä
Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme
Awesome!
Completion rate improved to 3.33
Loops in Arrays
Pyyhkäise näyttääksesi valikon
Initialize the array declaring every time the single element can take a lot of your code. To go through the array you can use for
loops. Let’s print each element of the array using loops:
1234int numbers[5] = {1, 2, 3, 4, 5}; for (int i = 0; i <= 4; i++) { cout << numbers[i] << " "; }
In this code, the for loop goes through each element by its index and print in such a way the whole array.
The last index of the array is 4 since we have 5 elements. Keep in mind that the first element’s index is 0 that’s why the for loop initialized the variable
i
to0
.
We can also define each element in the loops (for example, by its index):
12345int numbers[5]; for (int i = 0; i <= 4; i++) { numbers[i] = i; cout << numbers[i] << " "; }
Swipe to start coding
Print each element of the array with its index.
- Define the array.
- Use
for
loop to go through array. - In output define the element and index in the gaps.
Ratkaisu
Kiitos palautteestasi!
Awesome!
Completion rate improved to 3.33single