Professional Documents
Culture Documents
Sum of 3 integers
int x = 2;
int y = 4;
int z;
z = x + y + 3;
this code creates two integer variables x and y with initial values, creates a third
integer variable z, and sets the value of z to the value of x + y.
it means "take x, multipy it by itself, and assign the resulting value back to x". Now
x would have the value 4.
The expression "x = x + 1;" (increasing the value of x by 1) tends to occur a lot in
programming, so C++ has a shorter way of writing this: the piece of code "x++;"
has exactly the same effect. Similarly "x = x - 1;" and "x--;" are equivalent. For
example, in the following lines of code, x has initial value 3, but has final value 5.
4. Division operation
int x = 4;
int y = x / 3;
The "int" means that y is a whole number. In this expression, the computer will
discard the non-integer part of the value of x/3. So since 4/3 = 1 + 1/3, y will get
the value 1; y is "rounded down". If the expression is negative, then the resulting
value will get "rounded up" (this is a convention, and suits the way the computer
calculates the numbers). So for example, the value of (-4)/3 = -1 - 1/3, so its
integer part is -1 (and not -2).
5. Remainder expression
int x = 11;
int y = x % 4;
The value of the expression "x % y" is the remainder of x when it is divided by y.
For example, if x has the value 11 and we write "int y = x % 4;", then z will have
the value 3.
6. Boolean function
bool a = false;
bool b = true;
bool c = (a || b) && (a || true);
Similarly to how we can write expressions for integer variables which use multiple
operators and mix variables with numbers, we can do the same with boolean
variables. For example, in the above code, c will get the value true. || is the OR
operator and && is the AND operator.
7. If statements
int x = 6;
int y = 5;
if ( x > y )
{
cout << "x is bigger than y" << endl;
}
This code outputs the value of the natural logarithm of 20 which is 2.9957.