Once the code design is completed, you can begin writing the program. But rather than try to write the entire program at once and then debug it, you will use a method called fast prototyping. This consists of writing the smallest portion of the specification you can implement that will still do something. In our case, you will cut the four functions down to a one-function calculator. Once you get this small part working, you can build the rest of the functions onto this stable foundation. Also, the prototype gives the boss something to look at and play around with so he has a good idea of the direction the project is taking. Good communication is the key to good programming, and the more you can show someone, the better. The code for the first version of the four-function calculator is

Example : calc/calc.cc


#include <iostream.h>

int   result;               // the result of the calculations
char  oper_char;     // the user-specified operator
int   value;               // value specified after the operator

int main()
{
    result = 0;           // initialize the result

    // Loop forever (or till we hit the break statement)
    while (1) {
        cout << "Result: " << result << '\n';

        cout << "Enter operator and number: ";
        cin >> oper_char;
        cin >> value;

        if (oper_char = '+') {
            result += value;
        } else {
            cout << "Unknown operator " << oper_char << '\n';
        }
    }
    return (0);
}
The program begins by initializing the variable result to zero. The main body of the program is a loop starting with:

    while (1) {
This will loop until a break statement is reached. The code:

    cout << "Enter operator and number: ";
    cin >> oper_char >> value;
asks the user for an operator and number. These are parsed and stored in the variables oper_char and value. (The full set of I/O operations such as << and >> are described in Chapter 16, File Input/Output.) Finally, you start checking the operators. If the operator is a plus (+), you perform an addition using the line:

    if (oper_char = '+') {
        result += value;
So far you only recognize the plus operator. As soon as this works, you will add more operators by adding more if statements.

Finally, if an illegal operator is entered, the line:

    } else {
         cout << "Unknown operator " << oper_char << '\n';
    }
writes an error message telling the user he made a mistake.

Posted By :-Cplusplusprogramming
Designed By Blogger Templates | Templatelib & Distributed By Blogspot Templates