Skip to content

Instantly share code, notes, and snippets.

@iidaatcnt
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iidaatcnt/3224731b1ec227199e02 to your computer and use it in GitHub Desktop.
Save iidaatcnt/3224731b1ec227199e02 to your computer and use it in GitHub Desktop.
for文、while文、再帰呼び出しの3パターンでリストの値を合計せよ。
#!/usr/bin/env xcrun swift
// For文
func ForProcess(nums: [Int]) -> Int {
var s = 0
for i in nums {
s += i
}
return s
}
// While文
func WhileProcess(nums: [Int]) -> Int {
var s = 0
var i = 0
while ( i < 10 ) {
s += nums[i]
i++
}
return s
}
// 再帰呼び出し
func RecursivePesrocess(var nums:[Int]) -> Int {
if nums.count == 1 {
return nums[0]
} else {
nums[0] += nums[1]
nums.removeAtIndex(1)
return ( RecursivePesrocess(nums) )
}
}
var sum = 0
let evenNumbers = [10,9,8,7,6,5,4,3,2,1]
sum = ForProcess(evenNumbers)
println("For= \(sum)")
sum = WhileProcess(evenNumbers)
println("While= \(sum)")
sum = RecursivePesrocess(evenNumbers)
println("Recursive = \(sum)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment