Pages

Input Validation Using While Loop and Do While Loop


/* A c++ program example that uses while loop for input validation */


// Program 1

#include <iostream>

using namespace std;

int main ()
{
    int number;

    cout << "Enter a number from 1 to 9: ";
    cin >> number;

    while (! (number >=1 && number <= 9 ))
    {
        cout << "Invalid Input. Try Again." << endl;
        cout << "Enter a number from 1 to 9: ";
        cin >> number;
    }

    cout << "Your Input Is Valid." << endl;

    return 0;
}

/* A c++ program example that uses do-while loop for input validation */


// Program 2

#include <iostream>

using namespace std;

int main ()
{
    int number;

    do
    {
        cout << "Enter a number from 1 to 9: ";
        cin >> number;

        if (! (number >=1 && number <=9 ))
        {
            cout << "Invalid Input. Try Again." << endl;
        }
    } while (! (number >=1 && number <=9 ));
   
    cout << "Your Input Is Valid." << endl;

    return 0;
}

/* A c++ program example that uses do-while loop with data-type bool for input validation */


// Program 3

#include <iostream>

using namespace std;

int main ()
{
    int number;
    bool isValid = false;

    do
    {
        cout << "Enter a number from 1 to 9: ";
        cin >> number;
        isValid = ( number >=1 ) && ( number <=9 );

        if (isValid)
        {
            cout << "Your Input Is Valid." << endl;
            break;
        }

        else
        {
            cout << "Invalid Input. Try Again." << endl;
        }
    } while (!isValid);

    return 0;
}

Explanation And Clarification

while (! (number >=1 && number <= 9 )) can also be written as:
while (! (number > 0 && number < 10 ))
Since, 'greater than zero' is same as 'greater than or equal to 1'.
And, 'less than 10' is same as 'less than or equal to 9'.

The above while loop condition was written using AND with NOT operator. It can also be written using OR operator and will work same as above.
while (number <= 0 || number >=10 )
OR
while (number < 1 || number > 9 )

No comments:

Post a Comment