What the hell is with arrays, I thought I Am doing that correctly already, but apparently not. It is one of these things I can't wrap my head around...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
int main()
{
int arraya[5];
int total{ 0 };
std::cin >> arraya[5];
// calculate total
for (int i = 0; i < 5; i++) {
total += arraya[i];
}
std::cout << total;
}
I thought that when I declare array of [5] it will go from 0-4 indices. So when I create for loop and set condition i < 5. It will start from 0 run once, then increment 1, so after 5th run [4] index, it will get value 5, but won't run again because i must be lower than 5!
I checked this site and it is same here, I also tried i < 4 and i < 6 doesn't work either, but I Am pretty sure i < 5 is correct! What I Am doing wrong? Again don't understand why it doesn't work!
a couple of points:
1: total should be initialized like this:
int total = 0;
instead of with the {}
use the brackets when initializing values to an array, like this:
int arraya[5] { 1, 2, 3, 4, 5 };
2: assuming you are trying to initialize the indices of the array from user input and then print the sum you can use code that looks like this:
#include <iostream>
1 2 3 4 5 6 7 8 9
...
// initialize aaraya and sum total from user input
for (int i = 0; i < 5; i++) {
std::cin >> arraya[i];
total += arraya[i];
}
//print total
std::cout << total;
1). No. The 'modern' way to initialise is to use {} or {a}. If {} is used than a default value for the type is used to initialise. Note that {} doesn't do a narrowing conversion whereas = does. But really this is a preference (unless you want an initialisation to the type default value).
for (int i { }; i < 5; i++)
{
total += arraya[i];
}
It is still possible to go out of bounds with the operator[] indexing. Modern C++ has range-based for loops (AKA for-each loops). Works with C++ containers and regular arrays as long as the array hasn't decayed to a pointer (as happens when passing it to a function):