Jump to content

Welcome to Geeks to Go - Register now for FREE

Geeks To Go is a helpful hub, where thousands of volunteer geeks quickly serve friendly answers and support. Check out the forums and get free advice from the experts. Register now to gain access to all of our features, it's FREE and only takes one minute. Once registered and logged in, you will be able to create topics, post replies to existing threads, give reputation to your fellow members, get your own private messenger, post status updates, manage your profile and so much more.

Create Account How it Works
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,355 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