Calculating in C++

1.1.   Calculating in C++

In this post we will talk about calculations in programming language C++. We will define the variables and use them for calculations. If you know how to carry out simple input or output now you are beginning the bit in the middle, the processing part of a C++ program.

1.1.1.The assignment statement

The function of the assignment statement is to calculate the value of an expression that appears on the right hand side of the equals sign. For example:
f = a + b + c + d;
In this case, the sum of a, b, c, d equals a variable f. With this code you have given an order to computer to calculate the sum of variables a, b, c and d and the result is stored in the variable specified on the left-hand side, in this case, the variable with the name f. In this statement, the f is exactly the sum of its parts. Don’t forget that statement ends with semicolon.
We can also use repeated assignments, for example:
a = b = c = 5;
In this statement we have assigned the value 5 to variables a, b and c. This means that each of these variables have the same assigned value.

1.1.2.  Arithmetic Operation

The basic arithmetic operators you have at your disposal are addition, subtraction, multiplication, and division, represented by the symbols +, - , *, and / , respectively. Generally, these operate as you would expect, with the exception of division, which has a slight aberration when working with integer variables or constants, as you’ll see. You can write statements such as the following:
netPay = hours * rate - deductions;
Here, the product of hours and rate will be calculated and then deductions subtracted from the value produced. The multiply and divide operators are executed before addition and subtraction, as you would expect. I will discuss the order of execution of the various operators in expressions more fully later in this chapter. The overall result of evaluating the expression hours*rate – deductions will be stored in the variable netPay .
The minus sign used in the last statement has two operands — it subtracts the value of its right operand from the value of its left operand. This is called a binary operation because two values are involved. The minus sign can also be used with one operand to change the sign of the value to which it is applied, in which case it is called a unary minus . You could write this:
int a = 0;
int b = -5;
a = -b; // Changes the sign of the operand
Here, a will be assigned the value +5 because the unary minus changes the sign of the value of the operand b. Note that an assignment is not the equivalent of the equations you saw in high - school algebra. It specifies an action to be carried out rather than a statement of fact. The expression to the right of the assignment operator is evaluated and the result is stored in the location specified on the left.
Look at this statement:
number = number + 1;
This means “add 1 to the current value stored in number and then store the result back in number.” As a normal algebraic statement, it wouldn’t make sense, but as a programming action, it obviously does.

1.1.3.Calculating a Remainder

You saw in the last example that dividing one integer value by another produces an integer result that ignores any remainder, so that 11 divided by 4 gives the result 2. Because the remainder after division can be of great interest, particularly when you are dividing cookies amongst children, for example, C++ provides a special operator, % , for this. So you can write the following statements to
handle the cookie - sharing problem:
int residue = 0, cookies = 19, children = 5;
residue = cookies % children;
The variable residue will end up with the value 4, the number left after dividing 19 by 5. To calculate how many cookies each child receives, you just need to use division, as in the statement:
each = cookies / children;
1.1.4.                 Modifying a Variable
It’s often necessary to modify the existing value of a variable, such as by incrementing it or doubling it. You could increment a variable called count using the statement:
count = count + 5;
This simply adds 5 to the current value stored in count and stores the result back in count, so if count started out as 10, it would end up as 15. You also have an alternative, shorthand way of writing the same thing in C++:
count += 5;
This says, “Take the value in count , add 5 to it, and store the result back in count . ” We can also use other operators with this notation. For example,
count *= 5;
has the effect of multiplying the current value of count by 5 and storing the result back in count . In general, you can write statements of the form,
lhs op= rhs;
lhs stands for any legal expression for the left - hand side of the statement and is usually (but not necessarily) a variable name. rhs stands for any legal expression on the right - hand side of the statement. op is any of the following operators:



You have already met the first five of these operators, and you’ll see the others, which are the shift and logical operators, later in this chapter. The general form of the statement is equivalent to this:
lhs = lhs op (rhs);
The parentheses around rhs imply that this expression is evaluated first, and the result becomes the right operand for op. This means that you can write statements such as:
a /= b + c;
This will be identical in effect to this statement:
a = a/(b + c);
Thus, the value of a will be divided by the sum of b and c , and the result will be stored back in a .

1.1.5.The Increment and Decrement Operators

This section introduces some unusual arithmetic operators called the increment and decrement operators. You will find them to be quite an asset once you get further into applying C++ in earnest. These are unary operators that you use to increment or decrement the value stored in a variable that holds an integral value. For example, assuming the variable count is of type int , the following three statements all have exactly the same effect:
count = count + 1; count += 1; ++count;
They each increment the variable count by 1. The last form, using the increment operator, is clearly the most concise. The increment operator not only changes the value of the variable to which you apply it, but also results in a value. Thus, using the increment operator to increase the value of a variable by 1 can also appear as part of a more complex expression. If incrementing a variable using the ++ operator, as in ++count, is contained within another expression, then the action of the operator is to first increment the value of the variable and then use the incremented value in the expression. For example, suppose count has the value 5, and you have defined a variable total of type int . Suppose you write the following statement:
total = ++count + 6;
This results in count being incremented to 6, and this result is added to 6, so total is assigned the value 12. So far, you have written the increment operator, ++, in front of the variable to which it applies. This is called the prefix form of the increment operator. The increment operator also has a postfix form, where the operator is written after the variable to which it applies; the effect of this is slightly different. The variable to which the operator applies is incremented only after its value has been used in context. For example, reset count to the value 5 and rewrite the previous statement as:
total = count++ + 6;
Then total is assigned the value 11, because the initial value of count is used to evaluate the expression before the increment by 1 is applied. The preceding statement is equivalent to the two statements:
total = count + 6;
The clustering of „+ „signs in the preceding example of the postfix form is likely to lead to confusion. Generally, it isn’t a good idea to write the increment operator in the way that I have written it here. It would be clearer to write:
total = 6 + count++;
Where you have an expression such as a++ + b, or even a+++b, it becomes less obvious what is meant or what the compiler will do. They are actually the same, but in the second case, you might really have meant a + ++b , which is different. It evaluates to one more than the other two expressions. Exactly the same rules that I have discussed in relation to the increment operator apply to the decrement operator, - - . For example, if count has the initial value 5, then the statement
total = --count + 6;
results in total having the value 10 assigned, whereas,
total = 6 + count--;
sets the value of total to 11.

1.1.6.The Sequence of Calculation

So far, I haven ’ t talked about how you arrive at the sequence of calculations involved in evaluating an expression. It generally corresponds to what you will have learned at school when dealing with basic arithmetic operators, but there are many other operators in C++. To understand what happens with these, you need to look at the mechanism used in C++ to determine this sequence. It ’ s referred to as operator precedence .
Operator Precedence
Operator precedence orders the operators in a priority sequence. In any expression, operators with the highest precedence are always executed fi rst, followed by operators with the next highest precedence, and so on, down to those with the lowest precedence of all. The precedence of the operators in C++ is shown in the following table.
() [] - > . Left
! ~ + (unary) - (unary) ++ - - & (unary) * (unary) (typecast) static_cast const_cast dynamic_cast reinterpret_cast
sizeof new delete typeid decltype
.* (unary) - > * Left
* / % Left
+ - Left
< < > > Left
< < = > > = Left
== != Left
& Left
^ Left
| Left
& & Left
|| Left
?: (conditional operator) Right
= *= /= %= += - = & = ^= |= < < = > > = Right

Rather than spreading them around, I have put all the C++ operators in the precedence table so that you can always refer back to it if you are uncertain about the precedence of one operator relative to another. Operators with the highest precedence appear at the top of the table. All the operators that appear in the same cell in the table have equal precedence. If there are no parentheses in an expression, operators with equal precedence are executed in a sequence determined by their associativity. Thus, if the associativity is “left, ” the left - most operator in an expression is executed first, progressing through the expression to the right - most. This means that an expression such as a + b + c + d is executed as though it was written (((a + b) + c) + d) because binary + is left – associative Note that where an operator has a unary (working with one operand) and a binary (working with two operands) form, the unary form is always of a higher precedence and is, therefore, executed first.
You can always override the precedence of operators by using parentheses. Because there are so many operators in C++, it’s sometimes hard to be sure what takes precedence over what. It is a good idea to insert parentheses to make sure. A further plus is that parentheses often make the code much easier to read.
Share on Google Plus