0

I'm trying to write a program in java that displays the result of the sum of n numbers and its exponents, while the next number and exponent in the sample is (n-1) until it gets to 0. I hope I'm explaining myself. An example:

If I ask the user for the number 3, the program would have to do this: 3^3 + 2^2 + 1^1 = 32

I need to use cycles, so I can't use any kind of function even if it's more efficient.

This is what I have so far:

public static void main(String[] args) 
{
    int n,i,j,s=0,exp;

    Scanner r = new Scanner (System.in);

    System.out.println("Value of n: ");
    n = r.nextInt();

    for(i=1;i<=n;i++)
    {
        s = 0;

        for(j=1;j<=i;j++)
        {
            exp = n * n;
            s = s + exp;
        }
    }

    System.out.println("Total: "+s);
}

Any tips on how to get this to work? I can't wrap my head around this.

sodah
  • 3
  • 1
  • 2
  • 1
    what's not working? what do you expect to get printed, what gets printed instead? – iluxa Oct 29 '13 at 02:15
  • You should step back and go line by line over what you've written. You don't need two loops, and ask yourself what `exp = n * n` does. – lealand Oct 29 '13 at 02:17
  • As @iluxa has mentioned, please update the question and add the problem you are having to help us to help you ;) – Ean V Oct 29 '13 at 02:29

1 Answers1

2

The logic in your for-loop is incorrect.

Below is an example to make it work;

Variable i in outer loop is to determine what int values to handle, such as 1, 2, 3 if n=3

The inner loop is to handle pow expression for a given i, such as 1^1, 2^2 and 3^3 as you mentioned.

        for(i=1;i<=n;i++)
        {
            exp = 1;
            for(j=1;j<=i;j++)
            {
                exp *=i;
            }
           s+=exp; 
        }
Mengjun
  • 3,159
  • 1
  • 15
  • 21