CyberiaPC.com Main Page




Learning C++

{3} Writing the Code

What we're going to do now is write the code for our program.  Basically, what we need to do is:

1. Get the numbers/operation from the user

2. Determine which operator was selected

3. Calculate and get value for answer

4. Display result

Getting the values for the numbers and the operator from the user is a simple process of using cout and cin.  Here is how the code will look:

     cout << "Enter first number" << endl;
     cin >> firstnumber;
     
     cout << "Enter operation (* / + -)" << endl;
     cin >> operation;
     
     cout << "Enter second number" << endl;
     cin >> secondnumber;

As you can see, we ask the user to input values for each of our variables.  The endl at the end of each line tells the compiler to jump to the next line.  Kind of like using <p> in HTML.

Next, we have to use an If..Else block to determine which operator the user chose.  Depending on the choice, the code will perform the calculation and then store the result in answer:

     if (operation=='*')
         answer=first*second;
     else if (operation=='/')
          answer=first/second;
     else if (operation=='+')
          answer=first+second;
     else if (operation=='-')
          answer=first-second;
     else
     {    // if invalid operator is entered
          cout << "You did not enter a valid operator!";
          cout << endl;
          return; // Terminates application
     }

I've color coded the above code segment on purpose so that you can see how different parts of the code function.  The code in green is called a comment.  This is not read or executed by the compiler and is only placed in programs so that programmers know what a specific line does.

The variable operation is being used above and being compared to the four choices.  When a variable is declared as char, its value is enclosed in single quotes.  If operation, however, was a string, its value would be enclosed in double quotes.

The code basically checks to see which operation is selected and then performs the calculation.  the final result is then placed in answer.  If the user enters an operator that is not one of the four, then they get a message that an invalid operator was entered.  return tells the compiler to quit the program.

The last thing we need to do is display the result:

     cout.precision(3); // Set decimal places
     cout << "The result is: " << answer << endl;

The first line sets the decimal precision of the output to only three digits.  This type of formatting makes the program more user-friendly and pleasant to look at.  The second line displays the message The result is:  and then displays the value of answer followed by a hard return to the next line.

If you've been reading through the VB Tutorial, you'll notice that the exact same project is done much more efficiently in C++.  When it comes to calculations and numbers, C++ is the language to use!

{Go To Step 4}