Sure! Here's an example of using compound assignment operators in C++:
#include <iostream>
int main() {
// Initialize variables
int x = 10;
int y = 5;
// Addition assignment (+=)
x += 3; // Equivalent to x = x + 3
std::cout << "After x += 3, x = " << x << std::endl;
// Subtraction assignment (-=)
y -= 2; // Equivalent to y = y - 2
std::cout << "After y -= 2, y = " << y << std::endl;
// Multiplication assignment (*=)
int z = 4;
z *= 3; // Equivalent to z = z * 3
std::cout << "After z *= 3, z = " << z << std::endl;
// Division assignment (/=)
int a = 15;
a /= 3; // Equivalent to a = a / 3
std::cout << "After a /= 3, a = " << a << std::endl;
// Modulus assignment (%=)
int b = 17;
b %= 5; // Equivalent to b = b % 5
std::cout << "After b %= 5, b = " << b << std::endl;
return 0;
}
Example Output:
After x += 3, x = 13
After y -= 2, y = 3
After z *= 3, z = 12
After a /= 3, a = 5
After b %= 5, b = 2
This code demonstrates the use of various compound assignment operators in C++. You can compile and run it to see the results.
