Problem: Write a method that takes in an integer 'num' and returns the sum of all integers between zero and num, up to and including num.
Game Plan:
>> function takes in one parameter, num.
>> for loop to go through each number below (and including) num (i--).
>> declare variable and set it equal to 0, will hold value from each iteration of loop.
>> return total sum
>> for loop to go through each number below (and including) num (i--).
>> declare variable and set it equal to 0, will hold value from each iteration of loop.
>> return total sum
Step 1:
function sumNums(num) {
}
}
Step 2:
function sumNums(num) {
var sum = 0;
}
var sum = 0;
}
Step 3:
function sumNums(num) {
var sum = 0;
for (var i = num; i > 0; i--) {
}
}
var sum = 0;
for (var i = num; i > 0; i--) {
}
}
Loop starts with num and stops when it is greater than 0, or 1.
Step 4:
function sumNums(num) {
var sum = 0;
for (var i = num; i > 0; i--) {
sum += i;
}
}
var sum = 0;
for (var i = num; i > 0; i--) {
sum += i;
}
}
You could also write sum = sum + i;
Step 5:
function sumNums(num) {
var sum = 0;
for (var i = num; i > 0; i--) {
sum += i;
}
return sum;
}
var sum = 0;
for (var i = num; i > 0; i--) {
sum += i;
}
return sum;
}
Check out past problems here:
No comments :
Post a Comment