What is a While loop?
A while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The while loop can be thought of as a repeating if statement.
The while construct consists of a block of code and a condition/expression. The condition/expression is evaluated, and if the condition/expression is true, the code within the block is executed. This repeats until the condition/expression becomes false. Because the while loop checks the condition/expression before the block is executed, the control structure is often also known as a pre-test loop.
What they do is simply do a test like an if-statement, but instead of running the code block once, they jump back to the "top" where the while is, and repeat. A while-loop runs until the expression is False.
What does the while loop do?
A "While" Loop is used to repeat a specific block of code an unknown number of times, until a condition is met. For example, if we want to ask a user for a number between 1 and 10, we don't know how many times the user may enter a larger number, so we keep asking "while the number is not between 1 and 10".
For example, say we want to know how many times a given number can be divided by 2 before it is less than or equal to 1. If we know a specific number, such as 32, we can say 5 times, but for a given symbolic variable "NUMBER" which represents any number in the world, how many times is not known a priori (before hand). In this case, we could use a while loop to determine that answer:
The "pseudocode" for such an algorithm is: while the number is bigger than one keep dividing it by two. additionally, keep a count of how many times we do the division.
Therefore, the while loop;
Here is a mathlab example that can find the factorials of 10. This means 10x9x8x7x6x5x4x3x2x1
n = 10;
n! = 3628800
Let n be 10
MAURICE NYAMOTI is a high school teacher and has passion in helping students improve grades
Form 1 to Form 4 kcse past papers latest
Pre-Primary 1 to Std 8 Latest KCPE Past papers
KNEC PAPERS FOR COLLEGE
Contact us anytime
Trusted by over 500 schools and colleges
The list keeps growing 'day in, day out' ... List of Schools in Kenya