This week's book giveaway is in the Beginning Java forum.
We're giving away four copies of Get Programming with Java (MEAP only) and have Peggy Fisher on-line!
See this thread for details.
Win a copy of Get Programming with Java (MEAP only) this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Bear Bibeault
  • Knute Snortum
  • Liutauras Vilda
Sheriffs:
  • Tim Cooke
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Ron McLeod
  • Ganesh Patekar
  • salvin francis
Bartenders:
  • Tim Holloway
  • Carey Brown
  • Stephan van Hulst

Crazy question  RSS feed

 
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
 
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.
 
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.
 
lowercase baba
Posts: 12628
50
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;
 
I was born with webbed fish toes. This tiny ad is my only friend:
RavenDB is an Open Source NoSQL Database that’s fully transactional (ACID) across your database
https://coderanch.com/t/704633/RavenDB-Open-Source-NoSQL-Database
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!