Decrement operator
The decrement operator(--) is a unary operator which decreases the value of operand by one(1). It is used to abbreviate the assigning of variable's decreased value (by 1) to the same variable i.e. a-- means a=a-1.
Unary operators are those operators which perform an operation upon one operand to produce a new value.
The decrement operator can be utilized in two different ways, depending on whether the operator is written before or after the operand.
Pre-decrement operator
If the decrement operator precedes the operand, then it is called the pre-decrement operator(E.g. --a). The value of operand will be decremented before its value is utilized in the expression.
Example:
y= --a; means a=a-1; and y=a; will be executed serially.
First, the value of a will be decremented, then it will be assigned to y.
Post-decrement operator
If the decrement operator follows the operand, then it is called the post-decrement operator(E.g. a--). The value of operand will be decremented after its value is utilized in the expression.
Example:
y=a--; means y=a; and a=a-1; will be executed serially.
First, the value of a will be assigned to y, then it will be decremented.
Write a program in C++ to give an idea about the pre-decrement and post-decrement operator.
In this program, we perform different operations using pre-decrement and post-decrement operator. We will input a number from the user and the altered values due to pre-decrement and post-decrement operator will be printed.Program
1 #include<iostream.h>
2 #include<conio.h>
3 void main()
4 {
5 int a,y;
6 clrscr();
7 cout<<"Enter a value in a= ";
8 cin>>a;
9 cout<<endl<<"a= "<<a<<endl;
10 y=a--;
11 cout<<"y= a--= "<<y<<endl;
12 cout<<"a= "<<a<<endl;
13 y=--a;
14 cout<<"y= --a= "<<y<<endl;
15 cout<<"a= "<<a<<endl;
16 cout<<"a--= "<<a--<<endl;
17 cout<<"--a= "<<--a<<endl;
18 a--;
19 cout<<"a--"<<endl<<"a= "<<a<<endl;
20 getch();
21 }
Output
USE OF DECREMENT OPERATOR IN C++ |
Explanation
In this program, the user enters 5 as the input number(i.e. a=5). The remaining part of the program will be executed as follows:Line number Action Output
9 Value of a(i.e. 5) is printed. 5
10 y=a-- i.e. y=5 and a=5-1=4
11 Value of y(i.e. 5) is printed. 5
12 Value of a(i.e. 4) is printed. 4
13 y= --a i.e. a=4-1=3 and y=3
14 Value of y(i.e. 3) is printed. 3
15 Value of a(i.e. 3) is printed. 3
16 Value of a-- is printed i.e. the value
of a(i.e. 3) is printed and a=3-1=2. 3
17 Value of --a is printed i.e. a=2-1=1
and the value of a(i.e. 1) is printed. 1
18 a-- i.e. a=1-1=0
19 Value of a(i.e. 0) is printed. 0
In this way, the statements are executed and we obtain our required output on the screen.
No comments:
Post a Comment