Assume the vector v exists Write a statement using a for loo

Assume the vector v exists. Write a statement using a for loop that will compute the sum of the elements of v and stores the result in variable r.

Solution

r = 0;

for(int i = 0; i < v.size(); i++) //This loop will run from the first element to the last element of the vector.

r += v.at(i); //Every element is added to the value r.

//Therefore, the sum of elements of v is stored in the variable r.

The other way we can do the same summation using iterator object is:

r = 0;

for(iterator it = v.begin(); it != v.end(); it++)

r += *it;

//Will do the same summation but this time using iterators.

Assume the vector v exists. Write a statement using a for loop that will compute the sum of the elements of v and stores the result in variable r.Solutionr = 0;

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site