Site icon TestingDocs.com

C++ while statement

Introduction

In this post, we will discuss the iteration using the while loop statement. Using while statement is a simple way to execute a statement or group statements repeatedly in a C++ program. while( expression)     action

 

Flowchart

Sample program

/*************************
* C++ while loop demo
*************************/

#include <iostream>
using namespace std;

int main()
{
    double n;
    int size=3;
    double sum=0;
    int count =0;
    // while loop
    while(count < size)
    {
        cout << "Please enter a number : " ;
        cin >> n;
        sum += n;
        count++;
    }
    cout << "Average of 3 numbers is = " << sum/size << endl;
    return 0;
}

 

Sample output

Please enter a number : 24.5 Please enter a number : 27.8 Please enter a number : 26.9 Average of 3 numbers is = 26.4 Process returned 0 (0x0) execution time : 18.825 s Press any key to continue. ************************** The while loop is executed until the expression is true. The loop will stop when the expression truth value is false. You can group several statements in the while loop with the help of curly braces.

break statement

The break statement is used for the early termination of the loops. Let’s modify the above code to compute the average of numbers without limiting them to three. We specify a large number as the conditional expression in the while loop. However, the user can stop entering the numbers if he/she types -1. For example, 5.0 7.0 -1 Average of numbers is (5.0 + 7.0)/2 = 6 in order to achieve this we check for the input and terminate the loop is user enters -1 if(n==-1) break;

/*************************
* C++ while loop demo
*************************/

#include <iostream>
using namespace std;

int main()
{
    int maxNumbers=9999;
    double n;
    double sum=0;
    int count =0;
    // while loop
    while(count < maxNumbers)
    {
        cout << "Please enter a number | -1 to stop: " ;
        cin >> n;
        if(n==-1)
            break;
        sum += n;
        count++;
    }
    cout << "Average of numbers is = " << sum/count << endl;
    return 0;
}

Output:

Please enter a number | -1 to stop: 5.0

Please enter a number | -1 to stop: 7.0

Please enter a number | -1 to stop: -1

Average of numbers is = 6

Process returned 0 (0x0) execution time : 6.469 s

Press any key to continue.

 

The use of break statement in loops is discouraged because it makes the program logic harder to understand. We can rewrite the loops to eliminate the break statement.

 

 The IDE used in the program is Code:: Blocks. To download and install Code Blocks follow the link:

https://www.testingdocs.com/download-and-install-codeblocks/

For more information on Code Blocks IDE, visit the official website of Code blocks IDE: http://www.codeblocks.org/

Exit mobile version