'Visual Basic loop sum of integers ^ 2 till user input. power of 2
I need help with one simple task:
Input an integer number n and output the sum: 1 + 2^2 + 3^2 + ... + n^2. Use input validation for n to be positive. My code does not work and till now is:
Sub Main()
Dim inputNumber As Integer
Console.WriteLine("Please enter a positive number.")
inputNumber = Console.ReadLine()
If inputNumber <= 0 Then
Console.WriteLine("Please use only positive numbers > 0 !")
End If
Dim sum As Integer
Dim i As Integer = 1
For i = 1 To i <= inputNumber
sum = sum + (i * i)
i = i + 1
Next
Console.WriteLine(sum)
Console.ReadLine()
End Sub
Solution 1:[1]
Try these changes:
Dim inputNumber as Long ' not Integer. Also change sum, i.
...
inputNumber = CLng(Console.ReadLine) ' make it a number, not a string
...
Dim sum as Long ' yum
dim i as Long ' don't assign it here
for i = 1 to inputNumber ' don't use "<=" in a for loop
...
' i = i+1 ' Don't increment i within the loop, since the loop does that for you.
Solution 2:[2]
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim Input As Integer Input = TextBox1.Text
Dim i As Integer
i = 0
Dim x As Integer
x = 0
Dim y As Integer
y = 0
For a = 1 To Input
y = Math.Pow(a, (Input - i))
x = Math.Pow(a, (Input - i)) + x
i = i + 1
Next
Label1.Text = x
End Sub
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | cxw |
Solution 2 | Muhammad Azib Ali |