Intro to C++ : Using Expressions, Statements and Operators

Statements

C++ Programs are made up of statements, which are commands that end with a semicolon (;).

The assignment operator
Below, you see a statement assign the variable x to equal the sum of a+ b.

x = a+b;

If statements
Used to control the program flow based on some condition, it’s used to execute some statement code block if the expression is evaluated to true. Otherwise, it will get skipped.

#include <iostream> 
using namespace std;
int main()
{
int a = 15, b = 20;
if (b > a) {
cout << "b is greater" << endl;
}
system("PAUSE"); }

Another example is the if statement which evaluates the test expression inside parenthesis. if test expression is evaluated to true, statements inside the body of if is executed. if test expression is evaluated to false, statements inside the body of if is skipped.

Compound Statements

Several statements can be grouped together as a compound statement, which begins with an open brace and then close with a closing brace. The if and if-else conditions are often are followed by compound statements.

//example of a conditional statement that is a compound statement#include <iostream>
using namespace std;
if (zombies=== 0)
{
cout << "No more zombies in Nation Z!\n"
score += 1000;
}

What the code does is two things when zombies equal zero, it will display β€œNo more zombies in Nation Z!” If the zombies don’t equal 0, neither of these things will occur at all.

if (x == y){
cout << "x and y are equal." << endl;
cout << "Isn't that nice?";
they_are_equal = true;
}

Conditional Statements

The if Statement

if (zombies == 0);
{
cout << "No more zombies!\n";
}

The else Clause

An if statement can be followed by an optional else if…else statement, which is very useful to test various conditions using single if…else if statement.

if(boolean_expression 1) {
// Executes when the bool expression 1 is true
} else if( boolean_expression 2) {
// Executes when the bool expression 2 is true
} else if( boolean_expression 3) {
// Executes when the bool expression 3 is true
} else {
// executes when the none of the above condition is true.
}

When using if , else if, else statements there are few points to keep in mind.

  • An if can have zero or one else’s and it must come after any else if’s.
  • An if can have zero to too many else if's and they must come before the else.
  • Once an else if succeeds, none of the remaining else if’s or else’s will be tested.

WhiteSpace
Any spaces, tabs, and newline characters are called whitespace. The complier ignores the whitespace the first chance it gets.

x = a + b;
x = a + b;
Note- Cannot use a whitespace for a variable.
e.g highScore does not equal to high Score.

Expressions

An expression is any statement that returns a value.

a = b + 1;

Operators

An operator is a symbol that causes the compiler to take an action such as assigning a value or performing multiplication, division, or another mathematical operation.

Assignment Operators (=)
Assignment operator is the only operator which can be overloaded but cannot be inherited.

Be aware. Operator = (one equal sign) is not the same as operator == (two equal signs), the first is an assignation operator (assigns the right side of the expression to the variable in the left) and the other (==) is a relational operator of equality that compares whether both expressions in the two sides of the operator are equal to each other.

Mathematical Operators (+, - , *, /, %)
Used to perform basic mathematical operations. Modulus operator cannot be used with floating-point numbers.

  • Addition (+) ,
  • Subtraction (-) ,
  • Division (/)
  • Multiplication (*)
  • Modulus (%)

Combining Operators (+=)

Operators    Comparative
╔═════════╦════════════════════════════╗
β•‘ == β•‘ Equality β•‘
β•‘ != β•‘ Inequality β•‘
β•‘ > β•‘ Greater Than β•‘
β•‘ < β•‘ Less than β•‘
β•‘ >= β•‘ Greater than or equal to β•‘
β•‘ <= β•‘ Less than or equal to β•‘
β•šβ•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•

Logical Operators (&&)(||)(!)
If two statements are connected using AND (&&)operator, the validity of both statements will be considered, but if they are connected using OR (||) operator, then either one of them must be valid. The third logical NOT (!) operator is useful in C++ programs to toggle the value of a variable in successive loop iterations with a statement like

a = !a

These operators are mostly used in loops (especially while loop) and in Decision making.

Increment and Decrement Operators (Most common is ++ and - -).
The increase operator (++) and the decrease operator (--). They increase or reduce by 1 the value stored in a variable. They are equivalent to +=1 and to -=1,

a++;
a+=1;
a=a+1;
a--;
a-=1;
a=a-1;

Prefix and Postfix Operators (++ and - -)
The increment operator ++ and decrement operator -- can be used either before or after a variable name to achieve different results. An operator placed before a variable’s name is called a prefix operator, as in this statement:

++count;

A concrete example to show the difference between ++count and count++

int x = 5;
int sum = ++x;

After these statements are executed, the x variable and sum variable both equal 6. The prefix operator in ++x causes x to be incremented from 5 to 6 before it is assigned to sum. Now compare it to the example below.

int x = 5;
int sum = x++;

This causes sum to equal 5 and x to equal 6. The postfix operator causes x to be assigned to sum before it is incremented from 5 to 6.

Relational Operators
These operators establish a relationship between operands. The relational operators are : less than (<) , greater than (>) , less than or equal to (<=), greater than equal to (>=), equivalent (==) and not equivalent (!=).

You must notice that assignment operator is (=) and there is a relational operator, for equivalent (==). These two are different from each other, the assignment operator assigns the value to any variable, whereas equivalent operator is used to compare values, like in if-else conditions.

int x = 10;  //assignment operator
x=5; // again assignment operator
if(x == 5) // here we have used equivalent relational operator, for comparison
{
cout <<"Successfully compared";
}

Conditional operator ( ? ).
The conditional operator evaluates an expression and returns a different value according to the evaluated expression, depending on whether it is true or false. Its format is:

condition ? result1 : result2

if condition is true the expression will return result1, if not it will return result2.

7==5 ? 4 : 3 returns 3 since 7 is not equal to 5.7==5+2 ? 4 : 3 returns 4 since 7 is equal to 5+2.5>3 ? a : b returns a, since 5 is greater than 3.

sizeof()
This operator accepts one parameter, that can be either a variable type or a variable itself and returns the size in bytes of that type or object:

a = sizeof (char);

This will return 1 to a because char is a one byte long type.

The value returned by sizeof is a constant, so it is always determined before program execution.

Order of the Precedence

Values produced by complex expressions depend on the order of precedence, which is the order in which expressions are evaluated.

int a = 1 + 3 * 2 NOTE- Multiplication has higher precedence than addition. 

Looking at the table, operators are evaluated from the top of the table down. Operators with the same precedence are evaluated from left to right or right to left, as indicated on the table.

 Level       Operators          Evaluation╔══════════════════════════╦════════════════╗
β•‘ 1 β•‘ ( ) . [ ] -> :: β•‘ Left to Right β•‘
β•‘ 2 β•‘ * & ! ~ ++ -- + - β•‘ Right to Left β•‘
β•‘ β•‘ sizeof new delete β•‘ Left to Right β•‘
β•‘ 3 β•‘ . * -> * β•‘ Left to Right β•‘
β•‘ 4 β•‘ * / β•‘ Left to Right β•‘
β•‘ 5 β•‘ + / β•‘ Left to Right β•‘
β•‘ 6 β•‘ << >> β•‘ Left to Right β•‘
β•‘ 7 β•‘ < <= >>= β•‘ Left to Right β•‘
β•‘ 8 β•‘ == != β•‘ Left to Right β•‘
β•‘ 9 β•‘ & β•‘ Left to Right β•‘
β•‘ 10 β•‘ ^ β•‘ Left to Right β•‘
β•‘ 11 β•‘ | β•‘ Left to Right β•‘
β•‘ 12 β•‘ && β•‘ Left to Right β•‘
β•‘ 13 β•‘ || β•‘ Left to Right β•‘
β•‘ 14 β•‘ ?: β•‘ Right to Left β•‘
β•‘ 15 β•‘ = *= /= += -= %= β•‘ Right to Left β•‘
β•‘ β•‘ β•‘ β•‘
β•‘ β•‘ <<= >>= &= ^= |= β•‘ Right to left β•‘
β•‘ 16 β•‘ , β•‘ Left to right β•‘ β•šβ•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•

Sample Problem.

x = 2 + 3 % 4

Binary operator % has higher precedence than operator + or operator =, so it gets evaluated first:

x = 2 + (3 % 4)

Binary operator + has a higher precedence than operator =, so it gets evaluated next:

x = (2 + (3 % 4))

Associativity

Associativity defines -in the case that there are several operators of the same priority level- which one must be evaluated first, the rightmost one or the leftmost one.

All these precedence levels for operators can be manipulated or become more legible using parenthesis signs ( and ), as in this example:

a = 5 + 7 % 2;

might be written as:

a = 5 + (7 % 2); //ora = (5 + 7) % 2;

So if you want to write a complicated expression and you are not sure of the precedence levels that will take place, make sure to always include the parenthesis. Congrats! Next we will be covering arrays and strings.

If you enjoy this, don’t miss the other articles in this order.

  1. [Intro to C++ : Your First Program]
  2. [Intro to C++ : Variables, Constants, & Data Types]
  3. [Intro to C++ : Using Expressions, Statements and Operators]
  4. [Intro to C++: Managing Arrays & Strings]
  5. [Intro to C++: Controlling the Flow]
CyberCode Twins πŸ‘Ύ πŸ‘Ύ

Written by

#TEDx SpeakersπŸŽ™οΈ| M.I.T Media Lab BC Alumni ⛓️| Top 5 IBM #SmartCities Finals πŸŒ‡ | πŸš€PR πŸ‡΅πŸ‡· LA | #TwitchDev #Blockchain #AI| CyberCodeTwins.com | shEOS.org

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium β€” and support writers while you’re at it. Just $5/month. Upgrade