I would like to understand, why is it when I specify the number for the method to sum up numbers it returns 21, but when i enter the value through scanner it gives me the correct value. For example number 3 should be 1 + 2 + 3 = 6 but its giving me 21, any ideas thanks.
public class sumInt
{
public static void main(String[] args)
{
int i = sumInt(3);
int j = sumInt(10);
Scanner in = new Scanner (System.in);
System.out.println("Please enter posiutive integer: ");
int k = in.nextInt();
System.out.println(sumInt(i));
System.out.println(sumInt(j));
System.out.println(sumInt(k));
}
public static int sumInt(int n)
{
int sum = 0;
for (int i = 0; i <= n; i++)
{
sum += i;
}
return sum;
}
}
You are actually summing up to 6 for
i, your current code could also be written as:You’ll need to print out
idirectly instead of callingsumInton it again.