Skip to main content

Expressions and Operators in C++.

An Expression is composed one more or more operand and operations to be applied on them. 

In C++ Operand can by anything like an integer, a float, or a array and the operations applied to the operands are represented by Operators

We can classify the Operators in three Categories -

  1. Unary Operators.
  2. Binary Operators.
  3. Ternary Operator. ( will be discussed at last )
(Don't try to relate anything about Binary Operators and Binary Numbers.)
1. Unary Operators - Unary operators are those which act on only one operand.(Do you know any operators like this? YES, you have seen them previously), The address of (ampersand (&)) operators and de-reference (*) operator. These two operators are Unary operators, We have used them like - 

#include<iostream>
using namespace std;
int main()
{
    int a = 10;     // Initialization of variable 'a'
    int *b = &a;    // Storing address using unary operators '*' and '&' in b

    return 0;
}

You can easily see that de-reference operator and ampersand operator are both acting on a single operand.

Very important thing to remember is it depends on how you use these operators, for example if you use '*' operator like (a*b), then it is a binary operator, as it is acting on two operands. similarly '&' also can be used as binary operator(Bitwise AND), you will see it later, in thus slide.

2. Binary Operators - As I already discussed, the operators that act on two operands are binary operators.

There are many such operators exist in C++ language. Let's see the table.


We will discuss each of these operators one by one in this Order.

  1. Arithmetic Operators.
  2. Assignment Operators.
  3. Relational Operators.
  4. Logical Operators.
  5. Unary Operators.
  6. Bitwise Operators.
  7. Ternary Operators.
So, let's begin

1. Arithmetic Operators - We are already familiar with these operators. These are operators as we have studied from our childhood. i.e. addition, subtraction etc.Let's see them one by one.
  1. Addition (+) operators - We use it to add two numbers, e.g. (10 + 20) gives us 30 after addition.
  2. Subtractions (-) operator - We use it to subtract numbers, e.g. (10-20) gives us -10.
  3. Multiplication (*) operator - We use it to product/multiply two numbers. e.g. (10*20) gives us 200.
  4. Division (/) operator - We use it divide numerator by denominator, e.g. (10/20) gives us 0.5.
  5. Modulus or Remainder Operator - We use to find the remainder after successively dividing the numerator by the denominator, e.g. (7%4) gives us 3.
#include<iostream>
using namespace std;
int main()
{
    int a = 7;

    cout << a + 3 << endl;      // Addition operator
    cout << a - 3 << endl;      // Subtraction operator
    cout << a * 3 << endl;      // Multiplication operator
    cout << a / 3 << endl;      // Division operator
    cout << a % 3 << endl;      // Modulus operator

    return 0;
}

See output here.
2. Assignment Operators - These Operators can be easily understood with the help a program.

#include<iostream>
using namespace std;
int main()
{

    int a = 10;

    a += 10;        // Equivalent to a = a + 10;
    a -= 10         // Equivalent to a = a - 10;
    a *= 10;        // Equivalent to a = a * 10;
    a /= 10;        // Equivalent to a = a / 10;
    a %= 10         // Equivalent to a = a % 10;

    return 0;
}

The above program is sufficient for understanding these operators.

3. Relational Operators - These Operators describe what is the relation between 2 operands and on the basis of the relation, return some boolean true/false, let's see them one by one.

  1. Greater than (>) operator - If the left operand is greater than right operand, then it evaluates to true.
  2. Greater than or equal to (>=) operator - If the left operand is greater than or equal to right operand, then it evaluates to true.
  3. is equal to (==) - It is different from assignment operator (=), syntactically as well as operationally, If the left operand is equal to the right operand then it evaluates to true.
  4. less than (<) - If the left operand is less than the right operand then it evaluates to true.
  5. Less than or equal to (<=) - If the left operand is less than or equal to the right operand then it evaluates to true.
  6. Not equal to (!=) - If the left operand is not equal to right operand then it evaluates to true.
I am not showing program for Relational operators as we have discussed, if, else and else if statements now,

4. Logical Operators - Logical operators as the name suggest help us to form some logic, from other logical expression, for e.g. Think of going to market only if the weather is good and the day itself is a holiday, Now, there are two conditions are acting here, and to combine those conditions we used a logical connective "and", which can also equivalent to && operator.
let's discuss the different logical operators
  1. Logical and (&&) - If the left and the right expression both evaluate as true, the && operator will evaluate as true. e.g. if(1 < 3 && 3 < 5) is a tautology(the statement which is always true).
  2. Logical OR (| |) - If any one of the expression, either on left or on right side evaluates to true, the OR operator will evaluate to true, e.g. if(1 > 3 || 3 < 4), here even if left expression evaluates to false, but the right expression is true, So, the final result is true.
  3. Logical Not (!) - Actually, it is a unary operator, it makes the true condition false, and false condition true. like if(!(1<3)) will evaluates to false even if 1 < 3 is true.
I am not showing program for logical operators as we have discussed, if, else and else if statements now,

5. Unary Operators - Unary as already stated act on a single operand, We have already seen de-reference and ampersand operator. Now, let's only discuss ++ and -- operator.
  1. Increment operator (++) - It is a upgraded version of assignment operator, but only for a specific task, as in assignment operator we write like, something += something else, but, if the value of something else is "1" then we can replace the whole expression with something++ (post increment) or ++something(pre increment) according to situation. We will cover post increment and pre-increment with some good example in some other slide.
  2. Decrement Operator (--) - We can relate this one with the same example but with something -= something else. and if something else is "1" we can write it in two ways, try to guess them.
Example program -

#include<iostream>
using namespace std;
int main()
{
    int a = 10;
    
    a++; // Increased value by one
    cout << a << endl;  // print 11
    
    a--; // decreased value by one
    cout << a << endl;  // prints 10

    return 0;
}
See output here.

6. Bitwise Operators - Bitwise operators are very useful tricks when it comes to speed of execution, because here the execution taking place of any calculation is at bit level. Let's see how we can use them.
  1. Bitwise AND (&) - Like And operator we have a Bitwise AND too, but we use single ampersand here. It is used to compare the set bits of two numbers (set bits are bits which is turned on i.e. bits with value 1), Bitwise AND is used in bitmasking, one simple use of of Bitwise AND is to find if the number is odd or not, to do so we can simply check the first bit of the given number as we know the weightage of the first bit is 2^0 which is just 1, every other bit of a number will evaluate to a even number of first bit is 0 but if first bit is one the number is guaranteed to be odd. I will show it's syntax while covering the decision making statements in C++.
  2. Bitwise OR (|) - It syntax is a single bar. It is also used in bitmasking. It like OR but the expression here are bits, 1 means true and 0 means false. if any true it's true.
  3. Bitwise XOR(^) - The name looks similar to OR but with extra X, the idea of XOR is if only one of the bit is 1 then it gives true otherwise false, which simply means, both bits should not be same. Simple application could be finding a number occuring odd number of times in an array.
  4. Bitwise LeftShift(<<) - This operator is to shift the bits of number(say N) towards left i.e. from Low significant bit to high significant bit. Which means if we left shift the bits by i numbers than the N = N*2^i and syntax will look like N = (N<<i);
  5. Bitwise RightShift(>>) - This operator is used to shift the bits of a number(say N) towards right, i.e. from High significant bit towards Low significant bit. Which means if we right shift the bits by i numbers than the N = N / 2^i and syntax will look like N = (N>>i);
  6. Bitwise Not (~) - It is a bitwise equivalent of not operator and also a unary operator, the simple application could be to turn off(making 0) the ith bit of a number (say N). Syntax looks like N &= ~(1<<i); I will cover all these topics in a separate slide.
Sample program - 
#include<iostream>
using namespace std;
int main()
{
    int a = 7;
    int b = 10;
    cout << (a & b) << endl;        // Bitwise AND
    cout << (a | b) << endl;        // Bitwise OR
    cout << (a ^ b) << endl;        // Bitwise XOR
    cout << (a << b) << endl;       // Bitwise left shift print a*2^10
    cout << (a >> b) << endl;       // Bitwise rigth shift print 0
    cout << (~a) << endl;           // Bitwise Not is a unary opeator too.
    return 0;
}
See output here.

7. Ternary Operator - Ternary is something that is made up of three parts, but in C++ it is not worthless to specify that those three parts must be of same type, we use ternary operate as following-
Syntax --- (condition) ?  if true Do something : else Do something else;
Now, let's see it in a program.

// Program for printing largest of two numbers?
#include<iostream>
using namespace std;
int main()
{
    int a = 10;
    int b = 20;

    cout << ((a > b) ? a : b) << endl;
}

See output here.

Here, we are directly checking if "a" is greater then "b" then return "a" to output stream (cout) and if not return "b" to output stream (cout).

For the complete list of operators click here.

In the next slide we will 

 Stay tuned for the upcoming content. For any query leave a comment below.


Click the Subscribe button at the top, to follow my every post regarding c++.

References -
  • Lippman, Stanley B. c++ primer 3rd edition(april 2, 1998)
  • Wikipedia
  • Hilite.com for code snippets
  • Ideone.com (for ability to share codes online).

Comments

Popular posts from this blog

Introduction to Computer Science.

 Before directly jumping deeply in c++, let's first start by creating the roots of computer science. In this post we will answer the following question. What is Computer and How it works? What is Program and Operating system? Low Level vs High Level Language? Compiler v/s Interpreter? By Knowing All these basic concepts You will be able to understand the upcoming more complex concepts easily. Let's start answering the above questions. What is Computer and How it works? What is computer? If I answer briefly,  what is computer?  then it is just a calculator used for doing simple calculations. If I have to answer where is computer used?, then I could probably say everywhere. We are surrounded by computer, for example mobile, smartwatches, and personal computer (obviously).  The below image is the first mechanical computer that we used for calculation.                                        Abacus How computer works? The computer's internal functionality is a whole separate bra

C-style strings vs String Class.

Here, we are going to learn about, what are C-Style Strings and what is String class . So, let's start by giving you the introduction. C-Style String is nothing but, an array of characters, and from the term array we can surely assume that these are static in size i.e. the size of these C-Style strings cannot be increased or decreased. String Class is a Built-in class that provide us much more functionality than C-Style String. C-STYLE STRINGS Before learning the String class, which is full-fledged feature of C++, we should rather start by taking a look at some important things about C-Style String. C-Style Strings are actually array of characters that are terminated by a null character "\0". If you are confused with, why null character? The reason is that, It helps us to define, upto which index we have some useful data present in our character array, and after null character there may or may not be some garbage values of characters. Let's first start by showing a

Algorithms, Pseduocodes and FlowCharts.

Some Basic Knowledge. C++ is a general purpose programming language, created by Bjarne Stroustrup and was firstly released in  1985. It is an extension to C language, Reason for that is if you are familiar with C language than you must be familiar with the fact that there are no classes, templates etc. present in C language. Due to which when classes are added to C language it is named as "C with Classes", but C++ is considered as default name now.  Extra thing to remember - In "C++" the symbol "++" after C is post increment symbol and therefore, "C++" means that In C additional features are added. Now, let's define, what are algorithms? Algorithms are nothing but set of rules that must be followed to accomplish some task. (Now, What that mean?😕) let's take an example of swapping two numbers, i.e. if a = 10 and b = 20 after swapping a = 20 and b = 10. How will you write the procedure for this?  (There are many such algorithms). Accordin