Last active
August 29, 2015 14:21
-
-
Save iidaatcnt/3224731b1ec227199e02 to your computer and use it in GitHub Desktop.
for文、while文、再帰呼び出しの3パターンでリストの値を合計せよ。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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