-2

I am trying to summation,where the baseNumber is from 1-4 and the expNumber is,i tried to use the for loop but isnt work and dont know where the problem is.Where the i shoudl get raised until 4 and so the basnum.

I tried to change places of number but what the weirdest thing is the sum get sometimes negative.

public static void main(String[] args) {

    int basenum = 1;
    int exp = 2;
    metoda(basenum,exp);

}
public static void metoda(int basenum,int exp) 
{
    for(int i = 1; i <= 4; i++) 
    {
        int sum = basenum * basenum;
        basenum++;
        System.out.println(sum);
    }


}

(Edited) now i get 1,4,9,25(those answer that i wanted) but now i want instead of all number i want to output the 1+4+9+25=30(the 30 as output).

DurimK
  • 1
  • 2
  • 3
    Integer overflow I guess. Your `basenum` is growing much faster than `i`. – PM 77-1 Sep 04 '19 at 22:05
  • 2
    You're trying to loop up to `basenum` but increasing `basenum` each turn (until it overflows). – khelwood Sep 04 '19 at 22:06
  • 1
    Run your code step-by-step under debug and see for yourself. – PM 77-1 Sep 04 '19 at 22:06
  • Debug your code. After the first iteration, `basenum` is 16, `i` is 2, less than `basenum`, so it will enter the loop again, at after it `basenum` is `2^8`, `i` is 3, then `basenum` is 2^16, and then an integer overflow happens, because 2^32 is bigger then Integer.MAX_VALUE, and it becomes 0. Now `i` is larger, you exit the loop and return 0. – Johannes Kuhn Sep 04 '19 at 22:12

1 Answers1

1

First of all you are using basenum instead of exp to define power

for(int i = 1; i <= basenum; i++)  // should be `i <= exp`

and because of this I guess you are exceeding the range of int having negative number as result. For more information take a look at this topic:

solution for this (after setting proper exp power value ofc) is to realise what operations do you want to allow and use either long or BigInteger to provide proper range

m.antkowicz
  • 13,268
  • 18
  • 37
  • [link]https://wikimedia.org/api/rest_v1/media/math/render/svg/14a5d4e143960f07dd1be548c683664975e536f8 That is actually what i tried to do. – DurimK Sep 05 '19 at 08:41