# How to find sum of first N numbers in swift ?

###### # Question 1: Find sum of first n numbers. Example :– n = 3 => 3+2+1 =6. We will use recursion to solve this problem.
``````func sumOfNNumber(number: Int, sum: inout Int) -> Int{
if number < 1 {
return sum
}
sum += number
sumOfNNumber(number: number - 1, sum: &sum)
return sum
}
var sumValue = 0
sumOfNNumber(number: 3, sum: &sumValue)
print(sumValue)

// Approach 2 sun of first n mumbers

func sumOfFirstNNumer(number: Int) -> Int {
if number == 0 { return 0 }
return number + sumOfFirstNNumer(number: number - 1)
}
print(sumOfFirstNNumer(number: 4))``````
###### # Question 2: Find sum of array elements using recursion approach :
``````func sumOfArray(inArray: [Int], arrayCount: inout Int, sum: inout Int)  {
if arrayCount <= 0 {
return
}
arrayCount -= 1
sum += inArray[arrayCount]
sumOfArray(inArray: inArray, arrayCount: &arrayCount, sum: &sum)
}

var arrayInput = [1,2,3,4,5,6]
var arrayCount = arrayInput.count
var sum = 0
sumOfArray(inArray: arrayInput, arrayCount: &arrayCount, sum: &sum)
print(sum)``````