What is the modulo operator used for?

This section describes how a program writes data in variables, reads them out again, calculates them with other variables and constants and stores them again in variables.

allocation

Equal sign

During the initialization, the equal sign was already used to pre-assign a value to a variable. The equals sign is also used otherwise when a variable is to be given a new value. There is a subtle difference between the pre-assignment or initialization, which takes place when the variables are created, and the assignment, as the assignment with values ​​is called when the variable already exists.

The goal of the assignment is always to the left of the equal sign. In general, that's a variable. The data source is on the right-hand side of the equal sign. This can be another variable, a numerical value or a calculation. The data source on the right-hand side of an assignment is commonly referred to as an expression. The English name for this is "expression". An expression is a construct that supplies a value and can thus serve as a data source. The following example shows several assignments. The arithmetic operations are also anticipated a little.

[Assignments]

VAT rate = 16; Net = 200; VAT amount = net * VAT rate / 100; Gross = net + VAT amount;

L-value

The goal of the assignment is always on the left-hand side of the equal sign. Typically this is a variable. If it says something else, most compilers will bring up an error message that reads "L-Value expected" or something similar. Translated directly, the message means that a "left value" is expected, that is, something that can be on the left side of an assignment. The L-Value has to be something that can be assigned something else. As you will see later, not all variable constructs are accepted as L-values.

Cascading assignment

The special feature of C ++ is that you can assign the same value to several variables in one statement. Think of it as an assignment passing its value through to the left. This ability enables a line like the following:

[Cascading assignment]

a = b = c = d = 5 + 2;

The instruction is processed from the data source. 5 + 2 equals 7. This 7 becomes the variable d assigned. The result of the assignment is this value 7, which is then c is assigned. From there it goes on to the variable b and finally to variables a. As a result, all listed variables contain the value 7.

Arithmetic artist

Basic arithmetic

In the previous listing you saw how you can calculate in a program. In the end, it doesn't look very different from writing down an arithmetic problem on a piece of paper. The only thing that is somewhat unusual is that the assignment target and an equal sign appear on the left. The multiplication sign is the asterisk and the division sign is the slash. Plus and minus signs look like you'd expect. You can even use the minus sign as a prefix as usual.

rest

The modulo calculation is a special type of calculation. It delivers the remainder of an integer division. If you remember how you divided in the first grades, you might think of sentences like: "25 divided by 7 is 3, the remainder is 4". This remaining calculation is also available under C ++. It is known as the modulo calculation. The percent symbol is used as the operator symbol. Remainder = 25% 7; // So the rest is 4

point before line

The laws of mathematics are also respected in C ++. The old rule of “point calculation comes before line calculation” is adhered to here as well. This rule states that the multiplication and the division are carried out before an addition or subtraction if both are equivalent.

From left to right

Binary operators, i.e. arithmetic symbols that link two expressions together, are generally left-binding. This means that they will be executed from left to right if the priority is the same. That means that it is evaluated as. Assignment is an exception. This is evaluated as. The assignment operator is therefore right-binding. Single-digit operators are also right-binding. This also includes the operator, which you will get to know in the course of this section.

Unclear order

In very special special situations, it cannot be clearly clarified in which order the individual operators are executed. The following example can be interpreted in several ways. a = 1 b = (a * 2) + (a = 2);

The assignment in the right brackets results in 2, as was already mentioned above for the cascading assignments. But whether the assignment is carried out before or after the left parenthesis remains unclear. The variable b could contain both 4 and 6 after this line.

KISS

Programs develop a considerable amount of complexity anyway. That is why you should avoid ambiguity where possible. If expressions get confusing, you should use brackets or even split the calculation into several intermediate steps. Your goal should be to keep your program as simple and clear as possible. In the English-speaking world, there is the KISS rule for this: Keep It Small and Simple. A program that consists of a collection of the most ingenious tricks becomes illegible and is therefore unmaintainable and therefore unprofessional.

Abbreviations

Man tends to be lazy. It's no different for programmers. They act on the principle never to do anything that a computer can do for them, and so it stands to reason that there are ways to keep repetitive tasks as brief as possible.

Increment

To increase the value of a variable by 1, you can write the following line:

[The content of the variable counter increases by 1]

Counter = counter + 1;

Evaluate right side first

This means that the new value of the variable is formed from the old value of the variable plus 1. The right side of the equal sign is evaluated first before it is assigned to the variable on the left. Overall, the line causes the content of the variable Counter increased by 1.

It often happens that the new value of a variable results from its previous value, which is offset against another value. Whenever a value is increased, decreased, doubled or halved, a shorter variant can be used. The following line again shows the value of the variable Counter increased by 1:

[Write lazy increment]

Counter + = 1;

Here the plus sign is combined with the equal sign. So that the plus is not mistakenly interpreted as the sign of the 1, it must come before the equal sign. There must be no space between plus and equal signs. The meaning of the line is: "Add the value 1 to the variable."

It's an obvious thought that this doesn't just work for adding. You can use it in subtracting, multiplying, dividing and doing the modulo calculation.

short notation long spelling
a + = b a = a + b
a - = b a = a - b
a * = b a = a * b
a / = b a = a / b
a% = b a = a% b

Double plus

In the special case that the value is increased by 1, the expression can be shortened even further. To do this, two plus signs are simply appended to the variable.

[Very lazy writing increment]

Counter ++;

You will already have guessed that this double plus gave the language C ++ its name. C ++ corresponds to the C language, which has been increased by one.

Decrement

As expected, there is also a double minus. It does exactly what you suspect: it subtracts the value 1 from the variable. I won't tell you why there is neither a double star nor a double slash. Think of it as one of the last secrets of our earth.

You can also use the double plus or minus on the right side of an assignment. Then, after the variables have been evaluated, their value is increased or decreased. Consider the following example:

[Increment on the right side]

Counter = 5; Sum = 2 + counter ++;

sequence

It is clear that the variable contains the value 6 after these commands. On the other hand, it is a little less clear what value the variable has. If you tap 7 you are correct. As stated above, the variables are only incremented after the evaluation. However, you can also put the double plus in front of the variable. Then the variable is only evaluated after it has been incremented.

[The same, easier to read]

Counter = 5; Sum = 2 + ++ counter;

In this case the variable will have the value 8. If you find the whole thing a bit confusing, that speaks for your taste. I would avoid such a construction in the program. Better to write a few more characters. Then a colleague will understand what you have written more quickly later. The following lines do the same thing and are much easier to read:

[Another result]

Counter = 5; ++ counter; Sum = 2 + counter;

The placing in front of the increment operator is called a prefix. It causes the variable to be incremented first and then evaluated. The adjustment of the operator is called postfix. The variable is evaluated first and only then incremented. Incidentally, the prefix variant is a little more efficient to implement.

The following table provides an overview of the mathematical operators in ascending order of priority.

operator importance example
+ addition a = 11 + 5; (16)
- subtraction a = 11-5; (6)
* multiplication a = 11 * 5; (55)
/ division a = 11/5; (2)
% Modulo a = 11% 5 (1)
++ Increment ++ a; or a ++;
-- Decrement --a; or a--;

Random functions

It may be unusual to come across random numbers, of all things, as the first example of mathematical functions. After all, there are so many serious mathematical functions that C ++ provides. Don't worry: the serious functions will also be discussed later. Random numbers will come in handy for some sample programs. They also do a good job in practice. You can use it to generate data in order to test program parts.

Pure coincidence

A computer generated random number is not really random, but is generated by a function. Good random numbers have two properties: They are difficult to predict and they are evenly distributed. After all, they are not only used for rolling the dice or for card games, but also for simulations that are run through millions of times.

Starting value

There is a start function so that test series can be repeated. It receives a start value as a parameter. If the same starting value is used, the same sequence of random numbers is then always generated.

srand ()

The random number generator is initialized when the function is called. The function has an integer as a parameter that serves as the start value.

Random value

After the random number generator has been initialized once with the function, a quasi-random return value of the type can be called up as often as required by calling. With each new call, the function returns a new random value. Both functions come from the standard library stdlib.

The following little program starts the random numbers once with the value 9. Then the function is called twice and the variable coincidence assigned.

[Random numbers]

#include main () {long random; srand (9); random = rand (); random = rand (); }

RAND_MAX

The constant RAND_MAX contains the largest possible random number. The return value of the function is between 0 and this value. In practice, RAND_MAX is equal to LONG_MAX, so mostly around 2 million.

Modulo

Most programs can do little with that. Typically the programs want to simulate a dice, a lottery number or a playing card. There is a simple method to break down the large numbers to the values ​​6, 49 or 52: You use the modulo calculation. If you want to simulate a dice, calculate modulo 6 and get a value between 0 and 5. Now you only have to add 1 and you have the usual numbers between 1 and 6. augen = rand ()% 6 + 1;

If you really need an unpredictable starting value for a game, I recommend the time functions. The seconds since 1/1/1970 are ideal as a starting value. And if that still seems too calculable to you, use the milliseconds modulo 1000 that have passed in the period of time that the user needed for his input.

Typecast

There are two spellings to convert an expression of one type to another. In C, the expression is preceded by the target type in brackets. In C ++, the notation was introduced that the name of the type is followed by a bracket in which the expression to be converted is located.

int value; Value = (int) AnyWhat; Value = int (AnyWhat);

Automatically

C ++ does some conversions directly without talking about them. A variable or constant is assigned directly to a variable. There are no problems of interpretation here, and any value can be stored in a variable. The opposite way is more difficult. The number 200,000 does not fit into a variable if it only consists of two bytes. Here the compiler will generally issue a warning that relevant information could be lost.

Calculations

It can be particularly tricky if the compiler uses integer values ​​instead of floating point numbers. A classic rule of three will be used as an example. Three tomatoes cost 4 euros. How much do five tomatoes cost? This would be implemented in the program as follows: float SollPreis = (4/3) * 5;

The content of the variable Target price should surprise you: It is 5. The reason is that the compiler executes the expression as an integer calculation and cuts off the decimal places. So the result of the division is 1. Multiply by 5 gives the result mentioned above. Still, you'd rather expect to pay 6.67 euros at the checkout, and the merchant is sure to agree with your point of view. In such cases you can intervene with a type conversion. At least one operand of the division must be converted to value in order to force a calculation.

float target price = (float (4) / 3) * 5;

After this adjustment, the calculation results in the expected 6,66667.

Unnecessary brackets

As an aside, it should be mentioned that the brackets around are superfluous from the point of view of C ++ because the expression only contains point calculations and is then executed from left to right. For this, these brackets have a documentation value. Anyone who later looks for a bug in the program can see immediately how the author wanted to set the priorities. So if there is any doubt about the priorities of expressions, it is better to put a few too many brackets than too few. The compiler will optimize them away anyway.