Increment and SasdDecrement Operator in CFSDF
Increment and SasdDecrement Operator in CFSDF
Increment operators are used to increase the value of the variable by one and decrement operators
Both increment and decrement operator are used on single operand or variable, so it is called as
unary operator. Unary operators are having higher priority than the other operators it means unary
Syntax
++ // increment operator
-- // decrement operator
Note: Increment and decrement operators are can not apply on constant.
Example
pre-increment
post-increment
In pre-increment first increment the value of variable and then used inside the expression (initialize
Syntax
++ variable;
void main()
{
int x,i;
i=10;
x=++i;
cout<<"x: "<<x;
cout<<"i: "<<i;
getch();
}
Output
x: 11
i: 11
In above program first increase the value of i and then used value of i into expression.
In post-increment first value of variable is use in the expression (initialize into another variable) and
Syntax
variable ++;
Example post-increment
#include<iostream.h>
#include<conio.h>
void main()
{
int x,i;
i=10;
x=i++;
cout<<"x: "<<x;
cout<<"i: "<<i;
getch();
}
Output
x: 10
i: 11
In above program first used the value of i into expression then increase value of i by 1.
pre-decrement
post-decrement
In pre-decrement first decrement the value of variable and then used inside the expression
Syntax
-- variable;
Example pre-decrement
#include<iostream.h>
#include<conio.h>
void main()
{
int x,i;
i=10;
x=--i;
cout<<"x: "<<x;
cout<<"i: "<<i;
getch();
}
Output
x: 9
i: 9
In above program first decrease the value of i and then value of i used in expression.
In Post-decrement first value of variable is use in the expression (initialize into another variable)
Syntax
variable --;
Example post-decrement
#include<iostream.h>
#include<conio.h>
void main()
{
int x,i;
i=10;
x=i--;
cout<<"x: "<<x;
cout<<"i: "<<i;
getch();
}
Output
x: 10
i: 9
In above program first used the value of x in expression then decrease value of i by 1.
Example
#include<iostream.h>
#include<conio.h>
void main()
{
int x,a,b,c;
a = 2;
b = 4;
c = 5;
x = a-- + b++ - ++c;
cout<<"x: "<<x;
getch();
}
Output
x: 0
4.10 Increment and Decrement Operators
In addition to the arithmetic assignment operators, C++ also provides two unary operators for adding 1 to or
subtracting 1 from the value of a numeric variable. These are the unary increment operator, ++, and the
unary decrement operator, --, which are summarized in Fig. 4.16. A program can increment by 1 the value of
a variable called c using the increment operator, ++, rather than the expression c=c+1 or c+=1. An increment
or decrement operator that is prefixed to (placed before) a variable is referred to as the prefix
increment or prefix decrement operator, respectively. An increment or decrement operator that is postfixed
to (placed after) a variable is referred to as the postfix increment or postfix decrement operator,
respectively.
Fig. 4.16 Increment and decrement operators.
Using the prefix increment (or decrement) operator to add (or subtract) 1 from a variable is known
as preincrementing (or predecrementing) the variable. Preincrementing (or predecrementing) causes the
variable to be incremented (decremented) by 1, then the new value of the variable is used in the expression in
which it appears. Using the postfix increment (or decrement) operator to add (or subtract) 1 from a variable is
known as postincrementing (or postdecrementing) the variable. Postincrementing (or postdecrementing)
causes the current value of the variable to be used in the expression in which it appears, then the variable's
value is incremented (decremented) by 1.
Figure 4.17 demonstrates the difference between the prefix increment and postfix increment versions of
the ++ increment operator. The decrement operator (--) works similarly. Note that this example does not
contain a class, but just a source code file with function main performing all the application's work. In this
chapter and in Chapter 3, you have seen examples consisting of one class (including the header and source
code files for this class), as well as another source code file testing the class. This source code file contained
function main, which created an object of the class and called its member functions. In this example, we
simply want to show the mechanics of the ++ operator, so we use only one source code file with
function main. Occasionally, when it does not make sense to try to create a reusable class to demonstrate a
simple concept, we'll use a mechanical example contained entirely within the main function of a single source
code file.
Fig. 4.17 Preincrementing and postincrementing.
1 // Fig. 4.17: fig04_17.cpp
2 // Preincrementing and postincrementing.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 int main()
8 {
9 int c;
10
11 // demonstrate postincrement
12 c = 5; // assign 5 to c
13 cout << c << endl; // print 5
14 cout << c++ << endl; // print 5 then postincrement
15 cout << c << endl; // print 6
16
17 cout << endl; // skip a line
18
19 // demonstrate preincrement
20 c = 5; // assign 5 to c
21 cout << c << endl; // print 5
22 cout << ++c << endl; // preincrement then print 6
23 cout << c << endl; // print 6
24 return 0; // indicate successful termination
25 } // end main
5
5
6
5
6
6
A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times.
Syntax
The syntax of a for loop in C++ is −
for ( init; condition; increment ) {
statement(s);
}
Here is the flow of control in a for loop −
The init step is executed first, and only once. This step allows you to declare and initialize
any loop control variables. You are not required to put a statement here, as long as a
semicolon appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the
body of the loop does not execute and flow of control jumps to the next statement just after
the for loop.
After the body of the for loop executes, the flow of control jumps back up to
the increment statement. This statement can be left blank, as long as a semicolon appears
after the condition.
The condition is now evaluated again. If it is true, the loop executes and the process repeats
itself (body of loop, then increment step, and then again condition). After the condition
becomes false, the for loop terminates.
Flow Diagram
Example
Live Demo
#include <iostream>
using namespace std;
int main () {
// for loop execution
for( int a = 10; a < 20; a = a + 1 ) {
cout << "value of a: " << a << endl;
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
C++ Loops
Loops can execute a block of code as long as a specified condition is reached.
Loops are handy because they save time, reduce errors, and they make code
more readable.
Syntax
while (condition) {
// code block to be executed
}
In the example below, the code in the loop will run, over and over again, as
long as a variable (i) is less than 5:
Example
int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}
While Loop example in C++
#include <iostream>
using namespace std;
int main(){
int i=1;
/* The loop would continue to print
* the value of i until the given condition
* i<=6 returns false.
*/
while(i<=6){
cout<<"Value of variable i is: "<<i<<endl; i++;
}
}
Output:
#include <iostream>
using namespace std;
int main(){
int i=1; while(i<=6) {
cout<<"Value of variable i is: "<<i<<endl; i--;
}
}
21
87
15
99
-12
How while loop works?
The while loop evaluates the test expression.
If the test expression is true, codes inside the body of while loop is evaluated.
Then, the test expression is evaluated again. This process goes on until the test
expression is false.
When the test expression is false, while loop is terminated.
Then, the while loop starts executing the code. Here's how while loop works:
do {
// codes;
}
while (testExpression);
Output
Enter a number: 2
Enter a number: 3
Enter a number: 4
Enter a number: -4
Enter a number: 2
Enter a number: 4.4
Enter a number: 2
Enter a number: 0
The compound assignment operators are specified in the form e1 op= e2, where e1 is a
modifiable l-value not of const type and e2 is one of the following:
1. An arithmetic type
2. A pointer, if op is + or –
Multiply the value of the first operand by the value of the second operand; store the result
*=
in the object specified by the first operand.
Divide the value of the first operand by the value of the second operand; store the result
/=
in the object specified by the first operand.
Take modulus of the first operand specified by the value of the second operand; store the
%=
result in the object specified by the first operand.
Add the value of the second operand to the value of the first operand; store the result in
+=
the object specified by the first operand.
Subtract the value of the second operand from the value of the first operand; store the
–=
result in the object specified by the first operand.
Shift the value of the first operand left the number of bits specified by the value of the
<<=
second operand; store the result in the object specified by the first operand.
Shift the value of the first operand right the number of bits specified by the value of the
>>=
second operand; store the result in the object specified by the first operand.
Obtain the bitwise AND of the first and second operands; store the result in the object
&=
specified by the first operand.
Obtain the bitwise exclusive OR of the first and second operands; store the result in the
^=
object specified by the first operand.
Obtain the bitwise inclusive OR of the first and second operands; store the result in the
|=
object specified by the first operand.
a += b;
cout << a << endl;
a -= b;
cout << a << endl;
a *= b;
cout << a << endl;
a /= b;
cout << a << endl;
return 0;
}
This will give the output:
5
3
6
3
Note that Compound assignment to an enumerated type generates an error message. If
the left operand is of a pointer type, the right operand must be of a pointer type or it must
be a constant expression that evaluates to 0. If the left operand is of an integral type, the
right operand must not be of a pointer type.
Operators
Once introduced to variables and constants, we can begin to operate with them by using operators.
What follows is a complete list of operators. At this point, it is likely not necessary to know all of them,
but they are all listed here to also serve as reference.
x = 5;
This statement assigns the integer value 5 to the variable x. The assignment operation always takes
place from right to left, and never the other way around:
x = y;
This statement assigns to variable x the value contained in variable y. The value of x at the moment this
statement is executed is lost and replaced by the value of y.
Consider also that we are only assigning the value of y to x at the moment of the assignment operation.
Therefore, if y changes at a later moment, it will not affect the new value taken by x.
For example, let's have a look at the following code - I have included the evolution of the content stored
in the variables as comments:
Assignment operations are expressions that can be evaluated. That means that the assignment itself has
a value, and -for fundamental types- this value is the one assigned in the operation. For example:
y = 2 + (x = 5);
In this expression, y is assigned the result of adding 2 and the value of another assignment expression
(which has itself a value of 5). It is roughly equivalent to:
1 x = 5;
2 y = 2 + x;
x = y = z = 5;
Arithmetic operators ( +, -, *, /, % )
The five arithmetical operations supported by C++ are:
operator description
+ addition
- subtraction
* multiplication
/ division
% modulo
Operations of addition, subtraction, multiplication and division correspond literally to their respective
mathematical operators. The last one, modulo operator, represented by a percentage sign (%), gives the
remainder of a division of two values. For example:
x = 11 % 3;
results in variable x containing the value 2, since dividing 11 by 3 results in 3, with a remainder of 2.
Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)
Compound assignment operators modify the current value of a variable by performing an operation on
it. They are equivalent to assigning the result of an operation to the first operand:
y += x; y = y + x;
x -= 5; x = x - 5;
x /= y; x = x / y;
and the same for all other compound assignment operators. For example:
are all equivalent in its functionality; the three of them increase by one the value of x.
In the early C compilers, the three previous expressions may have produced different executable code
depending on which one was used. Nowadays, this type of code optimization is generally performed
automatically by the compiler, thus the three expressions should produce exactly the same executable
code.
A peculiarity of this operator is that it can be used both as a prefix and as a suffix. That means that it can
be written either before the variable name (++x) or after it (x++). Although in simple expressions
like x++ or ++x, both have exactly the same meaning; in other expressions in which the result of the
increment or decrement operation is evaluated, they may have an important difference in their
meaning: In the case that the increase operator is used as a prefix (++x) of the value, the expression
evaluates to the final value of x, once it is already increased. On the other hand, in case that it is used as
a suffix (x++), the value is also increased, but the expression evaluates to the value that x had before
being increased. Notice the difference:
Example 1 Example 2
x = 3; x = 3;
y = ++x; y = x++;
// x contains 4, y contains 4 // x contains 4, y contains 3
In Example 1, the value assigned to y is the value of x after being increased. While in Example 2, it is the
value x had before being increased.
Relational and comparison operators ( ==, !=, >, <, >=, <= )
Two expressions can be compared using relational and equality operators. For example, to know if two
values are equal or if one is greater than the other.
The result of such an operation is either true or false (i.e., a Boolean value).
operator description
== Equal to
!= Not equal to
< Less than
1 (7 == 5) // evaluates to false
2 (5 > 4) // evaluates to true
3 (3 != 2) // evaluates to true
4 (6 >= 6) // evaluates to true
5 (5 < 5) // evaluates to false
Of course, it's not just numeric constants that can be compared, but just any value, including, of course,
variables. Suppose that a=2, b=3 and c=6, then:
Be careful! The assignment operator (operator =, with one equal sign) is not the same as the equality
comparison operator (operator ==, with two equal signs); the first one (=) assigns the value on the right-
hand to the variable on its left, while the other (==) compares whether the values on both sides of the
operator are equal. Therefore, in the last expression ((b=2) == a), we first assigned the
value 2 to b and then we compared it to a (that also stores the value 2), yielding true.
The logical operators && and || are used when evaluating two expressions to obtain a single relational
result. The operator && corresponds to the Boolean logical operation AND, which yields true if both its
operands are true, and false otherwise. The following panel shows the result of
operator && evaluating the expression a&&b:
The operator || corresponds to the Boolean logical operation OR, which yields true if either of its
operands is true, thus being false only when both operands are false. Here are the possible results
of a||b:
|| OPERATOR (or)
a b a || b
For example:
When using the logical operators, C++ only evaluates what is necessary from left to right to come up
with the combined relational result, ignoring the rest. Therefore, in the last example ((5==5)||(3>6)),
C++ evaluates first whether 5==5 is true, and if so, it never checks whether 3>6 is true or not. This is
known as short-circuit evaluation, and works like this for these operators:
operator short-circuit
if the left-hand side expression is false, the combined result is false (the right-hand side
&&
expression is never evaluated).
if the left-hand side expression is true, the combined result is true (the right-hand side
||
expression is never evaluated).
This is mostly important when the right-hand expression has side effects, such as altering values:
Here, the combined conditional expression would increase i by one, but only if the condition on the left
of && is true, because otherwise, the condition on the right-hand side (++i<n) is never evaluated.
If condition is true, the entire expression evaluates to result1, and otherwise to result2.
For example:
In this example, a was 2, and b was 7, so the expression being evaluated (a>b) was not true, thus the
first value specified after the question mark was discarded in favor of the second value (the one after
the colon) which was b (with a value of 7).
Comma operator ( , )
The comma operator (,) is used to separate two or more expressions that are included where only one
expression is expected. When the set of expressions has to be evaluated for a value, only the right-most
expression is considered.
a = (b=3, b+2);
would first assign the value 3 to b, and then assign b+2 to variable a. So, at the end, variable a would
contain the value 5 while variable b would contain value 3.
| OR Bitwise inclusive OR
1 int i;
2 float f = 3.14;
3 i = (int) f;
The previous code converts the floating-point number 3.14 to an integer value (3); the remainder is
lost. Here, the typecasting operator was (int). Another way to do the same thing in C++ is to use the
functional notation preceding the expression to be converted by the type and enclosing the expression
between parentheses:
i = int (f);
sizeof
This operator accepts one parameter, which can be either a type or a variable, and returns the size in
bytes of that type or object:
x = sizeof (char);
Here, x is assigned the value 1, because char is a type with a size of one byte.
The value returned by sizeof is a compile-time constant, so it is always determined before program
execution.
Other operators
Later in these tutorials, we will see a few more operators, like the ones referring to pointers or the
specifics for object-oriented programming.
Precedence of operators
A single expression may have multiple operators. For example:
x = 5 + 7 % 2;
In C++, the above expression always assigns 6 to variable x, because the % operator has a higher
precedence than the + operator, and is always evaluated before. Parts of the expressions can be
enclosed in parenthesis to override this precedence order, or to make explicitly clear the intended
effect. Notice the difference:
From greatest to smallest priority, C++ operators are evaluated in the following order:
Left-to-
1 Scope :: scope qualifier
right
() functional forms
Left-to-
2 Postfix (unary)
[] right
subscript
+ - unary prefix
Right-to-
3 Prefix (unary) & * reference / dereference
left
new delete allocation / deallocation
Left-to-
4 Pointer-to-member .* ->* access pointer
right
Left-to-
5 Arithmetic: scaling * / % multiply, divide, modulo
right
Left-to-
6 Arithmetic: addition + - addition, subtraction
right
Left-to-
7 Bitwise shift << >> shift left, shift right
right
Left-to-
8 Relational < > <= >= comparison operators
right
Left-to-
9 Equality == != equality / inequality
right
Left-to-
10 And & bitwise AND
right
Left-to-
11 Exclusive or ^ bitwise XOR
right
Left-to-
12 Inclusive or | bitwise OR
right
Left-to-
13 Conjunction && logical AND
right
Left-to-
14 Disjunction || logical OR
right
= *= /= %= += -
= assignment / compound
Assignment-level >>= <<= &= ^= assignment Right-to-
15
expressions |= left
?: conditional operator
Left-to-
16 Sequencing , comma separator
right
When an expression has two operators with the same precedence level, grouping determines which one
is evaluated first: either left-to-right or right-to-left.
Enclosing all sub-statements in parentheses (even those unnecessary because of their precedence)
improves code readability.
C++ Compound Assignment Operators
In this article, we are going to discuss another operator provided by C++, known as compound
assignment operator. There are four compound assignment operators in C++ such as -
+=
-=
*=
/=
+= operator
o Statement i+=2 is equal to i=i+2, hence 2 will be added to the value of i, which gives us 4.
o Finally, the result of addition, 4 is assigned back to i, updating its original value from 2 to 4.
int i=2;
i+=2*2; //equals to, i = i+(2*2);
In all the compound assignment operators, the expression on the right side of = is always calculated
first and then the compound assignment operator will start its functioning. Hence in the last code,
statement i+=2*2; is equal to i=i+(2*2), which results in i=i+4, and finally it returns 6 to i.
Example with += operator
#include<iostream
int main()
{
char c='a';
cout<< "Original char : " << c << "\n";
c+=10; // c = c+10;
cout<< "char after +=10 operation : "<< c << "\n";
short s=10;
cout<< "Original short : " << s << "\n";
s+=5*10; // s = s+(5*10);
cout<< "short after +=5*10 operation : " << s <<"\n";
int i=10;
cout<< "Original int : " << i << "\n";
i+=10; // i = i+10;
cout<< "int after +=10 operation : "<< i <<"\n";
float f=10.5f;
cout<<"Original float : "<< f << "\n";
f+=20; // f = f+20;
cout<< "float after +=20 operation : "<< f << "\n";
double d=22.5;
cout<< "Original double : " << d << "\n";
d+=30; // d = d+30;
cout<< "double after +=30 operation : " << d;
return 0;
}
Output is
Original char : a
char after +=10 operation : k
Original short : 10
short after +=5*10 operation : 60
Original int : 10
int after +=10 operation : 20
Original float : 10.5
float after +=20 operation : 30.5
Original double : 22.5
double after +=30 operation : 52.5
-= operator
int i=2;
i-=2;
o Statement i-=2 is equal to i=i-2, hence 2 will be subtracted from the value of i, which gives us 0.
o Finally, the result of subtraction i.e. 0 is assigned back to i, updating its value to 0.
#include
short s=10;
cout<< "Original short : "<< s << "\n";
s-=5*10; // s = s-(5*10);
cout<< "short after -=5*10 operation : "<< s << "\n";
int i=10;
cout<< "Original int : " << i << "\n";
i-=10; // i = i-10;
cout<< "int after -=10 operation : " << i << "\n";
float f=10.5f;
cout<< "Original float : " << f << "\n";
f-=20; // f = f-20;
cout<< "float after -=20 operation : " << f << "\n";
double d=22.5;
cout<< "Original double : " << d << "\n";
d-=30*2; // d = d-(30*2);
cout<< "double after -=30*2 operation : " << d;
return 0;
}
Output is
Original char : k
char after -=10 operation : a
Original short : 10
short after -=5*10 operation : -40
Original int : 10
int after -=10 operation : 0
Original float : 10.5
float after -=20 operation : -9.5
Original double : 22.5
double after -=30*2 operation : -37.5
Advertisement
*= operator
o Statement i*=2 is equal to i=i*2, hence 2 will be multiplied with the value of i, which gives us 4.
o Finally, the result of multiplication, 4 is assigned back to i, updating its value to 4.
#include<iostream>
int main()
{
char c='a';
cout<<"Original char : " <<c <<"\n";
c*=1; // c = c*1;
cout<<"char after *=1 operation : " <<c <<"\n";
short s=10;
cout<<"Original short : "<<s <<"\n";
s*=5+10; // s = s*(5+10);
cout<<"short after *=5+10 operation : " <<s <<"\n";
int i=10;
cout<<"Original int : "<<i <<"\n";
i*=10; // i = i+10;
cout<<"int after *=10 operation : "<<i <<"\n";
long l=100000;
cout <<"Original int : " <<l <<"\n";
l*=1000; // l = l*1000;
cout<<"long after *=1000 operation : " <<l <<"\n";
float f=10.5f;
cout<<"Original float : " <<f <<"\n";
f*=20; // f = f*20;
cout<<"float after *=20 operation : " <<f <<"\n";
double d=22.5;
cout<<"Original double : "<<d <<"\n";
d*=30; // d = d*30;
cout<<"double after *=30 operation : " <<d;
return 0;
}
Output -
Original char : a
char after *=1 operation : a
Original short : 10
short after *=5+10 operation : 150
Original int : 10
int after *=10 operation : 100
Original int : 100000
long after *=1000 operation : 100000000
Original float : 10.5
float after *=20 operation : 210
Original double : 22.5
double after *=30 operation : 675
/= operator
o Statement i/=2 is equal to i=i/2, hence 4 will be divided by the value of i, which gives us 2.
o Finally, the result of division i.e. 2 is assigned back to i, updating its value from 4 to 2.
#include<iostream*gt;
int main()
{
char c='j';
cout<< "Original char : " << c << "\n";
c/=1; // c = c/1;
cout<< "char after /=1 operation : "<< c << "\n";
short s=10;
cout<< "Original short : "<< s << "\n";
s/=5-2; // s = s/(5-2);
cout<< "short after /=5-2 operation : " << s << "\n";
int i=10;
cout<< "Original int : " << i << "\n";
i/=10; // i = i/10;
cout<< "int after /=10 operation : " << i << "\n";
long l=999;
cout<< "Original int : " << l << "\n";
l/=2; // l = l/2;
cout<< "long after /=2 operation : " << l << "\n";
float f=80.5f;
cout<< "Original float : " << f << "\n";
f/=20; // f = f/20;
cout<< "float after /=20 operation : " << f << "\n";
double d=44.5;
cout<< "Original double : " << d <<"\n";
d/=22; // d = d/22;
cout<< "double after /=30 operation : " << d;
return 0;
}
Output-
Original char : j
char after /=1 operation : j
Original short : 10
short after /=5-2 operation : 3
Original int : 10
int after /=10 operation : 1
Original int : 999
long after /=2 operation : 499
Original float : 80.5
float after /=20 operation : 4.025
Original double : 44.5
double after /=30 operation : 2.02273