If you like my posts please leave a comment.

Tuesday, July 24, 2012

C++ OPERATORS AND EXPRESSIONS


Operator:

An operator is one, which works on data items and performs some mathematical calculation or change the data. C++ provides six types of operators.

Arithmetical Operators:

These are general mathematical operators, which work or one or more operands. The operators which always work with two or more operands are known as binary operators.
Example:
+                      Addition
-                       Subtraction
*                      Multiplication
/                       Division
%                     Modulus / Remainder

Note* - Both / & % do division operation on the operands but / returns quotient as the result and % returns remainder as the result of the operation.
Now consider a program illustrating the use some of these arithmetic operators.
// Program to convert time given in minutes into hours and remaining minutes.
#include<iostream.h>
#include<conio.h>
int main()
{
int time, hour,min;
cout<<"\n Enter the time in minutes: ";
cin>>time;
hour=time/60;
min=time%60;
cout<<"\n Hours: "<<hour;
cout<<"\n Minutes: "<<min;
getch();
return 0;
}

Relational Operators:

The operators used to do the comparison of the variables or constants are known as Relational operators. These operators are used to determine the relationship between different operands. There are 6 relational operators
Example:
= =                   Equal to
>                      Greater than
<                      Less than
>=                    Greater than equal to
<=                    Less than equal to
!=                     Not equal to
in C++. A relational logic always produces the True or False result. In C++ True result evaluates to 1 and a False to 0. But comparison between signed and unsigned produces some different result.
While comparing one signed and another unsigned values compilers considers both as unsigned. That is if the signed value is negative, it will be treated as an unsigned value. Also the internal bit, representing the sign will not be considered as sign bit, which produces a contradictory result.
            Consider the following two programs to illustrate this fact more.
//program to compare two signed integers
#include<iostream.h>
void main()
{
int x=-5;
int y=2;
clrscr();
cout<<”\n Relational result is "<<(x>y);
if(x>y)
cout<<"\n x is greater";
else
cout<<"\n y is greater";
}
Output:
Relational result is 0
y is greater

Here in the above program values used are -5 and 2. Binary of -5 is 1101 left most 1 represents the negative sign. Binary of 2 is 0010 left most 0 representing the positive sign of 2. Thus the compiler compares two sing bits and thus the result evaluated correctly i.e. false means 0.

//program to compare one signed and another unsigned integer
#include<iostream.h>
void main()
{
int x=-5;
unsigned int y=2;
clrscr();
cout<<”\n Relational result is "<<(x>y);
if(x>y)
cout<<"\n x is greater";
else
cout<<"\n y is greater";
}
Output:
Relational result is 1
x is greater

In the above program we are comparing one signed integer and other unsigned integers. Now C++ compiler will treat both as unsigned integers. Thus sign bit of these two numbers will not be taken into consideration. So -5 whose binary is 1101 will be evaluated to 13 and 2 whose binary is 0010 will be evaluated to 2. Now when compiler compares it compares as (13>2) and gives result True i.e 1

Logical operators:

Logical operators are used to combine one or more relational expressions. There are basically three types of logical operators present in C++;
Example:
||                       OR
&&                  AND
!                       NOT

Illustration for AND logical test
E.g.
If((a>b) && (c>d))
cout<<”\n Both the conditions are true\n”;
else
cout<<”\n Either one the conditions is not true\n”;

Now in the above example if value of ‘a’ is greater than value ‘b’ also value of ‘c’ is greater than value of ‘d’ then only ‘Both the conditions are true’ line will be as output. Otherwise you will see ‘Either one of the condition is not true’ as the output. This implies that, in the case of && (AND) logical test both the conditions specified should be evaluated to true. Then only the statement immediately after the ‘if’ condition will follow.

Illustration for OR logical test
E.g.
If((a>b) || (c>d))
cout<<”\n Either one of the conditions is true\n”;
else
cout<<”\n None of the conditions is true\n”;

In the above example either the value of ‘a’ should be greater than value of ‘b’ or value of ‘c’ should be greater than value of  ‘d’. if any one these conditions is satisfied than only the line immediately after ‘if’ will be executed and you will see the output as – ‘Either one of the conditions is true’. Otherwise you will see the line ‘None of the conditions is true ‘as output. This implies that, if only one of the two specified conditions with OR (||) operator in between is evaluated to true then only line following the ‘if’ condition will be executed. Otherwise the line followed by ‘else’ will be executed.

Illustration for NOT logical test
The logical NOT (Negation) has only one single condition as an operand; it is a unary operator. This operator enables the programmer to reverse the meaning of a condition.
E.g.
If(!grade==’A’)
cout<<”\n Poor performance\n”;
else
cout<<”\n Good performance\n”;

In the above example if ‘grade’ is not equal to ‘A’ then the condition evaluates to true and you will see the line – ‘Poor performance’ as output. Otherwise you will see the line – ‘Good performance’ as output. So,
Expression is                            NOT Expression evaluates to
False                                                                True
True                                                                 False

Unary and Binary Operators:

Earlier we have discussed what is Binary operator? The operators which always work with two or more operands are known as binary operators. Thus the operators so far we discussed, most of them belongs to Binary operator.  C++ uses some operators which acts on one operand is called as Unary operator. You can use addition and subtraction operators by themselves and when you do this they will be called as Unary operator.
Examples:
int a = -35; // Assigns negative 35 to a
int b = +66 // Assigns positive 66 to b (However to assign a positive number ‘+’ sign is not needed)
int c = -a; // Assigns negative of value in ‘a’ to c (35)
int d = -b; // Assigns negative of value in ‘b’ to d (-66)

Increment and Decrement Operators (++, --)

The increment (++) and decrement (--) operator is used to increase or decrease the value of a variable by 1. This operator can be used before or after a variable. If the unary increment (++) or unary decrement operator (--) is used before the variable they are known as “Prefix” increment or decrement operators and “Postfix” increment or decrement operators if they are used after the variable. Remember Postfix increment and decrement has higher precedence then prefix increment and decrement.
Illustration:
Let’s take some example to understand this concept more.
Example 1:

int a = 5;
int b = 10;
int c = a++ //statement 1
int d = ++b // statement 2

In statement 1 variable ‘c’ will have 5 and in statement 2 variable ‘d’ will have 11, because ‘=’ is having higher precedence than unary operator.  So, in statement 1 ‘a’ is assigned to ‘c’ first then value of ‘a’ is incremented. See the operation in the other way as it took place.
c = a; //First assignment occurred
a = a+1; // then value of ‘a’ is increased by 1
Whereas in statement 2 value of ‘b’ is incremented first than assigned to‘d’.
b = b+1; // First value of ‘b’ is increased by 1
d = b;   // then value of ‘b’ is assigned to d
So, after execution value of ‘a will be 6 and value of ‘b’ will be 11.

//Program to illustrate the concept of prefix / postfix increment or decrement
#include<iostream.h>
#include<conio.h>
int main()
{
int a,b,c,d;
clrscr();
a=5;
b=10;
c=a++;
d=++b;
cout<<"c = "<<c<<" a = "<<a<<"\n";
cout<<"d= "<<d<<" b = "<<b;
getch();
return 0;
}
Output:
[Run this program by your own and observe the output]

Thus “Prefix” increment/decrement means – increment / decrement first and then assignment(operation) and “Postfix” increment /decrement means – assignment (operation) first then increment / decrement.

Example 2:
Now let’s consider the following condition:
int a= 4;
int b= 5;
cout<<a++<<’\t’<<++a<<’\t\<<a++<<endl;
cout<<b--<<’\t’<<--b<<’\t’<<b--<<endl;

Output will be:
6          6          4
3          3          5
This is because, in a ‘cout’ cascading line, the operation occurs from the last part of the statement i.e.

Assignment Operator

An assignment operator assigns the value of the right-hand operand to the operand at the left side. Therefore, the left side operand must be a modifiable l-value. In C++ assignment operators can be categorized as simple and compound assignment operators.
A Simple-assignment operator assigns the value of right operand to the left operand. While assigning the value of the right operand is converted to the type of the assignment expression and replaces the value stored in the object designed by the left operand.
Example:
double D;
int X;
D = X;
Here the value of ‘X’ is converted to double type and assigned to ‘D’.

A Compound-assignment operator; combines the simple-assignment operator with the binary operator. Compound-assignment operator performs the operation specified by the additional binary operator first then assigns the result to the left operand. A list of compound-assignment operator is given below:

Operator         Example          Evaluation process
+=                    x += 1              x = x + 1
-=                    x -= 1               x = x - 1
*=                    x *= 1              x = x * 1
/=                     x /= 1               x = x / 1
%=                   x %= 1             x = x % 1

Multiple Assignments
In C++ if you need to assign same value to the multiple variables of same type (declared earlier) you can use the following syntax: var1 = var2 = var3 = value;  
Example: x = y = z = 5;

Sizeof Operator:

In C++ we have another operator which very much resembles like a library function call is sizeof. This is a unary operator. The size of has following formats:
sizeof data // format 1
sizeof (data type)
This operator produces a result that is the size, in bytes, of the data or data type specified. Most data types and variables require different storage on different computers. Therefore, sizeof operator was provided to enable the same program to be run on different kinds of computers.
Example:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
cout<<"\n Size of int = "<<sizeof(int)<<endl;
cout<<"\n Size of int = "<<sizeof(short)<<endl;
cout<<"\n Size of int = "<<sizeof(signed)<<endl;
cout<<"\n Size of unsigned int= "<<sizeof(unsigned int)<<endl;
cout<<"\n Size of unsigned int= "<<sizeof(unsigned)<<endl;
cout<<"\n Size of long int = "<<sizeof(long int)<<endl;
cout<<"\n Size of long int = "<<sizeof(long)<<endl;
cout<<"\n Size of unsigned long int = "<<sizeof(unsigned long int)<<endl;
cout<<"\n Size of char = "<<sizeof(char)<<endl;
cout<<"\n Size of unsigned char = "<<sizeof(unsigned char)<<endl;
cout<<"\n Size of float = "<<sizeof(float)<<endl;
cout<<"\n Size of long float = "<<sizeof(long float)<<endl;
cout<<"\n Size of double = "<<sizeof(double)<<endl;
cout<<"\n Size of long double = "<<sizeof(long double)<<endl;
getch();
}
Output:
[Run this program by your own and observe the output]

Ternary operator / Conditional Operator:

In C++ operator ? and : used together as a conditional operator. This is C++’s only ternary operator. So fas as we have seen an operator requires one or two operands to operate on but a ternary operator requires three operands. This conditional operator can be used to replace if-else logical statement. The syntax is –
conditional-expression ? expression1 : expression2
Illustration:
//program to illustrate the use of conditional operator
#include<iostream.h>
#include<conio.h>
int main(){
clrscr();
int a=4; int b=10;
cout<<a++<<'\t'<<++a<<'\t'<<a++<<endl;
cout<<b--<<'\t'<<--b<<'\t'<<b--<<endl;
(a>b)?cout<<"\n a = "<<a: cout<<"\nb = "<<b;
getch(); return 0; }

Output:

Order of Precedence and Associatively:

Under this topic we will see, how C++ computes formulae? Now we will find the answer to this question through an example:
Suppose it is said to solve this simple calculation: 3 + 5 * 2. Answer would be 13. Because we know at first we will do the multiplication and then the addition here. That is, the order in which the operators in an expression are evaluated is called precedence.
            Like us, C++ also performs multiplication, division and modulus first and then computes addition and subtraction. Operators – ‘*’, ‘/’, ‘%’ enjoys same level of priority then ‘-‘, ‘+’. If the operators of same priority appear in the same expression then the operator at the left most will be evaluated first.  This concept will be clearer from the following tables.
Table below showing – order of precedence for the primary operators
Order
Operators
=
Assignment
* / %
Arithmetic multiplication, division and modulus
- +
Arithmetic subtraction and addition
+=, -=, /=, %=
Arithmetic assignments
,
Comma separator
++, --
Increment / decrement operator
&&, ||, !
Logical operators
==, !=, >=, <=, >, <
Relational operators
sizeof()
Compile time operator
?:
Conditional or Ternary operator

Table below showing – execution associatively of the operators
Precedence of Operators
Associatively
! + - * sizeof ++ --
Right to left
* / %
Left to right
+ - (binary)
Left to right
< <= > >=
Left to right
== !=
Left to right
&&
Left to right
||
Left to right
?:
Right to left
= *= /= %= += -=
Right to left
,
Left to right

Using of Parenthesis:

As in the case of normal mathematical equations parenthesis holds top most priority. Means the operators within the parenthesis must be evaluated first before the rest of the operators in the same equation. This same rule also applies here for C++. Let’s see the following example to understand this more.
X = 5*4 / (2 + 6 * 2 / 3 + 4) + 3 * 2 / 2
Steps to solve the above equation would be as follows:
 
Example 2:
x = i * 3 / 4 + j / 4 + 8 – i + 5 / 8
Steps to evaluate the above equation would be:
Step1: x = (i* 3) / 4 + j / 4 + 8 – i + 5 / 8
Step2: x = ((i* 3) / 4) + j / 4 + 8 – i + 5 / 8
Step3: x = (( i* 3) / 4) + (j / 4) + 8 – i + 5 / 8
Step4: x = ((i* 3) / 4) + (j / 4) + 8 – i + (5 / 8)
Step5: x = (((i* 3) / 4) + (j / 4) )+ 8 – i + (5 / 8)
Step6: x = ((((i* 3) / 4) + (j / 4) )+ 8) – i + (5 / 8)
Step7: x = (((((i* 3) / 4) + (j / 4) )+ 8) – i )+ (5 / 8)
Now suppose i = 3 and j = 6
By substituting the values –
x = 9/4 + 6/4 + 8 – 3 + 0
x = 2 + 1 + 8 – 3 + 0
x = 8

Expression:

An expression is a combination of operators, constants and variables arranged as per rules of the language. It may also contain function calls which return values. An expression may consist of one or more operands and zero or more operators to produce a value. In C++ expression are of the following types:
  • constant expression
  • Integral expression
  • Float expressions
  • Pointer expressions
  • Relational expressions
  • Logical expressions
  • Bitwise expressions
An expression may also use combination of the above expressions. Such expression known as compound expressions.

Constant Expressions:

Constant expression consists of only constants values. Examples:
15
20+5/2.0
‘x’

Integral Expressions:

Integral Expressions are those produces integer results after implementing all the automatic and explicit type conversions. Examples:
M
M * N-5
M * ‘X’
5 + int (20.0)
Note** Here M and N are the integer values.

Float Expression:

Float expressions are those produces floating –point results.
X+ Y
5 + float(10)
10.75

Pointer Expression:

A pointer expression produces address value. Example.
int *ptr = &m;
Here address of variable m is assigned to the pointer variable ptr.

Relational Expression:

Relational Expression yields result of type true or false. Example:
X<=Y
A+B = = C+D
M + N > 100

Logical Expression:

Logical expression combines one or more relational expressions. Example:
(a > b) && (a > c)

Bitwise Expression:

C++ provides a list Bitwise operators. 
& (Bitwise and),  | (Bitwise or), ^ (xor), ~ (Bitwise not), << (Bitwise left shift), >> (Bitewise right shift)
Expression using one or more of these operators is known as Bitwise operator.
Example: n << p, a^b, ~a

1 comment: