help with basic sum calculator in java
Ok so I am trying to make a sum calculator that calculates the following:
∑ 2n+1
In this problem the user inputs the upper limit of the program and the lower limit is always 0.
This is what I got:
import java.io.*;
public class sum
{
public static void main(String args[]) throws IOException
{
BufferedReader keybd = new BufferedReader(new InputStreamReader(System.in));
int n;
System.out.print("Input the upper limit: ");
n = Integer.parseInt(keybd.readLine());
int calc=2*n+1;
for (int i=0; i<=n; i++)
{
calc=calc+i;
}
System.out.println(calc);
}
}
The program works (sort of). When I do test runs it gives me wrong answers, when n >= 2. When I input 0 or 1 for upper limit it gives me correct answer, but when the upper limit is greater than or equal to 2, the answer is wrong.
For instance when I run the program and input 2 for the upper limit, the answer it gives me is 8 ...
but when i do the sum by hand the correct answer is 9:
[2(0)+1] + [2(1)+1] + [2(2)+1]
= 1 + 3 + 5
= 9
This problem has been bugging me for several hours. Any help appreciated thanks! :)