Programming Problems every Developer should know how to solve

Great for testing yourself and stretching your brain. Take the opportunity to to solve them with a different programming language
Source: Five programming problems every Software Engineer should be able to solve in less than 1 hour

Write three functions that compute the sum of the numbers in a given list using...

  1. for-loop
  2. while-loop
  3. recursion
// Implemented in Swift (2.0)
func computeSumForLoop(numbers: [Int]) -> Int {
    var totalSum = 0

    for i in 0...numbers.count - 1 {
        totalSum += numbers[i]
    }

    return totalSum
}

func computeSumWhileLoop(numbers: [Int]) -> Int {
    var totalSum = 0
    var i = 0
    while i < numbers.count {
        totalSum += numbers[i]
        i += 1
    }

    return totalSum
}

func computeSumRecursion(numbers: [Int], noOfElements: Int, index: Int) -> Int {

    if index == noOfElements {
        return 0
    }

    return numbers[index] + computeSumRecursion(numbers, noOfElements: noOfElements, index: index + 1)
}

print("For Loop: \(computeSumForLoop(numbers))")
print("While Loop: \(computeSumWhileLoop(numbers))")
print("Recusive Loop: \(computeSumRecursion(numbers, noOfElements: numbers.count, index: 0))")
										

First, solve the problem. Then, write the code

John Johnson