开发者

Java: Calculate for loop

I've now googled around and tried various methods myself without any success. So to the problem, I've got this loop, I type in a number "n" ex. 10. Then the program counts from 1 to 10. This is the loop I'm using.

n = Keyboard.readInt();
for(int e = 1; e <=n; e++)          
System.out.println(e);  

That works fine, but now I want to calculate the numbers that has been shown in loop so..It would be 1+2+3+4+5+6+7+8+9+10 (If 'n' was chosen as number 10) 开发者_C百科and it should give the calculation of that so it would say 1+2+3+4+5+6+7+8+9+10 = 55.

Would be great if anyone here could help me.

Thanks in advance,

Michael.


You could do it the hard way or the easy way:

  1. The hard way: Keep a running sum and add to it inside the loop.

  2. The easy way: Notice that the sum you're looking for equals n*(n+1)/2 (which is easy to prove).


StringBuilder buffer = new StringBuilder();
int n = Keyboard.readInt();
int sum = 0;

for ( int e = 1; e <=n; e++ )
{
  buffer.append( "+ " + e );
  sum += e;
}

System.out.println( buffer.substring( 2 ) + " = " + sum ); 


Do it like that:

   public static void main(String[] args) {
        int n = 10;
        int sum = 0;
        for(int e = 1; e <=n; e++)          
            sum = sum + e;
        System.out.println(sum);
    }


int sum = 0;

for(int e = 1; e <=n; e++)
{
    sum += e;
}

System.out.println(sum);


Use another variable to accumulate the results.


I feel like spoon-feeding, so here's the code:

public static void main(String args[]) {
    int n = Keyboard.readInt();
    int total = 0;
    for (int i = 1; i <= n; i++)
        total += i;
    System.out.println(total);
}


Try this:

n = Keyboard.readInt();
int total = 0;
StringBuilder arith = new StringBuilder();

for(int e = 1; e <=n; e++) { 
   total += e;
   arith.append(e + (e < n? "+" : ""));
}

arith.append("=" + total);
System.out.println(arith.toString()); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜