|
||
|
|
| Learn to program in C++ | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Posted July 2, 2006. Written by John Zervos, author of the text Byte Into C++ (2002). Tertiary Press: Melbourne. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| This
article provides a comprehensive yet simple to understand treatment of the
C++ language for beginners. The article is divided into a series of
separate lessons as follows:
Lesson 1 - Introduction |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
Operator |
Description |
|
+ |
Add |
|
- |
Subtract |
|
* |
Multiply |
|
/ |
Divide |
|
% |
Modulus (remainder) |
|
= |
Assignment |
Strictly speaking, the assignment (equals) operator is not an arithmetic
operator but is shown here for completeness, as it is used in most arithmetic expressions.
Formulating expressions
Expression statements normally have a variable as the left-hand value, followed by an assignment operator, followed by a mathematical expression. Some examples are shown below:
speed = distance / time;
count = count + 2;
area = base * height * 0.5;
newPrice = oldPrice - discount;
When formulating expressions in this way, it is important to understand the precedence of operators. This is, in which order operators are read by the compiler in a statement. For operators listed above, *, /, and % are evaluated before + and -. The = operator is evaluated last. Consider the following code:
A = B + C * D;
The compiler will evaluate C times D first, then add B to it. This gives a different result to adding B and C then multiplying that result by D. If the latter is what you actually wanted, you can use parentheses (brackets) to force the order of precedence as shown below:
A = ( B + C ) * D;
Remember that the C++ compiler ignores whitespace, and so the spaces in the expressions above (shown for clarity) can be omitted if you prefer.
Unary operators
Unary operators perform their operation on a single variable only. Two widely used unary operators are shown below:
|
Operator |
Description |
|
++ |
Increment (add 1) |
|
-- |
Decrement (subtract 1) |
Examples of their use are
shown below:
count++; // Increment the counter
itemsLeft--; // Decrement number of items left
The precedence of these operators depends on their placement, giving four possibilities. These are outlined below:
count++; // Post-increment
++count; // Pre-increment
count--; // Post-decrement
--count; // Pre-decrement
If the incrementing or decrementing is pre, this gives it a very high precedence and is done before any other part of the expression is evaluated. If the incrementing or decrementing is post, this gives it a very low precedence and is done after all other parts of the expression are evaluated. An example is shown below:
int A, B = 2;
A = B++ * 2;
In this example, variable B is post-incremented. This means variable A will be evaluated with B's original value of 2, and so the value of A will be 2 * 2 = 4. B will then be incremented to 3. Had B have been pre-incremented, the story would be a little different:
int A, B = 2;
A = ++B * 2;
This time, B is pre-incremented and so is incremented to 3 before A is evaluated. The value of A will be evaluated with B's incremented value of 3, and so the value of A will now be 3 * 2 = 6.
Assignment operators
Statements such as the following are quite common:
count = count + 2;
This means "let the the new value of count be equal to the current value of count plus two". In other words, increase the value of count by two. This statement has some redundancy in it as the variable count is used twice. Therefore, C++ allows the following syntax:
count += 2;
The following assignment operators are supported: =, +=, -=, *=, /=, %=.
Mathematical functions
When more complex mathematical operations are required, such as trigonometric and logarithmic functions, prewritten functions are called from an external library. To use these functions you'll need to include the cmath header file as shown:
#include <cmath>
Some of the functions
available are listed in the table below:
|
Function |
Value returned |
|
sqrt(n) |
Square root of n |
|
pow(m,n) |
m raised to the power of n (mn) |
| log10(n) | Base 10 logarithm of n |
| log(n) | Natural logarithm of n |
| sin(n) | Sin of n radians |
| cos(n) | Cos of n radians |
| tan(n) | Tan of n radians |
The parameters and m in the table above can be replaced with any variable
declared as double type. Two examples are shown below:
dB = 10 * log10(ratio);
addresses = pow(2,bits);
Random numbers
There are often times when you'll want to generate a random number in a program to make it unpredictable. Examples include choosing random questions from a question bank, displaying a random quote of the day, rolling dice, and so on. To generate a random number, the rand() function is used. Normally the modulus operator is also used to set the limits of the random number returned. An example is shown below:
number = rand() % 100; // Returns a number between 0 and 99
As described above, this statement returns a number between 0 and one less than the modulus number. Here's away to return a random number between 1 and 6 to simulate the roll of a die:
face = rand() % 6 + 1; // Returns a number between 1 and 6
To make the number returned different each time, you need to seed the random number generator. This is done by calling the srand() function and using a time function as its argument. This is shown below:
srand(time(0)); // Seeds the random number generator from the timer
This function only needs to be called once at the start of the program. You need to include the ctime header file for the time function to work.
Relational operators
Relational operators are used in expressions that compare values. The six relational operators are described in the table below:
|
Operator |
Description |
|
== |
Equality (is equal to) |
|
!= |
Inequality (is not equal to) |
| > | Greater than |
| >= | Greater than or equal to |
| < | Less than |
| <= | Less than or equal to |
Note: Do not
confuse the assignment operator, =, with the equality operator ==.
Boolean expressions
Boolean expressions, expressions that use relational operators, are evaluated by the compiler as being either true (1) or false (0). Here's an example
mark < 50
If the value of mark is less than 50, that expression will be evaluated as true, otherwise it's evaluated as false. Boolean expressions are used as part of selection and iteration statements covered in the following lessons.
Boolean operators
Boolean expressions
can be made more complex by joining them using Boolean operators. The
Boolean operators are shown in the table below:
|
Operator |
Description |
|
! |
NOT |
|
&& |
Logical AND |
| || | Logical OR |
The NOT operator
simply changes a true to a false and a false to a true. The AND operator
requires both expressions to be true for the result to be true, and the OR
operator requires at least one expression to be true for the result to be
true. here's an example:
(classMark >= 50) && (examScore > 65)
In this example, classMark must be greater than or equal to 50 and examScore must be greater than 65 for the entire expression to be true. Here's another example:
(distance > 1000) || (time < 300)
In this example, the entire expression is true if distance is greater than 100, or time is less than 300, or both. here's an example using the not operator:
!(A < 3)
Here, if A is less than 3 the bracketed expression is true, but the NOT operator will invert this, making it false. In this case, it's the same as saying (A >= 3).
| © 2006 learn2dostuff.com |