+ 1
Please answer this i want to know answer
int arr[] = {11, 35, 62, 555, 989}; int sum = 0; for (int x = 0; x < 5; x++) { sum += arr[x]; } cout << sum << endl; //Outputs 1652 How this output will come can anyone tell me
2 Respostas
+ 3
"arr" is array containing integer values. every value of array has his index starting from zero [0]
arr[0] is 11, arr[1] is 35 etc.
so sum = 0 and x = 0,
at first iteration of for it looks like this
sum = sum + arr[0] = 0 + 11 = 11
at second time x increments by 1 for the second loop, so x = 1 and it < 5, loop continues
sum = sum + arr[1] = 11 + 35 = 46 ... etc..
at the end we get the sum of all numbers in array.
P.S. val += 1 is a short way of val = val + 1
+ 2
I think what you really want to do is this:
#include <iostream>
#include <array>
int main()
{
std::array<int, 5> arr = { 11, 35, 62, 555, 989 };
int sum{};
for (const int x : arr)
sum += x;
std::cout << sum << std::endl;
}
Tell me if you don't understand something.