• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Crazy question

 
Rachil Chandran
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As the subject line indicates, this is probably a very crazy question. But here goes...

I have the following code:

int a = 0;
for( int i = 0; i<10; i++)
{
print("Iteration number : "+i);
a += i;
}
print ("a = "+a);

The output will be

Iteration number : 0
Iteration number : 1
....
...
Iteration number : 9
a = 45

Is there some way I could get the "a =" line to be printed before the Iteration lines without using another loop?

i.e. the output should look like this,

a = 45
Iteration number : 0
Iteration number : 1
....
...
Iteration number : 9
 
Mir Ciu
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, it is possible, but you need a JVM with pre-cognition capabilities. I have one for sale, contact me for the payment details.
 
Chetan Parekh
Ranch Hand
Posts: 3640
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Rachil Chandran
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Chetan. Exactly what I wanted.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12144
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
or, to avoid all that nasty string concatenation, do this:

a = (9 * 10) / 2;

or in general, if you are summing up the numbers from 0 to n,

a = (n * (n+1)) / 2;
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic