In programming, a loop is used to repeat a block of code until the specified condition is met.
While Loops
The while
loops through a block of code as long as a specified condition is true
:
Syntax
How while loop works?
- The
while
loop evaluates thetestExpression
inside the parentheses()
. - If
testExpression
is true, statements inside the body ofwhile
loop are executed. Then,testExpression
is evaluated again. - The process goes on until
testExpression
is evaluated to false. - If
testExpression
is false, the loop terminates (ends).
Note: testExpression
it’s made by C Comparison Operators and C Logical Operators.
For loop Flowchart
Example:
Output: 1 2 3 4 5
Do…While Loop
The body of do...while
loop is executed at least once.
Only then, the test expression is evaluated.
Syntax
How do…while loop works?
- The body of
do...while
loop is executed once. Only then, thetestExpression
is evaluated. - If
testExpression
is true, the body of the loop is executed again andtestExpression
is evaluated once more. - This process goes on until
testExpression
becomes false. - If
testExpression
is false, the loop ends.
Example:
Output:
Enter a number: 1.5
Enter a number: 2.4
Enter a number: -3.4
Enter a number: 4.2
Enter a number: 0
Sum = 4.70