While Loops

While Loops    

 An example of a program that requires a while statement is where I want to know the number of times a particular number can be divided by another, say 5. This is a typical problem in a math course. For such a case, there are infinite possible numbers so the only option is a program with a while loop.

In this program, the pseudo code is that while the number is more than 4, divide it by 5 and count the number of divisions. The program starts by getting the number, setting count to 0, dividing  number by 5 while it is greater than 4, increasing count by 1, and finally, ending.

There are two types of while loops applicable here namely the while-do loop and the do-while loop. (“The 2 Different,”) The first example is for a while-do loop, which evaluates whether a number is greater than 4. If this condition is true, the loop evaluates the expression. This process continues until the condition is false.

This is how the program looks:

Int count =0;

While (number >4)

{

Number =number/5

Count=count+1

}

In the do-while loop case, the expression is evaluated whether the condition is met or not. The loop then evaluates the expression, and repeats the process until the condition is false.

Int count=0

{

Number =number/5

Count=count+1

} while (number >4)

In this example, the two while loops give different results. In the do-while loop, there will be at least one count regardless of the number under evaluation.  This is unlike the while-do loop, which will give no count if the number is less or equal to 4.

References

The 2 Different Types Of While Loops. (n.d.). Retrieved from http://pic.dhe.ibm.com/infocenter/rsawshlp/v7r5m0/index.jsp?topic=/com.businessobjects.integration.eclipse.designer.doc/html/topic500.html

 

Latest Assignments