Sunday, June 3, 2012

Input Validation Using While Loop and Do While Loop


Input Validation Using While Loop and Do While Loop

Looping is also used for input validation. Input validation is a process where you check whether the user is inputting the valid data or not. A user may input anything and that can make the program to behave unexpectedly.
For eg. If you create a program that takes various subject's marks as input from user and then calculates and displays total and average of those marks. Suppose that every subject was of 100 marks and so the student can score anything from 0 to 100. So if the user starts inputting more than 100 marks or less than 0 marks then the result of this will be unexpected.

The user may do mistake unintentionally or intentionally. If he does unintentionally then we should show him his mistake and then tell him to correct it . If he does intentionally then he will see that our program is smart enough to understand his mistakes.
Input validation is also necessary for security reasons as well and it can be very lengthy in real world programs, where each input is tested with various conditions. However, here i present you some easy programs to make you understand how we can make use of while and do while loop for input validation. The below three programs will accept input from user only if the numbers are from 1 to 9. Greater than 9 and less than 1 will not be accepted. To understand these programs, you must know The Difference Between 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 )

Please do comment if you don't understand any part or want to know more or just want to say thanks. I love programming and love to teach my friends. Your suggestions and appreciation will make this blog much better.
Want to learn more? View List Of All Chapters

25 comments:

  1. I tried the first example, and whether I input a char, the program go to an infinite loop. I debug the program and I had observed that integer variable is set with a negative random number and that "cin >> number" is skipped. I use MSVC10. What is the explanation of this ?

    Thanks

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. It change de value the next value ex: !1=0, !0=1

      Delete
  3. @mdu.
    This state is not catered by this post. If a user inputs a character in an integer stream, infinite loop occurs and the program crashes. Here is a post that i found very useful on internet on this topic.
    http://codingmash.com/2012/06/input-validation-in-c/

    ReplyDelete
  4. how can i write a program that inputs the grade of a students in four periods and print "PASSED"if letter grade is A,B and C and"FAILED" if letter grade D and E, otherwise invalid. ( greater than or equal to 80 #A) (less than 90 but greater than or equal 80 #B) (less than 80 but greater than or equal 75 #C) (Less than 70 but greater than or equal to 60 #D) (less than 60 #E).... KINDLY HELP ME TO code this #I am a freshmen on this #programing course!!

    ReplyDelete
    Replies
    1. You could very easily use a switch statement to accomplish this.

      Delete
  5. Download Islmic books here :http://islamicmsg.org/index.php/kutub/eedarey-ki-kutub/215-aahadees-e-mutariza-aur-un-ka-hal

    ReplyDelete
  6. Thanks for your ideas. You can also find the details on Affity Solutions, at the C++ Developers. The main object of the Affity Solutions is to provide quality web services and is among the few software development company in Nagpur.

    ReplyDelete
  7. Many of the C++ programs utilize the functionality of the while loop in making the conditions for certain inputs. This loop returns the function to the calling point whenever the user enters a value rather than the one in the given interval. I love the way the blogger has explained the C++ while loop use in such simplicity. Write my Business school Entrance Essay

    ReplyDelete
  8. Pkjazba Provides Fashion Makeup Hairstyle Digests Recipes Fitness Health
    Pkjazba.com

    ReplyDelete
  9. Fine method of telling, and enjoyable article to acquire factual statements.
    tutorial on c++

    ReplyDelete
  10. Interesting Information, Keep it up

    ReplyDelete
  11. Machine learning services are the future of the IT industry and one must learn these services to be competitive in the IT industry. You can click here to learn more about machine learning services and enhance your knowledge.

    ReplyDelete
  12. Nice Post....It will be helpful for beginner Student.Here is a blog for C++ Programming.

    ReplyDelete