derpyherp
derpyherp

Reputation: 525

Java does exponent instead of multiply

public class tester
{
  public static void main(String args[])
  {
    int n = 0;
    int sum = 0;
    for(n = 3;n<=24;n=( 2 * n))
    {
      sum = sum + n;
      System.out.println(sum);
    }
  }
}

could someone please explain to me why in this for loop it reads n = n*2 as an exponent and not multiplication

Upvotes: 0

Views: 124

Answers (3)

Andrew Fabian
Andrew Fabian

Reputation: 35

In a for loop: you set a value, declare a rule, and set a function to be preformed while said rule is true. In your case, you are adding 'n' to your sum, while n is less than 24, every time multiplying n by 2. The asterisk is used for strictly multiplication in java.

Taking a shot in the dark but did you mean to do:

for(n = 3;n<=24;n=( 2 * n)){
   sum = n;
   System.out.println(sum);
}

if not, a suggestion is to use += or -= like so:

sum += n;
sun -= n;

Upvotes: 0

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44448

You're not calculating the exponent per sé, you're just calculating it wrongly which results in the exponent.

n will be

3, 6, 12, etc

but you use sum

sum = sum + n;

which will basically be

sum = 0 + 3 => 3
sum = 3 + 6 => 9
sum = 9 + 12 => 21
etc

Upvotes: 1

Jon Newmuis
Jon Newmuis

Reputation: 26530

It doesn't. This outputs:

3
9
21
45

Because:

Iteration       n                 sum 
    1     n = 3            sum = 0 + 3 = 3
    2     n = 2 * 3 = 6    sum = 3 + 6 = 9
    3     n = 2 * 6 = 12   sum = 9 + 12 = 21
    4     n = 2 * 12 = 24  sum = 21 + 24 = 45
    5     n = 2 * 24 = 48  (break)

Notice how in each iteration, n is just multiplied by 2, not calculated as an exponent.

Upvotes: 2

Related Questions