![]() |
|
[C] C++ Array Exercise - Printable Version +- Hack Forums (https://hackforums.net) +-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444) +--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151) +---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118) +---- Thread: [C] C++ Array Exercise (/showthread.php?tid=6158300) |
C++ Array Exercise - 1337ITWizKid - Jun 10, 2021 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! RE: C++ Array Exercise - Djangoo - Jun 10, 2021 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. RE: C++ Array Exercise - 1337ITWizKid - Jun 10, 2021 (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 |