Wednesday 28 November 2012

Converting Inches to CM Part 2

Purpose of Program


This is an improvement on the last version, you can choose to either convert CM to inches or the other way round.

Program



#include 

using namespace std;

// a program that converts cm to inches

int main()
{
    // we declare a numerical constant.
    const float cstCentPerInch = 2.54;

    // menu variable
    string menuchoice ="";

    // declare a floating point number.
    float cm, inches;

    cout << "Select an option:" << endl;
    cout << "1. Inches to CM " << endl;
    cout << "2. CM to Inches " << endl;
    cin >> menuchoice;


     if (menuchoice=="1"){
            //Enter the length
            cout << "Enter a length in inches: ";
            cin >> inches;

            //return the number of inches.
            cm = inches * cstCentPerInch; // this is a divison

            cout << endl << inches << " inches equals " << cm << " cm " << endl;
    }
    else if (menuchoice=="2") {
            //Enter the length
            cout << "Enter a length in cm: ";
            cin >> cm;

            //return the number of inches.
            inches = cm / cstCentPerInch; // this is a divison

            cout << endl << cm << " cm equals " << inches << " inches " << endl;}
     else
        cout << "You chose an option that doesn't exist yet";



    return 0;
}

Thoughts

There are two main things to note in this code.

1. We are using a control statement ( the if... else if... else... statement) and,
2. We are using a new mathematical operator

Multiplication

To carry out multiplication in c++ we use a new operator... the multiplication operator which is * .

In our code cm = inches * cstCentPerInch means cm is assigned the result of multiplying inches with the constant cstCentPerInch (2.54).

Control Statement.
A control statement is a statement which alters the flow of execution in a program. Now, lets back up. The flow of execution is simply the order in which lines of code are run. Without control statements, every line in the program would be run once. You COULD write a program that way, but it would be very limited.

Say, you want to make a cup of tea or coffee depending on what a guest wants. So you ask them "do you want tea or coffee?" and what you do next depends on the answer.

In this above example, we have the same scenario. If they input 1 it will do one thing, if we input 2 it will do another.

"==" is another operator, in this case a Boolean operator. Boolean is another type - it says whether something is true or false.

Look back up to the statement... if our menuchoice is equal to "1" we do one thing, if it is equal to "2" we will do something else.

I'll explain more about the Boolean type in a full post later on as it is so important for programming.



No comments:

Post a Comment