Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Loops

 
Swati Samudra
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wan't to add integers 1 to 30. How can I do that in java.
I tried using for and while loop but failed to add the integers.
I only get 1,2,3 etc.But I wan't to add 1+2+3 etc.
It has to be
0 + 1 =1
1 + 2 =3
3 + 3 =6
6 + 4 =10
10 + 5 =15
15 + 6 =21 and so on
upto 30.
Please help me or tell me the other way I can do it in Java. Correct me if I am wrong.
 
YesYouretheOne
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First you can try killing a chicken with a bull's knife by using OOP, ie classes.
main()
{
printf(1+2+3+.....+30);
}
 
Angela Poynton
Ranch Hand
Posts: 3143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
YesYourTheOne .... please read here
about our naming policy ... your name does not comply please register again with a valid name.
Also I deleted your prvious post because it was rude and irrelevent to the discussion. Please keep your posts friendly, helpful and above all .. on topic!
 
Peter Tran
Bartender
Posts: 783
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Swati,
This will do what you want,
 
Swati Samudra
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Peter Tran,
I tried the coding. It's exactly what I was looking for but was not able to do the way you did it coz I was not using your first println statement:
System.out.println(sum+"+"+i+"=");
Thanks again.
[This message has been edited by Swati Samudra (edited January 18, 2001).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic