Question

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.

Was it helpful?

Solution

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; 
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top