Please help me to write the code for problem 2, make sure it work Problem 2: The
ID: 3591847 • Letter: P
Question
Please help me to write the code for problem 2, make sure it work
Problem 2: The following code is an example of a FOR loop. The function finds the sum from 1 + 2 + 3 + … x, where x is the input value. Paste the code below into Excel and modify the code so that it instead it adds 1^2 + 2^2 + 3^2 + … x^2. Extra credit: Have it check to make sure that x is a positive integer before it does the loop, and tell the user that the input is invalid. Paste your updated code here.
Function LoopSum(x)
'this function takes a positive integer input and finds the sum from 1 to that positive integer 'for example, for input x = 5, the output will be 1+2+3+4+5, that is it will output the number 15.
LoopSum = 0 'start the output variable with a value of 0
For k = 1 To x
LoopSum = LoopSum + k 'each time it goes through the for loop, it adds the current value of k
Next k
End Function
Explanation / Answer
Function LoopSum(x)
'this function takes a positive integer input and finds the sum of squares from 1 to that positive integer 'for example, for input x = 5, the output will be 1+2+3+4+5, that is it will output the number 15.
LoopSum = 0 'start the output variable with a value of 0
If x < 0 Then
MsgBox "Invalid argument for LoopSum. Enter only positive integers"
Else
For k = 1 To x
LoopSum = LoopSum + k ^ 2 'each time it goes through the for loop, it adds the current value of k^2
Next k
End If
End Function