First | Next | Previous | Last | Glossary | About

# Variables, Data Types, Arithmetic and Relational operators

- Variables in C++
- C++ data types
- C++ arithmetic operators
- if, else, the bool data type and the relational operators
- Simple program input
- Tutorial - working with variables, operators and decisions

## Variables in C++

Valid | Invalid
new_value | new&value
val99 | $val99
_com1 | com1:

Variable names must begin with a letter or underscore and may contain any combination of upper/lower case alpha, digits and underscores.

The length of variable names depends on the compiler.

Use meaningful names and note that C++ is case-sensitive, the identifier new_value is different from the identifier New_value. One of the most common mistakes made by a beginner in C++ is to overlook case sensitivity.

Return to top of page

## C++ data types

C++ has some basic or simple data types:

- int - Store an integer (whole number) value. Like most other languages the size of an integer in C++ is often determined by the size of the machine word. A 16 bit word would have signed values from -215 to 215 - 1 (-32768 to 32767).
- float - Store a floating point or real value.
- char - Store a single character. A literal or constant character value is a value enclosed in single quotes for example: 'K', '9','*'.
- bool - Store a value representing true or false. We look at this in detail in the session on decisions.

    //ex9.cc - int and float
    #include <iostream>
    int main()
    { int x,
          y = 12;
      float v1,
            v2 = 98.967;
      cout << " x is " << x << endl;
      x = 7 * y;
      cout << " x is " << x << endl;
      cout << " v1 is " << v1 << endl;
      v1 = 100.0 * v2;
      cout << " v1 is " << v1 << endl;
      return 0;
    }

Here is an example using the int and float data types. The example shows how to declare variables and how to initialise variables when they are declared. The integer variable y and the float variable v2 are both initialised to some known value when they are declared.

By the way you can also see how C++ treats white space. White space is anything like the space character, the newline character, formfeed, tab and so on, ie any character that generates white space in the source code. The lines:

    int x,
        y = 12;

could have been written as:

    int x, y = 12;

      x is 2144410891
      x is 84
      v1 is NaN
      v1 is 9896.7

When this program is built and executed you get output like this:

      x is 2144410891
      x is 84
      v1 is 1.56482e-37
      v1 is 9896.7

or perhaps like this:

The output depends on what the machine was doing before the program was executed. You can see that when x and v1 are declared they are not initialised whereas y and v2 are.

When the program runs it outputs x and v1 before these variables have values assigned to them - the contents of x and v1 are undefined.

The first run of ex9 produces the value 2144410891 for x and NaN for v1. What is NaN? It means that whatever is stored in location v1 is Not a Number. The output stream cout can't interpret whatever is there. The variable x was interpreted fine since almost any lump of memory can be viewed as containing integer values but, since floating point values have a special format and, since there are some areas of the floating point domain that are unknown, we get the result NaN.

    //ex10.cc

    #include <iostream>

    int main()
    {char a = 'A';

     cout << a << endl; ++a;
     cout << a << endl; ++a;
     cout << a << endl; ++a;
     cout << a << endl;

     for (a = 'A'; a <= 'Z'; a++)
      cout << a;

     return 0;
    }

The next example shows the use of a char variable.

The variable a is declared as a variable of type char and initialised to the value 'A'.

Don't worry about the for loop too much we will get to that soon, the interesting thing is the way the data type is treated. The ++ operator is an arithmetic increment, i.e. the same as a = a + 1.

Return to top of page

## C++ arithmetic operators

    //ex10a.cc
    #include <iostream>

    int main()
    {
     int x = 0, y = 2, z = 1025;
     float a = 0.0, b = 3.14159, c = -37.234;

    // incrementing and decrementing
      x = x + 1;  // This increments x
      y = y - 1;  // This decrements y
      a = a + 12; // This adds 12 to a.

    // The constant 12 is an int
      cout << x << " " << y << endl;
      y = 3;
      z = z + y + x;
      cout << y << " " << z << endl;
      x = 18 % 4;
      cout << x << endl;
      return 0;
    }

You have already used several operators and their use is largely intutive. We start with the arithmetic operators:

- + plus
- - minus
- * multiply
- / divide
- % modulus

and combine these with variables of the simple data types in a simple program. The example here shows some of the operators.

There are some issues which need your attention when dealing with arithmetic operations.

Avoiding division by zero. If we write statements like this z = 0; or during program execution a value becomes 0 and then we use it as a divisor we can expect to get a serious problem since we are attempting to divide by zero, for example the statement:

      x = 12 * y + 4 / z;

is likely to crash our program if z is 0.

     z = 13;
     x = 12 * y + z / 4;

Avoiding unwanted truncation. The problem with the code shown here is that the operation will result in a floating point value, 13 won't divide by 4 exactly. The result will be 39 but perhaps it should have been 39.25. The operation z / 4 was truncated which may or may not be acceptable.

    x = 12 * (y + 4);
    x = 12 * y + 4;

Ensuring the correct order of evaluation. Note the difference between 12 * (y + 4) and 12 * y + 4 . If y = 3 in the first case we get 84, in the second 40. The order of precedence of the the operators is obviously important, multiply and divide are higher than add and subtract.

You should use parentheses to force the order of evaluation that you want.

Return to top of page

## if, else, the bool data type and the relational operators

The relational operators tell us something about the nature of the relationship between two operands. A relational operation evaluates as being either true or false. In order to look at the relational operators:

- > greater than
- < less than
- >= greater than or equal
- <= less than or equal
- != not equal

we need first to look at the bool data type (which was mentioned earlier) and the decision construct in C++.

    //ex10c.cc
    #include <iostream>

    int main()
    { int x,y,z;
      float a,b,c;
      bool d, e;

      y = 3;
      x = 12 * y + 4;
      cout << x << endl;
      z = 12 * (y + 4);
      cout << z << endl;
      d = z > x;
      e = x > z;
      cout << "d is " << d << endl;
      cout << "e is " << e << endl;
      return 0;
    }

The output is:

       40
       84
       d is 1
       e is 0

You can see there is another data type bool (boolean or logical) and it is used with relational operators.

The expression d = z > x tests to see if z is greater than x and assigns a result to the boolean variable d. A boolean variable is true if it is none-zero and false if it is zero. If a boolean variable is displayed then you will see 1 for true and 0 for false.

We can assign integer values to boolean variables, for example d = 11 but it will still display as 1.

What will be displayed by the following?

     d = 11;
     d = d - d; cout << "d is " << d << endl;
     d = -4;    cout << "d is " << d << endl;

The decision structure is important in programs because it enables the possibility of programs branching according to some condition:

In C++ decisions are written this way:

      if (x > y)
       cout << "x is larger";

      if (x > y)
       cout << "x is larger";
      else
       cout << "x is not larger";

The logical condition or the proposition is enclosed in parentheses and is known as a logical or conditional or propositional or relational expression. Note that there is no "then" word.

if statements can be nested:

       if (x > y)
        cout << "x is larger than y";
       else
        if (y > x)
         cout << "y is not larger x";
        else
         cout << "x and y are the same";

This is called multiway selection.

Return to top of page

## Simple program input

We have used cout the standard output stream to display output from programs. The insertion operator inserts data into the output stream. There is a standard input stream cin which accepts or extracts data from the standard input device the keyboard and passes it on to variables using the extraction operator >>.

eg: cin >> x;

    //ex10e.cc
    #include <iostream>

    int main()
    { int x,y,z;

      cout << "Enter an integer value for y ";
      cin >> y;
      cout << "Enter an integer value for x ";
      cin >> x;

      z = x * (y + 4);
      cout << z << endl;

      if (x > y)
       cout << "x is larger than y";
      else
       cout << "x is not larger y";

      cout << endl;

      if (x > y)
       cout << "x is larger than y";
      else
       if (y > x)
        cout << "y is not larger x";
       else
        cout << "x and y are the same";

      return 0;
    }

Return to top of page

## Tutorial 3 - working with variables, operators and decisions

1. Try out the examples from this section and convince yourself that they work.
2. Use the example ex10e.cc and see if you can get some idea of what the largest integers are.

Return to top of page

First | Next | Previous | Last | Glossary | About

Copyright © 1999 - 2001 David Beech