Quote:
|
Write a program that would input a positive integer N and then outputs the sum of the squares of the integers from 1 to N. For example, if the input is 5 the output should be 55. (that is 1^2 + 2^2 + 3^2 + 4^2 + 5^2 = 55)
|
hmm...
so...
Get Input
You could do this in a loop
asm style:
.WHILE (input > 0)
mov ecx, input ;e.g. 5
imul ecx, ecx ;5 * 5 (square)
sub input, 1
add output, ecx
.ENDW
not too certain on c++ syntax.
but the algorithm would be:
Get Input
Store Input into a Variable (e.g. Input)
Create a loop that loops while Input > 0
Inside loop have it multiply current value stored in Input by itself (to square it) and then add that to an output variable. Then decrement value stored in Input.
Then when loop is exited, output the # that's currently in the output variable.
Code:
'Name: Sean
'Date: October 11, 2008
'Description: Write a program that would input a positive integer N and then outputs the sum of the squares of the integers
' from 1 to N. For example, if the input is 5 the output should be 55. (that is 1^2 + 2^2 + 3^2 + 4^2 + 5^2 = 55)
Option Explicit
Sub GzNProblem()
Dim InputVar As Long
Dim OutputVar As Long
Dim OrigInput As Long
InputVar = InputBox(\"Enter a positive integer\", \"Get positive integer\")
OrigInput = InputVar
If InputVar >= 0 Then
Do Until (InputVar = 0)
OutputVar = OutputVar + (InputVar * InputVar)
InputVar = InputVar - 1
Loop
MsgBox (\"You entered: \" & OrigInput & \". The result is: \" & OutputVar), 32, \"Result\"
Else
MsgBox (\"You entered a negative integer! Only enter a positive integer.\"), 32, \"Error\"
End If
End Sub
This would be the VB code for your problem. Just tested it out, works. (the random slashes in the code were added by GzN - remove them if you want to compile it).