Expressions,Statements, and Operators πŸ‘€

Section Overview:

Expressions, Statements, and Operators:

  1. Expressions 
  2. Statements and Block Statements
  3. Interesting Exercise
  4. Operators
  • Assignment 
  • Arithmetic
  • Increment and Decrement 
  • Equality
  • Relational
  • Logical 
  • Compound Statement
  • Precedence

Expressions:

An expression is:
  • The most basic building block of a program.
  • "A sequence of operators and operands that specifies a computation".
  • Computes a value from a number of operands.
  • There is much, much more to expressions - not necessary at this level.
Examples:
  • 34                               // Literal 
  • favourite_number     //Variable 
  • 1.5+2.8                    // Addition
  • 2*5                         //Multiplication
  • a>b                       // Relational
  • a=b.                    // Assignment

Statements:

A statement is:
  • A complete line of code that performs some action.
  • Usually terminated with a semi-colon
  • Usually contains expressions
  • C++ has many types of statements like expression, null, compound, selection, iteration, declaration, jump, try blocks, and others.
Examples:
  • int x;                         // Declaration
  • fav_no = 21;            // Assignment
  • 1+2                          // Expression
  • x = 3*5;                  // Assignment 
  • if a>b cout<<"a is greater than b";     // If Statement

Using Operators:

C++ has a rich set of operators:
  • Unary, binary, ternary
Common operators can be grouped as follows:
  • assignment 
  • arithmetic 
  • increment/decrement 
  • relational
  • logical 
  • member access
  • other

Assignment Operator(=):

LHS = RHS
  • RHS is an expression that is evaluated to a value
  • The value of the RHS is stored to the LHS
  • The value of the RHS must be type compatible with the LHS
  • The LHS must be assignable
  • Assignment expression is evaluated to what was just assigned
  • More than one variable can be assigned in a single statement.



Arithmetic Operators:


  • ' + ' - addition
  • ' - ' - subtraction
  • ' * ' - multiplication
  • ' / ' - division
  • ' % ' - modulo or reminder 
  • +, -, * and / operators are overloaded to work with multiple types such as int, double, etc.
  • % only for integer types.



Here in the above example, it is clearly explained how to handle each arithmetic operator specified above.

Exercise on Arithmetic Operators:

Assignment 1:
  • In this exercise, you will write a program that uses the assignment operator = to change the value of an initialized variable as well as assign the value of one variable to another.
  • Begin by declaring and initializing the integer variable num1 to the value 13.
  • Now declare and initialize the integer variable num2 to the value 0.
  • Use the assignment operator to change the value of num1 to 5.
  • Now use the assignment operator to assign the value of num1 to num2.
Assignment 2:

In this exercise, you will write a program that uses arithmetic operators to manipulate an integer number.
  • Declare any number to test your program.
  • In order to complete this exercise, you will have to update the value contained within the variable number by using the contained values as an argument in the statement.
  • This can be done through the use if the assignment operator  =  in the following way:
  • e.g. number = number + 4
  • Let's assume that number is currently holding the value 3. This means that the above statement is equivalent to number = 3 + 4. Thereby, through the assignment operator, the new value of number will be 7.
  • Use arithmetic operators in the manner and order in which they are listed below. For those who feel inclined, try challenging yourself by completing all operations in one statement remembering the rules of PEMDAS.
  • Use the multiplication * to double the value of the variable number and store the result back in number.
  • Use the addition operator + to add 9 to the variable number and store the result back in number.
  • Use the subtraction - to subtract 3 from the variable number and store the result back in number. new value.
  • Use the division operator / to divide the variable number by 2 and store the result back in number.
  • Use the subtraction operator - to subtract the variable named original_number from the variable number and store the result back in number.
  • Use the modulo operator % to find the remainder of the new value when divided by 3 and store the result back in number.

Increment and Decrement Operators:


This operator looks quite easy but there is a lot of confusion in understanding this operator.
  • Increment Operator  -  ++ 
  • Decrement Operator -   --
  • Increments or Decrements  it operand by 1.
  • Can be used with integers, floating-point types and pointers
  • Prefix ++num
  • Postfix num++
  • Don't overuse this Operator!
  • ALERT!!! Never use it twice for the same variable in the same statement. 

Here in the above example, we are performing simple increment operations to get some basic understanding. As shown in the example the counter value gets incremented by 1 by 1 and we will get the output as 10, 11, 12, 13.
There are some examples given below to get some deep understanding of how increment or decrement operators work.






Mixed Type Expressions:

C++ operations occur on the same type operands.
If operands are of different types, C++ will convert one.
Important! since it could affect calculation results.
C++ will attempt to automatically convert types. If it can't, a compiler error will occur.

Conversions 
  • Higher vs. Lower types are based on the size of the values the type can hold
  1. Long double, double, float, unsigned long, long, unsigned int, int
  2. short and char types are always converted to int.
  • Type Coercion: Conversion of one operand to another data type.
  • Promotion: Conversion to a higher type.
  1. Used in mathematical expressions
  • Demotion: Conversion to a lower type
  1. Used with an assignment to lower type.
We can use static_cast<double> to change from one type to another type.

Exercise on Type Casting:

Input:

  • Ask the user to enter 3 integers 
  • Calculate the sum of integers then 
  • Calculate the average of 3 integers.

Output:

  • Display the 3 integers entered 
  • The sum of 3 integers and the average of the 3 integers 

Testing for Equality:

The == and =! operators

  • Compares the values of 2 expressions 
  • Evaluates to a boolean(True or False, 1 or 0)
  • Commonly used in control flow statements like if-else, while, etc.
  • exp == exp2
  • expr1 != expr2
  • 100 == 200
  • num1 != num2

Relational Operators:


  • >: Greater than
  • > =: Greater than or Equal to 
  • < : Less than
  • <= : Less than or Equal to 
  • <=> : Three-way comparision


Go through this code and try it for your clear understanding of Relational Operators. In this program, the values stored in two variables can be compared using the following operators to find determine the relation between them.

Logical Operators:


  • !: Negation
  • && : Logical And 
  • || : Logical Or
We can write some pretty combine logic suppose if we combine relational and logical operators we can solve many algorithms.

Example: 

  • num1 >= 10 && num1 < 20
  • num1 <=10 || num1 >= 20
  • !is_raining && temperature > 32.0
  • is_raining || is_snowing
  • temperature > 100 && is_humid || is_raining

Short-Circuit Evaluation:

When evaluating a logical expression C++ stops as soon as the result is known

  1. exp1 && exp2 && exp3
  2. exp1 || exp2 || exp3

In the first statement if any of the expression is false then there is no chance that the expression is True this is called short-circuit evaluation.
In the second statement if any of the expression is true then there is a chance that the expression is True.

Compound Assignment:


  • a += 1;                       // a = a+ 1
  • a /= 5;                        // a = a / 5
  • a *= b+c;                   // a = a*(b+c)
  • cost += items * tax;  // cost = cost + (items * tax)

Exercise:

For this program I will be using US dollors and cents.
Write a program that asks the user to enter the following:
An integer representing the number of cents
You may assume that the number of cents entered is greater than or equal to zero 
The program should then display how to provide that change to the user.
In the US:
  • 1 dollar is 100 cents 
  • 1 quarter is 25 cents
  • 1 dime is 10 cents
  • 1 nickel is 5 cents, and 
  • 1 penny is 1 cent 
Here is a sample run:
Enter an amount in cents: 92
You can provide this change as follows:
  • dollars : 0
  • quarters : 3
  • dimes: 1
  • nickels: 1
  • pennies: 2
Feel free to use your own currency system.
Also, think of how you might solve the problem using the modulo operator.
Have fun and test your program !!

























Comments

Popular posts from this blog

Basic things You need to Know in C++😁

Arrays and Vectors ❤️