Write a program that finds the summation of every number from 1 to num. The number will always be a positive integer greater than 0. For example(Input -> Output): 2 -> 3 (1 + 2) 8 -> 36 (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8)
문제 풀이
var summation = function (num) {
let result = 0;
if(num > 0){
for(let i = 1 ; i <= num ; i++){
result += i;
}
}
return result;
}
num은 0보다 항상 커야한다고 조건이 작성되었기 때문에 if 구문을 이용해서 num이 0일 경우에 for 구문이 작동하도록 코드 작성
i는 1으로 선언하고, i가 (num)에 들어가는 변수보다 작거나 같아지면 반복문을 중단 후 i를 증감하도록 코드 작성
코드 비교
function summation(num) {
return num * (num + 1) / 2
}