Monday, January 27, 2014

Control Structures - Loops (while)

If you guys haven't read the previous posts linked with this post, please read them first and come back here :)
#1 Control Structures - If, If else, If else If
#2 Control Structures - Loops (for)

Ok, now you have a basic idea about what a loop is, and the for loop too. Now I will describe what is a while loop. While loop is used when we don't know the number of iterations in the loop. And the minimum number of iterations is zero.

This loop also works a bit similar to the for loop. Below I have an example code and the syntax.

while(<condition>)
{
   <statements>
}

Finite loop example:

int i = 0;
while(i<5)
{
   System.out.println("This is i: "+i"); //prints i when it is less than 5
}

Infinite Loop example

while(true)
{
   System.out.println("This will run forever!!");
}
While loop has the same arguments as in the for loop. But is has arranged in a different way. You will see that the starting index is not specified in the syntax, you can use that if you need a starting index for your code.

This works a bit simpler than the for loop. This only checks the condition, if the condition returns a true value, the code written between the curly brackets will run.
Resources: stepbystep.com

No comments:

Post a Comment

Its all about friendly scientific conversation here at One Science Fact. I'd love to hear your thoughts about this blog.

Be sure to check back again because i always reply to every single comment