C++ Assignment Operators
Assignment operators in C++ are used to assign values to variables and update their values using arithmetic operations. This tutorial provides separate examples for each operator and a combined program demonstrating all assignment operators.
1. Simple Assignment (=)
Assigns the value of the right-hand side to the left-hand side variable.
#include <iostream>
using namespace std;
int main() {
int a;
a = 10;
cout << "a = " << a << endl;
return 0;
}
2. Addition Assignment (+=)
Adds the right-hand side value to the left-hand side variable and assigns the result to the left-hand side.
#include <iostream>
using namespace std;
int main() {
int a = 5;
a += 3; // a = a + 3
cout << "a += 3 -> a = " << a << endl;
return 0;
}
3. Subtraction Assignment (-=)
Subtracts the right-hand side value from the left-hand side variable and assigns the result to the left-hand side.
#include <iostream>
using namespace std;
int main() {
int a = 10;
a -= 4; // a = a - 4
cout << "a -= 4 -> a = " << a << endl;
return 0;
}
4. Multiplication Assignment (*=)
Multiplies the left-hand side variable by the right-hand side value and assigns the result to the left-hand side.
#include <iostream>
using namespace std;
int main() {
int a = 5;
a *= 3; // a = a * 3
cout << "a *= 3 -> a = " << a << endl;
return 0;
}
5. Division Assignment (/=)
Divides the left-hand side variable by the right-hand side value and assigns the result to the left-hand side.
#include <iostream>
using namespace std;
int main() {
int a = 15;
a /= 3; // a = a / 3
cout << "a /= 3 -> a = " << a << endl;
return 0;
}
6. Modulus Assignment (%=)
Calculates the remainder of dividing the left-hand side variable by the right-hand side value and assigns the result to the left-hand side.
#include <iostream>
using namespace std;
int main() {
int a = 10;
a %= 3; // a = a % 3
cout << "a %= 3 -> a = " << a << endl;
return 0;
}
7. Combined Program
This program demonstrates all assignment operators together.
#include <iostream>
using namespace std;
int main() {
int a = 10;
cout << "Initial value: a = " << a << endl;
a = 20;
cout << "After = : a = " << a << endl;
a += 5;
cout << "After += 5: a = " << a << endl;
a -= 3;
cout << "After -= 3: a = " << a << endl;
a *= 2;
cout << "After *= 2: a = " << a << endl;
a /= 4;
cout << "After /= 4: a = " << a << endl;
a %= 3;
cout << "After %= 3: a = " << a << endl;
return 0;
}
Conclusion
C++ assignment operators allow assigning and updating variable values efficiently. Using separate examples and a combined program helps understand the behavior of =, +=, -=, *=, /=, and %= operators.
Codecrown