Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

C 

C++ Array Exercise

Sum Greater Than Five
Write a function that returns the sum of elements greater than 5, in the given array.

Examples
sumFive([1, 5, 20, 30, 4, 9, 18]) ➞ 77

sumFive([1, 2, 3, 4]) ➞ 0

sumFive([10, 12, 28, 47, 55, 100]) ➞ 252

Notes
Find all the elements greater than 5, not the elements greater than or equal to 5.


------------------
The above is the exercise. I don't know where I'm screwing up along the way. I though I was expected to have a value which would be the sum of every value above 5 that my for loop counts through, with the max size of the array being 7? Trying with a arr.sizeof() as a condition within the for loop brings errors still.

My closest work:

int sumFive(std::vector<int> arr) {
int i;
int addIt;
for (int i = 0; i <=7 ; i++){
if (i >5){addIt = addIt + i;}

}
return addIt;

}


here is the base setup for the work:

int sumFive(std::vector<int> arr) {}




Help would be appreciated! This problem shouldn't be too hard but I've been having problems with counting and grabbing values through/out of an array!
First of all I want to tell you that, you didn't assign any value to addit variable, so by default it has some garbage value. You need to assign it to 0 in this case. Second, why did you hardcode the condition i<=7 in for loop when you're passing an array? You should get the length of the array and loop through all the elements. Tell me if this helps.
Hello, Djangoo would love to solve your coding problems with Python.
Programming service | Automating stuff with Python | Homework
(Jun 10, 2021 07:33 PM)James Wrote:  this works fine for me - http://cpp.sh/7bx2px

thank you!

(Jun 10, 2021 07:24 PM)Djangoo Wrote:  First of all I want to tell you that, you didn't assign any value to addit variable, so by default it has some garbage value. You need to assign it to 0 in this case. Second, why did you hardcode the condition i<=7 in for loop when you're passing an array? You should get the length of the array and loop through all the elements. Tell me if this helps.

yes i didn't know that addit wouldve become some garbo value. thank you


Possibly Related Threads...
Thread / Author Replies Views Last Post
[Java] by minerwOct 5, 2020 06:44 AM 2 302 Oct 5, 2020 06:44 AM
Last Post: minerw
[Java] by bohhSep 30, 2020 12:53 PM 3 281 Sep 30, 2020 12:53 PM
Last Post: G.P.D.
[C] by gurlhackerclubMay 19, 2020 05:18 PM 8 251 May 19, 2020 05:18 PM
Last Post: k1r3n