C++ while Loop(How while loop works?)



In computer programming, loop repeats a certain block of code until some end condition is met.
There are 3 type of loops in C++ Programming:
  • while Loop.

C++ while Loop

The syntax of a while loop is:
while (testExpression) 
{
     // codes  
}
where test expression is checked on each entry of the while loop.

How while loop works?

  • The while loop evaluates the test expression.
  • If the test expression is true, codes inside the body of while loop is evaluated.
  • Then, the test expression is evaluated again. This process goes on until the test expression is false.
  • When the test expression is false, while loop is terminated.

Flowchart of while Loop

Flowchart of while loop in C++ Programming

Example 1: C++ while Loop

  1. // C++ Program to compute factorial of a number
  2. // Factorial of n = 1*2*3...*n
  3. #include <iostream>
  4. using namespace std;
  5. int main()
  6. {
  7. int number, i = 1, factorial = 1;
  8. cout << "Enter a positive integer: ";
  9. cin >> number;
  10. while ( i <= number) {
  11. factorial *= i; //factorial = factorial * i;
  12. ++i;
  13. }
  14. cout<<"Factorial of "<< number <<" = "<< factorial;
  15. return 0;
  16. }
  17. Output
    Enter a positive integer: 4
    Factorial of 4 = 24
    In this program, user is asked to enter a positive integer which is stored in variable number. Let's suppose, user entered 4.
    Then, the while loop starts executing the code. Here's how while loop works:
    1. Initially, i = 1, test expression i <= number is true and factorial becomes 1.
    2. Variable i is updated to 2, test expression is true, factorial becomes 2.
    3. Variable i is updated to 3, test expression is true, factorial becomes 6.
    4. Variable i is updated to 4, test expression is true, factorial becomes 24.
    5. Variable i is updated to 5, test expression is false and while loop is terminated.

Comments

Popular posts from this blog

C++ Templates ?

Function Overriding in C++ [With Example]

C++ Program to Print Number Entered by User