aspose file tools*
The moose likes Programming Diversions and the fly likes Crazy question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Other » Programming Diversions
Bookmark "Crazy question" Watch "Crazy question" New topic
Author

Crazy question

Rachil Chandran
Ranch Hand

Joined: Mar 05, 2006
Posts: 67
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


SCJP2 96%
Mir Ciu
Greenhorn

Joined: Oct 02, 2006
Posts: 1
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

Joined: Sep 16, 2004
Posts: 3636


My blood is tested +ve for Java.
Rachil Chandran
Ranch Hand

Joined: Mar 05, 2006
Posts: 67
Thanks Chetan. Exactly what I wanted.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11417
    
  16

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;


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
 
Don't get me started about those stupid light bulbs.
 
subject: Crazy question