You are on page 1of 3


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.

2. Square of a number / multiplication

int x = 2;
x = x * x;

it means "take x, multipy it by itself, and assign the resulting value back to x". Now
x would have the value 4.

3. Number increment (increase the number by 1)

int x = 3;

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;

The program conditionally execute a segment of code depending on the value of a

boolean expression. We do this using an if statement. In the above code, it will
output "x is bigger than y". This is an example of conditional execution - the value
of the (boolean) comparison expression x > y is true, and so the code inside the
brackets { ... } is executed.

8. Exponent operation, x raised to a number (x^n)

//x now gets the value 3^5.
x = pow( 3.0, 5 );
cout << "3^5=" << x << endl;

This code outputs the value of 3 raised to 5, equal to 243.

9. Logarithm, log of a number x

// x is now log base e of 20, or ln(20).

x = log( 20 );
cout << "ln(20)=" << x << endl;

This code outputs the value of the natural logarithm of 20 which is 2.9957.

10.Square root of a number

// x is now square root of 25
x = sqrt( 25 );
cout << "sqrt(25)=" << x << endl;

This code gives you an answer of 5, as the square root of 25.