1. Sums of sequences

VCMNA254: level 7: Design and implement mathematical algorithms using a simple general purpose programming language
  • finding the sum of a set of consecutive numbers using a loop structure


1.1. Sum of consecutive numbers

1.1.1. Listed numbers

The code below uses a for loop which iterates over the nums list.
Each number, num, in the list, nums, is added to the sum.
1nums = [1, 2, 3, 4, 5]
2sum = 0
3for num in nums:
4    sum += num
5print(sum)
Pseudocode:
nums ← [1, 2, 3, 4, 5]
sum ← 0
for each num in nums
sum ← sum + num
print sum

1.1.2. Range from 0

The code below uses the range function to provide a list of integers from 0 to 5.
1nums = list(range(6))
2print(nums)
3sum = 0
4for num in nums:
5    sum += num
6print(sum)
Pseudocode:
nums ← list from 0 to 5
print nums
sum ← 0
for each num in nums
sum ← sum + num
print sum

1.1.3. Range: first and last

The code below uses the range function to provide a list of integers from start_num to end_num.
1start_num = 4
2end_num = 12
3nums = list(range(start_num, end_num + 1))
4print(nums)
5sum = 0
6for num in nums:
7    sum += num
8print(sum)
Pseudocode:
start_num ← 4
end_num ← 12
nums ← list of integers from start_num to end_num
print nums
sum ← 0
for each num in nums
sum ← sum + num
print sum

1.1.4. Range: step size

The code below uses the range function to provide a list of integers from start_num to end_num in steps of step_size.
1start_num = 4
2end_num = 12
3step_size = 2
4nums = list(range(start_num, end_num + 1, step_size))
5print(nums)
6sum = 0
7for num in nums:
8    sum += num
9print(sum)
Pseudocode:
start_num ← 4
end_num ← 12
step_size ← 2
nums ← list of integers from start_num to end_num in steps of step_size
print nums
sum ← 0
for each num in nums
sum ← sum + num
print sum

1.1.5. Arithmetic sequence formula 1

One formula for the sum of a sequence of numbers with the same difference between them is:
S = n/2[2a + (n-1)d]
where
S is the sum
n is the number of numbers
a is the start number
d is the difference between numbers
1# S = n/2[2a + (n-1)d]
2# 
3a = 4
4n = 5
5d = 2
6sum = (n/2) * (2*a + (n-1)*d)
7print(sum)
Pseudocode:
a ← 4
n ← 5
d ← 2
sum ← (n/2) * (2*a + (n-1)*d)
print sum

1.1.6. Arithmetic sequence formula 2

Another formula for the sum of a sequence of numbers with the same difference between them is:
S = n/2[a + l]
where
S is the sum
n is the number of numbers
a is the start number
l is the last number
1a = 4
2n = 5
3l = 12
4sum = (n/2) * (a + l)
5print(sum)
Pseudocode:
a ← 4
n ← 5
l ← 12
sum ← (n/2) * (a + l)
print sum