In: Computer Science
Explain briefly what the following algorithm does and write the output below: (5 credits)
Step 1: Set sum equal to 0, set n equal to 1
Step 2: Repeat steps 3, 4 and 5 until sum > 60
Step 3: Set sum equal to sum + n2
Step 4: Replace n with n +1
Step 5: Print n and sum on a new line
Step 6: Stop
Show output:
This algorithm is calculating the sum of square of numbers[ 1,2,3... ] and printing that number along with the sum before that number.
Algorithm Dry Run Explanation:
Step 1: sum=0, n=1
Step 2: sum<60 return True
Step 3: sum = sum+n2 =0 + (1)2 = 1
Step 4: n = n+1 = 1+1=2
Step 5: print n and sum, 2 1 will be printed
Step 2: sum<60 return True
Step 3: sum = sum+n2 =1 + (2)2 = 5
Step 4: n = n+1 = 2+1=3
Step 5: print n and sum, 3 5 will be printed
Step 2: sum<60 , 5<60 return True
Step 3: sum = sum+n2 =5 + (3)2 = 5+9 = 14
Step 4: n = n+1 = 3+1=4
Step 5: print n and sum, 4 14 will be printed
Step 2: sum<60, 14<60 return True
Step 3: sum = sum+n2 =14 + (4)2 = 14+16=30
Step 4: n = n+1 = 4+1=5
Step 5: print n and sum, 5 30 will be printed
Step 2: sum<60 return True
Step 3: sum = sum+n2 =30 + (5)2 = 30+25=55
Step 4: n = n+1 = 5+1=6
Step 5: print n and sum, 6 55 will be printed
Step 2: sum<60 , 55<60 return True
Step 3: sum = sum+n2 =55 + (6)2 = 55+36 = 91
Step 4: n = n+1 = 6+1=7
Step 5: print n and sum, 7 91 will be printed
Step 2: sum<60 , 91<60 return False
Step6: Stop
OUTPUT:
2 1
3 5
4 14
5 30
6 55
7 91