Operators for assignment – Computer Sir Ki Class Code Learning #CPP#1734    ## Operators for assignment

Here we demonstrate the simple assignment and its variations.

## Learning Objectives

• Learning simple assignment and assignment within declaration.
• Learning composite assignments with use of +, – , * and / operator along with assignment operator.

## Source Code

 #include using namespace std; int main() { int a; a=10; a+=10; cout<

## Run Output

``````20
10
100
10``````

## Code Understanding

int a; a=10;
This is simple variable declaration followed by simple assignment using a single = operator. This can also be done in one instruction as int a=10;

a+=10; cout<<a<<endl;
This a composite assignment along with addition. The instruction a+=10 is equivalent to a=a+10; This is an efficient way of incrementing the variable by given number. Later we print it to produce 20 as the initial value of a was 10.

a-=10; cout<<a<<endl;
This a composite assignment along with subtraction. The instruction a-=10 is equivalent to a=a-10; This is an efficient way of decrementing the variable by given number. Later we print it to produce 10 as a was made 20 in previous instruction.

a*=10; cout<<a<<endl;
This a composite assignment along with multiplication. The instruction a*=10 is equivalent to a=a*10; This is an efficient way of multiplying the variable by given number. Later we print it to produce 100 as a was made 10 in previous instruction.

a/=10; cout<<a<<endl;
This a composite assignment along with division. The instruction a/=10 is equivalent to a=a/10; This is an efficient way of dividing the variable by given number. Later we print it to produce 10 as a was made 100 in previous instruction.

## Notes

While using assignment and composite assignments, care must be taken that the value assigned fits the data size of target data type like int, float, long, char etc.

Suggested Filename(s): operators-assign.cpp, assignments.cpp

CSKC| Created: 15-Dec-2017 | Updated: 28-Aug-2018|

×