Friday, March 9, 2012

While Loops

While Loops are extremely powerful. They allow you to continually do something WHILE something is true. The format for doing a while loop is as follows:

while(SOMETHINGisTrue){


}

or
while(somethingIsTrue)
{

}

Both are perfectly acceptable formats. Remember the if statement I discussed in my previous post? This is almost exactly the same. Let's say you have a value of x that is a negative number you want to be greater than zero. So with the if statement it would look something like this.

int x = -5;
if(x < 0){
x++;
}

System.out.println(x);(JAVA)

or

cout << x << endl;(C++)

Note. x++ is shorthand for x = x + 1.

Now an issue with this code is that it will only go one time. It would yield a result of -4. This doesn't quite complete our goal. So we want to use a while loop. The result of using a while loop would look like this.

int x = -5;
while(x < 0){
x++;
}
System.out.println(x);
or
cout << x << endl;

Now the way that this is computed is like this.

First thing that happens is that x is assigned the value of x. Following this we have a while loop statement. Remember that this works similar to how an if statement works.

So the second thing that happens is we check the value of x. We find that it is -5. The value is then checked to see if it is less than 0. We find that it is so we continue through our loop.

The x is then incremented. At the end bracket our program then does a check in the while loop to see if it is still true.

while(x < 0){
x++
}It checks right here. Right before it tries to exit the loop.

Then it finds that the statement is still true. So it repeats our third step of incrementing. It continues to do so until the value in the while statement is proven to be false.

Thank you for reading! As soon as I'm done explaining the lower level things in programming I'll start discussing the projects that I encounter and strategies I try to use to solve my problems.

No comments:

Post a Comment