Operator precedence, Control Structures.
Introduction to Operator Precedence in C++
The operator precedence determines which operator is to be first evaluated and which next in expression when one or more operators present in an expression. the other term which is related to expression is operator associativity. Operator associativity which determines the direction of operator evaluation of the same operator precedence, associativity can be left to right or right to left.
Lets take an example: x = 10 + 22 / 2.
In the above example, the result is 21, not 16 because the ‘/’ operator has higher precedence than the ‘+’ operator.
Lets take an example: x = 10 -20+ 22 / 2.
In the above example, the result is 1, not 19 because the same as above ‘/’ operator has higher precedence than the ‘+’ operator and ‘+’ and ‘-‘ operator is of the same precedence and their associativity is left to right so the expression evaluates as –
- x = 10 – 20+ 22 / 2
- x=10 – 20+11
- x=-10+11
- x=1
So, Operators Precedence and operator Associativity are two characteristics of operators that specify the order of evaluation in an expression.
Top 15 Operator Precedence in C++
Next, we see the operator precedence and associativity in C++ in the below table where the highest operators are at the top and lowest precedence operator at the bottom:
Category |
Operator |
Associativity |
Postfix | ‘()’,‘[]’, ‘.’, ‘->’,‘++’,‘- -‘ | L -> R |
Unary | ‘-‘, ‘+’,‘~’, ‘!’,‘–‘, ‘++’,‘&’, ‘*’, ‘(type)’, ‘sizeof’ | R -> L |
Multiplicative | ‘/’, ‘*’, ‘ %’ | L -> R |
Additive | ‘-‘, ‘+’ | R -> L |
Shift | ‘>>’, ‘<<’ | L -> R |
Relational | ‘>’, ‘>=’, ‘<’,‘<=’ | L -> R |
Equality | ‘!=’, ‘==’ | R -> L |
Bitwise AND | ‘&’ | L -> R |
Bitwise XOR | ‘^’ | L -> R |
Bitwise OR | ‘|’ | R -> L |
Logical AND | ‘&&’ | L -> R |
Logical OR | ‘||’ | L -> R |
Conditional | ‘?:’ | R -> L |
Assignment | ‘=’,‘+=’,‘-=’,‘*=’,‘/=’, ‘%=’, ‘>>=’, ‘<<=’, ‘&=’,‘^=’, ‘|=’ | R -> L |
Comma | , | L -> R |
Example to Implement Operator Precedence in C++
Below are mentioned the examples:
Example #1
Code:
#include <iostream>
using namespace std;
int main()
{
// declare variables
int a = 10, b=22, c=2, x;
// expression
x= a + b / c;
// display result
cout<<"The result of the expression is = "<<x;
return 0;
}
Output:
Explanation: As in the code, the expression is evaluated and output is 21, not 16 because the ‘/’ operator is first performed and then ‘+’ operator performed, so expression is solved as x = a + ( b / c ).
Example #2
Next, we rewrite the above c++ code to understand the operator precedence overload with the following example:
Code:
#include<iostream>
using namespace std;
int main()
{
// declare variables
int a = 10, b=22, c=2, x;
// expression
x = ( a + b ) / c;
// display result
cout<<"The result of the expression is = "<<x;
return 0;
}
Output:
Explanation: As in the code, the expression is evaluated and output is 16, not 16 because the ‘( )’ is first performed ( as subexpression) which is having ‘+’ operator so it is performed’ and then ‘/’ operator is performed.so an expression is solve as x = ( a + b ) / c.
Example #3
Next, we write the c++ code for operator associativity with the following example:
Code:
#include <iostream>
using namespace std;
int main()
{
// declare variables
int a = 10, b=22, c=2, x;
// expression
x = a == b != c;
// display result
cout<<"The result of the first expression is = "<< x <<endl;
x = a == ( b != c );
cout<<"The result of the second expression is = "<<x <<endl;
return 0;
}
Output:
Explanation: As in the above code the first expression operators == and != have the same precedence and the associativity is left to right so first == and then != operator performed. And in the second expression first != and then == operator performed. So first expression is solve as:
- x = a == b != c
- x = 10 == 22 != 2
- x=0 != 2
- x=1
- and second expression is solve as –
- x = a == (b != c)
- x = 10 == (22 != 2)
- x=10 == 1
- x=0
Example #4
Next we write the c++ code for operator associativity with the following example:
Code:
#include <iostream>
using namespace std;
int main()
{
// declare variables
int a = 10, b=22, c=2, x;
// expression
x = a > b > c;
// display result
cout<<"The result of the first expression is = "<< x <<endl;
x = a < b < c;
cout<<"The result of the second expression is = "<<x <<endl;
return 0;
}
Output:
Explanation: As in the above code, the first expression contains>operator whose associativity is left to right. Therefore the expression becomes ((a > b) > c), which becomes (0 > 2), so output is 0. And the second expression contains>operator whose associativity is left to right. Therefore the expression becomes ((a< b) < c), which becomes (1 < 2), so output is 1.
Conclusion
Operator precedence is the main characteristic of operators, which determines which operator is to be first evaluated and next in expression when one or more operators present in an expression and the associativity of the operator determine the direction of operator evaluation of the same operator precedence in an expression.
Control Statements, Looping and Iteration
- Conditional structure: if and else
- For Loop
- While Loop
- Do While
- Goto, Break and Continue
- Switch Statement and Break
Conditional structure: if and else
- The if statement executes based test expression inside the braces.
- If statement expression is to true, If body statements are executed and Else body statements are skipped.
- If statement expression is to false If body statements are skipped and Else body statements are executed.
- Simply, Block will execute based on If the condition is true or not.
- IF conditional statement is a feature of this programming language which performs different computations or actions depending on whether a programmer-specified boolean condition evaluates to true or false. Apart from the case of branch prediction, this is always achieved by selectively altering the control flow based on some condition.
if and else Syntax
if (expression) // Body will execute if expression is true or non-zero
{
//If Body statements
}else
{
//Else Body statements
}
if and else Syntax Example
for example, In c
if (i == 3) {
doSomething();
}
else {
doSomethingElse();
}
Syntax Explanation
Consider above example syntax,if (i == 3)
- which means the variable i contains a number that is equal to 3, the statements following the doSomething() block will be executed.
- Otherwise variable contains a number that is not equal to 3, else block doSomethingElse() will be executed.
Example Program For If..else
/* Example Program For If..else In C++ Programming Language */
// Header Files
#include<iostream>
#include<conio.h>
using namespace std;
//Main Function
int main()
{
// Variable Declaration
int a;
//Get Input Value
cout<<"Enter the Number :";
cin>>a;
//If Condition Check
if(a > 10)
{
// Block For Condition Success
cout<<a <<" Is Greater than 10";
}
else
{
// Block For Condition Fail
cout<<a<<" Is Less than/Equal to 10";
}
// Wait For Output Screen
getch();
//Main Function return Statement
return 0;
}
Sample Output:
Enter the Number :8
8 Is Less than/Equal to 10
Enter the Number :10
10 Is Less than/Equal to 10
Looping and Iteration
This chapter will look at C's mechanisms for controlling looping and iteration. Even though some of these mechanisms may look familiar and indeed will operate in a standard fashion most of the time.
The for statement
The C++ for statement has the following form:
Syntax:
for (expression1;Condition;expression2)
statement;
for (expression1;Condition;expression2) {
block of statements
}
expression1 initialises; expression2 is the terminate test; expression3 is the modifier (which may be more than just simple increment);
NOTE: C/C++ basically treats for statements as while type loops
For loop example program:
/* Example Program For for Loop In C++ Programming Language */
// Header Files
#include<iostream>
#include<conio.h>
using namespace std;
//Main Function
int main()
{
// Variable Declaration
int x=3;
//for loop
for (x=3;x>0;x--)
{
cout<<"x="<<x<<endl;
}
// Wait For Output Screen
getch();
//Main Function return Statement
return 0;
}
Output:
x=3
x=2
x=1
The while statement
The while statement is similar to those used in other languages although more can be done with the expression statement -- a standard feature of C.
The while has the form:
Syntax:
while (expression)
statement;
while (expression)
block of statements
}
While statement example program
/* Example Program For while Loop In C++ Programming Language */
// Header Files
#include<iostream>
#include<conio.h>
using namespace std;
//Main Function
int main()
{
// Variable Declaration
int x=3;
//while loop
while (x>0)
{
cout<<"x="<<x<<endl;
x--;
}
// Wait For Output Screen
getch();
//Main Function return Statement
return 0;
}
Output:
x=3
x=2
x=1
The do-while statement
Syntax:
C's do-while statement has the form:
do {
statement;
}while (expression);
It is similar to PASCAL's repeat ... until except do while expression is true.
do while Loop example:
/* Example Program For Do While Loop In C++ Programming Language */
// Header Files
#include<iostream>
#include<conio.h>
using namespace std;
//Main Function
int main()
{
// Variable Declaration
int x=3;
//do while loop
do {
cout<<"x="<<x<<endl;
x--;
}while (x>0);
// Wait For Output Screen
getch();
//Main Function return Statement
return 0;
}
outputs:
x=3
x=2
x=1
NOTE: The postfix x- operator which uses the current value of x while printing and then decrements x.
C/C++ provides two commands to control how we loop: break and continue
break -- exit form loop or switch.
continue -- skip 1 iteration of loop.
Consider the following example where we read in integer values and process them according to the following conditions. If the value we have read is negative, we wish to print an error message and abandon the loop. If the value read is great than 100, we wish to ignore it and continue to the next value in the data. If the value is zero, we wish to terminate the loop.
Switch Case Statement
In C/C++ programming language, the switch statement is a type of selection mechanism used to allow block code among many alternatives.Simply, It changes the control flow of program execution via multiple blocks.
Switch Statement Rules
- A switch works with the char and int data types.
- It also works with enum types
- Switch expression/variable datatype and case datatype are should be matched.
- A switch block has many numbers of case statements, Each case ends with a colon.
- Each case ends with a break statement. Else all case blocks will execute until a break statement is reached.
- The switch exists When a break statement is reached,
- A switch block has only one number of default case statements, It should end of the switch.
- The default case block executed when none of the cases is true.
- No break is needed in the default case.
Switch Statement Usage
- We can use switch statements alternative for an if..else ladder.
- The switch statement is often faster than nested if...else Ladder.
- Switch statement syntax is well structured and easy to understand.
Switch Statement Syntax:
switch ( <expression> or <variable> ) {
case value1:
//Block 1 Code Here
break;
case value2:
//Block 1 Code Here
break;
...
default:
Code to execute for not match case
break;
}
Example Program For Switch
/* Example Program For Switch Case In C++ Programming Language */
// Header Files
#include<iostream>
#include<conio.h>
using namespace std;
//Main Function
int main() {
// Variable Declaration
char ch;
//Get Input Value
cout << "Enter the Vowel (In Capital Letter):";
cin>>ch;
//Switch Case Check
switch (ch) {
case 'A': cout << "Your Character Is A\n";
break;
case 'E': cout << "Your Character Is E\n";
break;
case 'I': cout << "Your Character Is I\n";
break;
case 'O': cout << "Your Character Is O\n";
break;
case 'U': cout << "Your Character Is U\n";
break;
default: cout << "Your Character is Not Vowel.Otherwise Not a Capital Letter\n";
break;
}
// Wait For Output Screen
getch();
//Main Function return Statement
return 0;
}
Sample Output:
Enter the Vowel (In Capital Letter):A
Your Character Is A
Enter the Vowel (In Capital Letter):O
Your Character Is O
Enter the Vowel (In Capital Letter):h
Your Character is Not Vowel.Or Not a Capital Letter
![]()
The goto statement
goto allows making an absolute jump to another point in the program. You should use this feature with caution since its execution causes an unconditional jump ignoring any type of nesting limitations.
The destination point is identified by a label, which is then used as an argument for the goto statement. A label is made of a valid identifier followed by a colon (:).
Generally speaking, this instruction has no concrete use in structured or object oriented programming aside from those that low-level programming fans may find for it. For example, here is our countdown loop using goto:
// goto loop example
/* Example Program For goto In C++ Programming Language */
// Header Files
#include<iostream>
#include<conio.h>
using namespace std;
//Main Function
int main() {
// Variable Declaration
int num = 10;
//goto statement declaration
loop:
cout << num << ", ";
num--;
//goto usage
if (num > 0) goto loop;
cout << "FIRE!\n";
// Wait For Output Screen
getch();
//Main Function return Statement
return 0;
}
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!