Jump to content

Welcome to Geeks to Go - Register now for FREE

Need help with your computer or device? Want to learn new tech skills? You're in the right place!
Geeks to Go is a friendly community of tech experts who can solve any problem you have. Just create a free account and post your question. Our volunteers will reply quickly and guide you through the steps. Don't let tech troubles stop you. Join Geeks to Go now and get the support you need!

How it Works Create Account
Photo

Converting Loop in Java


  • Please log in to reply

#1
rhymin

rhymin

    Member

  • Member
  • PipPipPip
  • 210 posts
How do you go about converting this code from for loop to while loop?

Here is a simple example of for loop:

class ArithmeticProgression
{
public static void main (String[] args)
{
int sum = 0;

for (int i = 1; i <= 1000; i++)
{
sum = sum + i;
System.out.println(Integer.toString(sum));
}
}
}
  • 0

Advertisements


#2
Spike

Spike

    nOoB

  • Member
  • PipPipPipPip
  • 1,357 posts

How do you go about converting this code from for loop to while loop?


Hey again rhymin,

A while loop is basically a loop that continues to loop because a certain condition proves to be true. Syntax: while (<condition>) {} So until the condition is proven to be not true, the loop will continue to execute over and over again. Remember when using a while loop the condition is checked before the code body is executed (In other words, do not confuse it with the "Do...While" loop)

A nice way of thinking of the for loop, is actually a while loop that contains a counter that gets incremented each time the loop executes. With this in mind the code for the corresponding for and while loops would look something like this:

FOR LOOP
for(int i = 0; i < 10; i++) {
// Code Body
}

WHILE LOOP
int i = 0;
while(i < 10) {
i++;
// Code Body
}

So in your case converting that for loop to a while loop wouldn't require an extra counter as your sum variable could be considered a closing condition. Here is the code for a while loop for your for loop:
int sum = 0;
int i = 1;

while(i <= 1000) {
sum = sum + i;
i++;
 System.out.println(Integer.toString(sum));
}
I hope that's what you were looking for and you have a better understanding of the two loops. Let us know if you require anything else Posted Image

Peace Out Posted Image
  • 0

#3
rhymin

rhymin

    Member

  • Topic Starter
  • Member
  • PipPipPip
  • 210 posts
Spike hacker, thank you very much for the quick reply and taking the time again (p.s. love the profile pic :) ).

That helps me understand loops better for sure. If I have another question about this with more difficult code, I will reply to this thread.

Thanks again!
  • 0






Similar Topics

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

As Featured On:

Microsoft Yahoo BBC MSN PC Magazine Washington Post HP