Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Loops in Arrays | Intro to Arrays
Introduction to C++ | Mobile-Friendly

bookLoops 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:

1234
int numbers[5] = {1, 2, 3, 4, 5}; for (int i = 0; i <= 4; i++) { &nbsp;&nbsp;&nbsp;&nbsp; cout << numbers[i] << " "; }
copy

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 to 0.

We can also define each element in the loops (for example, by its index):

12345
int numbers[5]; for (int i = 0; i <= 4; i++) { &nbsp;&nbsp;&nbsp;&nbsp; numbers[i] = i; &nbsp;&nbsp;&nbsp;&nbsp; cout << numbers[i] << " "; }
copy
question mark

Choose the for loop to go though the array of 6 elements.

Select the correct answer

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 5. Kapitel 2

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Suggested prompts:

Ställ mig frågor om detta ämne

Sammanfatta detta kapitel

Visa verkliga exempel

Awesome!

Completion rate improved to 3.7

bookLoops in Arrays

Svep för att visa menyn

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:

1234
int numbers[5] = {1, 2, 3, 4, 5}; for (int i = 0; i <= 4; i++) { &nbsp;&nbsp;&nbsp;&nbsp; cout << numbers[i] << " "; }
copy

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 to 0.

We can also define each element in the loops (for example, by its index):

12345
int numbers[5]; for (int i = 0; i <= 4; i++) { &nbsp;&nbsp;&nbsp;&nbsp; numbers[i] = i; &nbsp;&nbsp;&nbsp;&nbsp; cout << numbers[i] << " "; }
copy
question mark

Choose the for loop to go though the array of 6 elements.

Select the correct answer

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 5. Kapitel 2
some-alt