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

Tuesday, November 15, 2011

The goto statement in c++

The goto statement in c++


We have gone through the while loop, for loop and do-while loop. The another way to do loop in c++ is through using the goto statement. The goto statement was used in olden days but it is not suitable for creating modern applications. But since c++ supports it, you should have knowledge about it, as you may encounter a c++ source code containing goto statements, in that case you will know what it is and how it works.

How the goto statement works?


It consist of label and statements that comes under that label. A label is named by you and it is followed by a colon sign (:). During execution of program, when goto is encountered, it jumps to the statements that comes under the label specified by goto statement. To get a clear idea, analyze the below program example.

/* A c++ program example that uses goto statement to display number from 0 to 9 */



#include <iostream>

using namespace std;

int main ()
{
    int i=0;

loop:
    cout << i << endl;
    i++;

    if (i<10)
        goto loop;

    return 0;
}


Why goto should not be used?


The use of goto should be avoided to make the program more readable and reliable. The goto statement can cause the program execution to jump to any location in source code and in any direction backward or forward. This makes the program hard to read and understand and also makes it difficult to find bugs.
Since now we have more tightly controlled and sophisticated loops like while loop, for loop and do-while loop, the use of obsolete statement like goto is not at all recommended in creating loops.

Tuesday, October 25, 2011

Repetition Statement: The Do-While Loop in c++

Repetition Statement: The Do-While Loop in c++


We have already gone through The While Loop and The For Loop. Now its time for The Do-While Loop.

/* A c++ program example that uses do-while loop to display number from 0 to 9 */


// Program 1

#include <iostream>

using namespace std;

int main ()
{
    int i = 0;
    do
    {
        cout << i << endl;
        i++;
    } while (i < 10);
    return 0;
}



The do-while loop works just like the for loop and while loop but with one exception. Unlike the for loop and while loop, the do-while loop will execute at least once.
The for loop and the while loop checks the condition and then the body of loop executes but in case of do-while, the body is executed first and then it checks the condition.

/* A c++ program example that demonstrates how do-while loop distinguishes from the for loop and while loop */


// Program 2

#include <iostream>

using namespace std;

int main ()
{

    // The while loop
    int i = -1;
    while (i != -1)
    {
        cout << "Inside the while loop. " << endl;
        cout << "Please enter a number or -1 to quit: ";
        cin >> i;
    }

    // The for loop
    int j = -1;
    for (; j != -1; )
    {
        cout << "Inside the for loop. " << endl;
        cout << "Please enter a number or -1 to quit: ";
        cin >> j;
    }

    // The do-while loop
    int k = -1;
    do
    {
        cout << "Inside the do-while loop. " << endl;
        cout << "Please enter a number or -1 to quit: ";
        cin >> k;
    } while (k != -1);

    return 0;
}

When you run the above program, only the body of do-while gets executed and others do not. The initial value is set to -1 and the condition is such that the value should not be equal to -1. The for loop and while loop checks the condition first and hence their body is not executed, the do-while loop executes the body first and hence it gets executed even though the condition is false, as it checks the condition after executing the body.

Use Do-While when you want the body of the loop to execute at least once, even if the condition is false at the start or else you could make use of the for loop and while loop.

Thursday, June 23, 2011

Repetition Statement: The For Loop in c++

Repetition Statement: The For Loop in c++


To understand this you must first go through The While loop in c++.
The below program, Program 1 does the same thing that the Program 1 of previous chapter The While Loop does. An integer i is declared and then three expression of the loop: initializer, loop-test and counting expression, all are passed as parameters in for loop. The variable i is initialized to 0 then it will test the condition whether the value of i is less than 10. If the condition is true, the body of loop will execute. The incrementation statement will be last statement to be executed by the for loop.

/* A c++ program example that uses for loop to display number from 0 to 9 using incrementation in the loop */


// Program 1

#include <iostream>

using namespace std;

int main ()
{
    int i;

    for (i=0; i<10; i++)
    {
        cout << i << endl;
    }

    return 0;
}

If you are just going to use the variable within the body of loop, then better declare it in the for loop itself. This will make your program more reliable. The below programs declare variable in the for loop.

/* A c++ program example that uses for loop to display multiplication of 8*/


// Program 2

#include <iostream>

using namespace std;

int main ()
{
    for (int i=8; i<=80; i+=8)
        cout << i << endl;

    return 0;
}


/* A c++ program example that tells you whether the number is even or odd. Number ranges from 1 to 20. */


// Program 3

#include <iostream>

using namespace std;

int main ()
{
    for (int i=1; i<=20; i++)
    {
        if (i%2==0)
            cout << i << "is an even number." << endl;

        else
            cout << i << "is an odd number." << endl;
    }

    return 0;
}

The operator "%" is called the remainder/modulo operator as already been described in Mathematical Operators. The statement i%2==0 simply means that the remainder of i divided by 2 equals to 0.

/* A c++ program example that uses for loop to diplay the square root and cube of numbers from 1 to 10. */


// Program 4

#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
    cout << "Number " << "Square " << "Cube" << endl;

    for (long i=1; i<=10; i++)
    {
        cout << setw (2) << i << setw (8)
        << i*i << setw (8) << i*i*i << endl;
    }

    return 0;
}


/*A c++ program example that displays multiplication table of a number provided by the user.*/


// Program 5

#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
    int number;

    cout << "Enter a number to get its multiplication table: ";
    cin >> number;
    cout << endl;
    cout << "-------------" << endl;

    for (int i=1; i<=10; i++)
    {
        cout << number << " x " << setw (2) << i << " = "
        << setw (3) << number*i << endl;
        cout << "-------------" << endl;
    }

    return 0;
}

Monday, May 23, 2011

Repetition Statement: The While Loop in c++

Repetition Statement: The While Loop in c++


The fundamental to programming are control statements. You must learn to have good command over control statement, if you want to program.
Sequence, selection and repetition are three types of control statement. It specifies the order in which the statement are executed.

(1) Sequence Structure: The sequence structure is built into c++. The c++ statement are executed in sequence, that is one after the other if not directed otherwise. Hope you know this. If not then remember from now on.

(2) Selection Statement: Selection statement are of three types: if, if-else and switch statement. We have already learned these in previous chapters.

(3) Repetition Statement: Repetition statement are of three types: while loop, for loop and do-while loop. We have to learn about these in this and coming chapters.

In programming, often the situation arises in which you have to repeatedly execute a particular code or set of codes. Suppose you want to print your name to the console five times. What you will do? If you have no knowledge of repetition statement, you will write your name in cout 5 times. Something like below:

/* A c++ program example that should have been written using repetition statements */


// Program 1

#include <iostream>

using namespace std;

int main ()
{
    cout << "Mohammed Homam" << endl;
    cout << "Mohammed Homam" << endl;
    cout << "Mohammed Homam" << endl;
    cout << "Mohammed Homam" << endl;
    cout << "Mohammed Homam" << endl;

    return 0;
}

But what if you have to print it 100 or 1000 times? It would be bothersome and also the code will be too lengthy if we use the above method. To simplify such task we use repetition statement.

The While Loop


/* A c++ program example that uses while loop to print the name 5 times using incrementation in the loop */


// Program 2

#include <iostream>

using namespace std;

int main ()
{
    int i = 0;
    while (i < 5)
    {
        cout << "Mohammed Homam" << endl;
        i++;
    }


    return 0;
}

Now lets analyse that what's happening in the above program. Look at the program while reading the each statement of explanation. We declared an integer i and intialised it to 0. After that while loop checks whether i is less than 5. Currently the value of i is 0 and hence the condition i<5 is true. Since the condition is true, the body of while is executed. The body of while loop contains two statement: one that displays the name and other that increments the value of i by 1. After executing the increment statement, now the new value of i is 1. The while loop will again check the condition and since 1 is less than 5 the body of while will execute again. This will go on until the value of i is incremented to 5. Once the value of i is 5, the condition will become false as a result of which the body of loop won't execute and will terminate.

What's the use of increment statement in the above program?
If you don't increment the value of i in the above program, then value of i will always be 0 and hence the condition i < 5 will also be always true. It means your loop will never stop, it will go on and on. This is called infinite loop. Try this by removing i++; from above program. Compile and run it again. Press ctrl+c to terminate the program.

/* A c++ program example that uses while loop to print the name 5 times using decrementation in the loop */


// Program 3

#include <iostream>

using namespace std;

int main ()
{
    int i = 5;
    while (i > 0)
    {
        cout << "Mohammed Homam" << endl;
        i--;
    }

    return 0;
}


The above program does the same thing as its above program. The logic used is different. Here we gave the intial value to i as 5. Now the condition is, that i must be greater than 0. As the body of while loop is executed each time, the value of i is decremented by 1. The loop terminates when the value of i becomes 0.

/* A c++ program example that uses while loop to print number from 0 to 9 using incrementation in the loop */


// Program 4

#include <iostream>

using namespace std;

int main ()
{
    int i = 0;
    while (i < 10)
    {
        cout << i << endl;
        i++;
    }

    return 0;
}

/* A c++ program example that uses while loop to print number from 0 to 9 using decrementation in the loop */


// Program 5

#include <iostream>

using namespace std;

int main ()
{
    int i = 9;
    while (i >= 0)
    {
        cout << i << endl;
        i--;
    }

    return 0;
}

The above program were simplest one's to get started into looping. In the next chapter we will learn about the for loop.

Thursday, December 9, 2010

Conditional (Ternary) Operator in c++ [? :]

Conditional (Ternary) Operator in c++ [? :]


The condional operator can often be used instead of the if else statement. Since it is the only operator that requires three operands in c++, it is also called ternary operator.

For example, consider the assignment statement :
x = y > 3 ? 2 : 4;
If y is greater than 3 then 2 will be assigned to variable x or else the value 4 will be assigned to x.

/* A simple c++ program example to demonstrate the use of ternary operator. */


// Program 1


#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
    int first, second;

    cout << "Enter two integers." << endl;

    cout << "First" << setw (3) << ": ";
    cin >> first;

    cout << "Second" << setw (2) << ": ";
    cin >> second;

    string message = first > second ? "first is greater than second" :
                                "first is less than or equal to second";

    cout << message << endl;

    return 0;
}


Compare the above "Program 1" and below "Program 2" with "Program 2" and "Program 3" of Selection Statement (if-else if-else) in c++ respectively, for better understanding.

/* A c++ program example to demonstrate the use ternary operator.*/


// Program 2


#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
    int first, second;

    cout << "Enter two integers." << endl;

    cout << "First" << setw (3) << ": ";
    cin >> first;

    cout << "Second" << setw (2) << ": ";
    cin >> second;

    string message = first > second ? "first is greater than second" :
                                first < second ? "first is less than second" :
                                "first and second are equal";

    cout << message << endl;

    return 0;
}

Saturday, November 27, 2010

The switch statement in c++

The switch statement in c++


The program that we create should be readable. To increase the readability of the program we should use tools that is simple to read and understand. When possible use switch statement rather than if else statement, as it can be more readable than if else statement. But switch statement has limitation. It can't replace if else completely but can be helpful at certain situation. It can't do everything thing that if else statement can do. For example, switch statement can take only int or char datatype in c++. The following programs will help you to understand the switch statement.

/* A simple c++ program example that demonstrate the use of switch statement in c++ by taking character input.*/


// Program 1


#include <iostream>

using namespace std;

int main ()
{
    char permit;

    cout << "Are you sure you want to quit? (y/n) : ";
    cin >> permit;

    switch (permit)
    {
        case 'y' :
            cout << "Hope to see you again!" << endl;
            break;
        case 'n' :
            cout << "Welcome back!" < < endl;
            break;
        default:
            cout << "What? I don't get it!" << endl;
    }

    return 0;
}

/* A c++ program example that demonstrate the use of switch statement in c++ by taking integer input. */


// Program 2

#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
    const int CHEESE_PIZZA = 11;
    const int SPINACH_PIZZA = 13;
    const int CHICKEN_PIZZA = 14;

    cout << " *********** MENU ***********" << endl;
    cout << setw (9) << "ITEM" << setw (20) << "PRICE" << endl;
    cout << " (1) Cheese Pizza" << setw (8) << "$"
            << CHEESE_PIZZA << endl;
    cout << " (2) Spinach Pizza" << setw (7) << "$"
            << SPINACH_PIZZA << endl;
    cout << " (3) Chicken Pizza" << setw (7) << "$"
            << CHICKEN_PIZZA << endl;
    cout << endl;

    cout << "What do you want? ";
    int option;
    cin >> option;

    cout << "How many? ";
    int quantity;
    cin >> quantity;

    int price;

    switch (option)
    {
        case 1:
            price = CHEESE_PIZZA;
            break;
        case 2:
            price = SPINACH_PIZZA;
            break;
        case 3:
            price = CHICKEN_PIZZA;
            break;
        default:
            cout << "Please select valid item from menu. " << endl;
            return 1;
    }

    int amount = price * quantity;
    cout << "Your Bill: $ " << amount << endl;

    return 0;
}


Explanation for the above program:


In the above program we take an integer value from the user which is stored in 'option' variable. We pass this value to switch statement. The switch statement has 3 cases: case 1, case 2 and case 3. The case 1: is similar to if (option == 1). This is the advantage of switch statement over if else statement. You don't need to type the name of variable again and again if you are doing selection operation on same variable. You just put the variable name on switch statement and then just specify the value after 'case'. One more thing to be noted is that it requires 'break' statement at the end of each 'case'. If you remove the break statement then it will jump to the case that follows it. Try it and check by yourself. The 'default' is same as else in if else statement.