Chapter 3: Arithmetic and Expressions
In the previous chapter, we introduced the C++ numeric type to perform arithmetic and build expression. Some other important concepts we’d be covering in this chapter include source formatting, user input, dealing with errors, and comments.              
Expressions
A literal value, for example, 10 and a properly declared variable like a are examples of an expression. You can use operators to combine variables and values to form a more complex expression. Consider the example in Code 3.1
Code 3.1
#include <iostream>
int main () {
int value1, value 2, sum;
std::cout << “Please enter two integer values: ”;
std::cin >> value 1 >> value2;
sum=value1 + value2;
std::cout << value1 << “ + “ << value2 << “ = “ << sum << ‘\n’;
}
In the example above, the following stands for:
This statement is a declaration statement, and it declares the three integer variables. But this statement does not actually initialize them. As we continue to examine the remaining parts of the program, you’d see why it would be superfluous to assign values to the variables here.
      std::cout << “Please enter two integer values: ”;
In this statement, the user is prompted to enter some information. This statement is where we often print, but we didn’t terminate it with the usual end of line marker ‘\n.’ So, when you type in the values, they appear on the same line as the message asking for the values. When you press the enter key to complete, the cursor will automatically proceed to the next line.
      std::cin >> value 1 >> value2;
This statement causes the program to stop when you enter two numbers and then press the Enter key. The first number you enter will be assigned to value1, while the second will be assigned to value2. When you press the enter key, the values entered will be assigned to the variable. The std::cin is an object in C++ used to read input from the user.
      sum=value1 + value2;
This is an assignment statement, and it contains the assignment operator (=). The variable sum appears on the left-hand side of the assignment operator. In other words, sum will get a value when the statement executes.
Every expression has a value, and a process of determining the value of an expression is called evaluation. Evaluating simple expression is easy, but things get more complex when you’re trying to evaluate a smaller expression that makes up a more complex expression. Basically, the following are the simple C++ arithmetic operators.
      % means modulus
      / means division
      * means multiplication
      - means subtraction
      + means addition
Mixed Type Expressions  
Expressions can also contain mixed elements for example, consider code 3.2:
Code 3.2
int x = 2
doule y = 8.1, sum;
sum = x + y;
In the source code above, int proceeds to a double, so how’s this arithmetic performed. But the range of ints falls within the range of doubles, thus letting you represent any int value with a double . Also, the int value 2 can be represented as a double 2.0. So, it is completely reasonable to assign int values to double variables. This process is called widening, and it is quite safe to widen int to a double. Consider the code 3.3 source code fragment.
Code 3.3
double d1;
int i1 = 100;
d1 = i1;
std::cout << “d1 = “ << d1 << ‘\n’;
Assigning a double to an int variable is not always possible since the double value cannot be in range of ints . The double variable has to also fall within the range of ints and not a whole number because the int variable can’t manage the fractional part. So, if you were to write code 3.4, you’d get an error message.
Code 3.4
double d = 2.9;
int I = d;
In Code 3.4, the second line will assign 2 to i but lose the 0.9 fractional part because proper rounding can’t is done. In fact, the visual C++ compiler will warn you of a potential problem with:
warning C4244 ‘=’: conversion from ‘double’ to ‘int,’ possible loss of data
In like manners, converting from a wider type to a narrower type (like double to int ) is known as narrowing. In narrowing, it is necessary to assign a floating-point value to an integer variable. And if the value we want to assign is within the range of the int , and has no fractional parts, and pose no truncation harm, then the assignment is safe. If we want to perform an assignment and not get a warning from the compiler, then we need to use a procedure known as cast, also called typecast. The cast causes the compiler to accept the assignment without issuing a warning.
Operator Precedence and Associativity
The normal rules of arithmetic apply when there are different operators used in the same expression. All C++ operators has an associativity and precedence.
     Associativity: This is when an expression contains two operators that have the same precedence.
     Precedence: This is when an expression contains two kinds of operators.
To further understand how precedence works, consider the expression 2 + 3 * 4. The expression can be interpreted as (2 + 3) * 4, which would be 20. This same expression can be expressed as 2 + (3 * 4), which would be 14. So, which one is the correct interpretation. Just like in normal mathematical arithmetic, multiplication and division have equal importance and are usually performed before addition or subtraction. So, in the expression, multiplication is performed before addition since multiplication precedence over addition. The correct answer is 14, according to mathematical arithmetic.
The multiplicative operators (*, / or %) all have equal precedence with each other, and the additive operator (binary, +, and -) all have equal precedence with each other. The multiplicative operator has precedence over the additive operators. And just like in standard arithmetic, in C++, parentheses can override the precedence rules. Consider the expression (2 + 3) * 4, which is equal to 20.
Another way to easily go about this is to follow B.O.D.M.A.S order of operation, which interprets brackets, order, division, multiplication, addition, and subtraction, respectively. To see how associative works consider the expression 2 – 3 – 4. The two operators in this example are the same, so they have equal precedence. But if we should apply the first subtraction, before the second as in (2 – 3) – 4, our answer would be – 5. But if we should apply the second subtraction before the second as in 2 – (3 – 4), our answer would be 3. All binary operators except assignment are left-associative with the assignment being right-associative.
Consider the table below; it shows operator precedence and associativity. Operators that are in the same row have the same precedence. The operator in each of the rows has a higher precedence than the operators below it.
Arity
Operators
Associativity
Unary
+, -
Binary
*, /, %
Left
Binary
+, -
Left
Binary
=
Right
Comments
A good programmer engages in annotating their code by using remarks to explain the purpose of a section in their code. This is why programmers choose to write a section of code in a particular way they do. These remarks are what help human readers easily understand the codes and not compilers. Choosing the right comments and identifiers to use aids in the assessment process of a program. The compiler ignores any text in the comment box. So, C++ supports two main types of comments, the single-line comment, and the block comments.
      Single Line Comment
This is the first type of comment that helps in writing a single line remark. Consider
// Compute the average of the values
Avg = sum / number;
The first line here explains the comment and what the statement following it is meant to do. If you also noticed, the comment begins with a double forward slash symbol (//) and continues until the end of the line. Because of the double slash, the compiler ignores the content on the rest of the line. Using this type of comment is also useful in appending a short comment at the end of a statement. For example:
avg = sum / number; // Compute the average of the values
In the code line above, the executable statement and the comment are on the same line. The compiler will read the assignment but ignore the comment. The compiler has a way of generating the same code for this example and the one we gave below.
      Block Comment
This is the other type of comment that begins with the symbols /* and is only in effect when it ends with the symbols */. The block comment comes in handy when you want to comment in multi-lines. Consider the example below:
/* After the computation is completed, the result is printed. */
std::cout << result << ‘\n;
Formatting
Commenting on programs helps humans read and understand a code more, but the compiler ignores them. Another aspect of code sourcing that is largely irrelevant to the compiler is formatting. Imagine how hard it would be to read a text with no indention or space to separate paragraphs and words. The same applies to C++; source code formatting is equally important. Consider code 3.5 and code 3.6 and how formatting can be of use:
Code 3.5
#include <iostream>
int
main
(
)
{
int
a
;
a
=
5
;
std
;;
cout
<<
a
<<
‘\n’
;
}
Code 3.6
#include <iostream>
Int main () {int a;a=5;std;;cout<<a<<’n\;}
Both code 3.5 and code 3.6 are the same thing and are both valid C++ codes. However, most people would agree that Code 3.6, the formatted version of the original code in Code 3.5, is easier to read and understand more quickly. C++ is a kind of language that gives the programmer a vast freedom to format source code. A compiler reads a source code character by character (one symbol at a time) from left to right before going to the next line. Although spaces help to increase readability, spaces are not allowed in some places, for example, in variable names and reserved words; they must appear unbroken. Also, multi-symbol operators like << can’t be separated with space, amongst other examples.
Even if in C++, you’re not forced to use a particular kind of style while writing code, it helps to maintain a consistent style throughout the code you’re writing. Source codes that are not properly formatted takes a longer time to develop into a correct software because programmer’s mistake hides better in a poorly formatted code. There are tools you can use like the pretty printer to quickly format arbitrarily formatted C++ source code into a properly formatted one.
Errors and Warnings
Because beginners are inexperienced in programming, they tend to make a lot of mistakes while generating source codes. It could also be because they are not familiar with the programming language. That’s why they make a lot of mistakes. Whatever could be the reason for mistakes, programming error falls into one of three categories:
  1. Compile-Time Error
When a developer misuses programming language, it results in a compile-time error. A syntax error is a common type of compile-time error. For example, the statement below is syntactically correct:
a = b + 2;
However, when we consider another example below, by replacing the assignment, and slightly modify the version, it becomes a syntax error.
b + 2 = a;
The statement above will report an error in the visual C++ compiler, among other things:
error C2106: ‘=’: left operand must be i-value
A compiler can also generate an error for a syntactically correct statement. Consider the example below,
a = b + 2
If the values of a and b have not been declared, it would cause an error. The visual C++ compiler would report
error C2065: ‘b’: undeclared identifier
  1. Run-Time Error
The structure rule of a C++ language is not violated thanks to the compiler. The compiler can detect the malformed assignment statement and using of variables before declaration. Some types of violation of language can’t be detected at compile time. In a case like this, the program wouldn’t complete by run into an error known as the run-time error. We commonly associate this type of error in a program as “crashed.” Consider Code 3.7 for better understanding:
Code 3.7
// File dividedanger.cpp
#include <iostream>
int main () {
int dividend, divisor;
//Get two integer from the user
std::cout << “Please enter two integers to divide”;
std::cout >> divided >> divisor;
// divide them and report the result
std::cout << dividend << “/” << divisor << “ = “
<< dividend/divisor << ‘\n’;
}
Using the dividend/divisor expression can be potentially dangerous because if you instead of typing 20 and 5 type 20 and 0, the program would report and error and then terminates.
  1. Logic Error
In Code 3.7 above, consider replacing the expression dividend/divisor with divisor/dividend. The compiler would run with no errors. This replacement works perfectly fine unless a value of zero is entered as the dividend. The answer it would compute with a zero dividend will not be correct. The only time when a correct answer would be printed is when the dividend is equal to the divisor. In other words, when the program has an error, and the compiler nor the run-time system can’t detect it, it’s known as logic error.
Also, errors that escape compiler detection are known as bugs. Because the compiler can’t detect the error, bugs are major issues for developers. This is particularly an issue because, in a complex program, the bugs are hard to find because they reveal themselves in certain situations, so they are difficult to reproduce while testing.
  1. Compiler Warning
You may get a warning by your compiler which marks a violation of the rules of the C++ programming language. It is a notification to the developer that the code contains a construction that will potentially cause problems. Consider Code 3.8 for more explanation:
Code 3.8
// unintialized.cpp
#include <iostream>
int main () }
int n;
std::cout << n << ‘\n’;
}
In the code example above, the programmer is attempting to print the value of a variable before giving it a known value. Trying to run this program on a compiler would display the following message on the Visual C++ compiler: 
warning C4700: uninitialized local variable ‘n’ used
Arithmetic Examples
In C++, you can perform complex arithmetic expressions determined by an operator by operator basis. Take for example, in Code 3.9 below; we would be attempting to convert a temperature from degree Celsius to degree Fahrenheit
F = (C  x 9/5) + 32
Code 3.9
#include <iostream>
int main () {
double degreesC, degreesF;
//Prompt user for temperature to convert
std::cout << “Enter the temperature in degrees C: “;
//Read in the user’s input
std::cin >> degreesF;
//Perfeorm the conversion
degreesF = (C x 9/5) +32;
// Report the result
std::cout << degreesF << ‘\n’;
}
Code 3.9 has documented comments that explains the purpose of each code. You can also make use of C++ to convers time by using modulus and integer division to split up the given number of seconds to hours, minutes and seconds. Consider code 3.10 for how it’s done:
Code 3.10
#include <iostream>
int main () {
int hours, minutes, seconds;
//First, compute the number of hours in the given number of seconds
Hours = seconds / 3600; // 3600 seconds = 1 hours
//Compute the remaining seconds after the hours are accounted for
seconds = seconds % 3600;
//Next, compute the number of minutes in the remaining number of seconds
minutes = seconds / 60; //There are 60 seconds in a minute
//Compute the remaining seconds after the minutes are accounted for
seconds = seconds % 60;
//Report the results
std::cout << hours << “ hr, “ << minutes << “ min, “
<< seconds << “ sec\n”;
}
In the conversion of time code, if you had entered 10,000 the program would have printed 2 hours, 46 minutes, and 40 seconds.
Integers vs. Floating-Point Numbers
Using the floating-point numbers comes with a bunch of advantages than the integers. Using the double statement with the floating-point number have a much greater range of values than any other integer type. One of the advantages floating point has over integer number is can have fractional parts. Although integers have one big advantage over floating-point numbers because they are exact.
Bitwise Operators
Together with the common arithmetic operation, we introduced earlier, there are other special-purpose arithmetic operations. This special operation allows developers the freedom to manipulate and examine the individual bits making up data values. This whole special operator is otherwise known as bitwise operators. These operators consist of characters like <<, >>, ^, ~, |, and &. Generally, application developers do not need to make use of the bitwise operator very often. Bitwise has also been useful in bit manipulation, which is essential in so many systems programming tasks.
Algorithms
An algorithm is simply a finite sequence of steps where each step takes a finite length of time often used to solve problems and compute results. A computer program is an example of an algorithm, the same as a recipe to make lasagna. In whatever example, an algorithm is always pretty simple. Considering another example, if a and b are integer variable in a program. How can we interchange the values of the two variables is pretty easily? Well, we would want to give the value of a to b’s original value. Check out the statement below; it may seem reasonable:
a = b
b = a
But the issue here is with the section code coming after the first statement is executed. A and b have the same value of b’s original value. The second assignment does nothing in changing the values of a and b because it is superfluous. So, the solution here is that there is a need for a third variable that needs to remember what the original value is before it is reassigned. The correct way to write the code to swap is:
temp = x;
a = b
y = temp;
In the example above, there is an emphasis on the fact that algorithms have to be specified precisely. Even though informal notions on solving problems are valuable in the early stage of programing design, coding program requires a correct detail description of the solution.