We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Practice
- Algorithms
- Warmup
- Simple Array Sum
- Discussions
Simple Array Sum
Simple Array Sum
3rdboss + 0 comments This sh*t ain't for beginners like myself
monsterousopera1 + 0 comments They need to give you feedback for how these test cases work... Its like why didn't it pass test 2? also if they want it coded a specific way, why don't they tell you what way they want it rather then setting you losse then saying, "nope! thats not what I wanted. not goting to tell you why... just know that its worng..." I give up!
eandino + 0 comments Here is a simple solution I came up with.
static int simpleArraySum(int n, int[] ar) { int sum = 0; for(int count = 0; count < ar.length; count++) { sum = sum + ar[count]; } return sum; }
Steps: 1.) You declare a variable to hold the sum. 2.) Give that variable an initial value. 3.) Now do a for loop to pass through every single element in the array. 4.) The first statement in the for loop sets an initial value to its variable count (can be named anything), int count = 0. The second piece of code (count < ar.length) sets a condition for which the loop will continue to run through the array, in this case, it will run until the end of the array. The third piece of code (count++) will add one to the counter which is the code that makes the counter pass through the array by increments of one (step by step). 5.) The code inside the brackets {sum = sum + ar[count]} will take the initial value of sum and add all of the values found inside the array to it. 6.) Finally the return statement will simply print out the new values of sum given by the for loop. *I hope this helps everyone, let me know if it does!
dmirzacarolina + 0 comments JavaScript solution:
function simpleArraySum(ar) { var count = 0; for (var i = 0; i < ar.length; i++) { count += ar[i]; } return count; }
Then I made it a one-liner using reduce:
function simpleArraySum(ar) { return ar.reduce((a, b) => a + b) }
daz1184 + 0 comments C# working example.
static int simpleArraySum(int[] ar) { int total = 0; foreach (int n in ar) { total += n; } return total; }
Load more conversations
Sort 2380 Discussions, By:
Please Login in order to post a comment