C Subtraction Assignment Operator
In C, the Subtraction Assignment -= operator is a shorthand operator used to subtract a value from a variable and assign the result back to that variable.
Subtraction Assignment is equivalent to writing variable = variable - value. This operator is useful for reducing code redundancy and improving readability.
Syntax of the Subtraction Assignment Operator
The syntax to use the Subtraction Assignment operator is:
variable -= value;
Explanation:
variable: The operand whose value will be updated.-=: The subtraction assignment operator.value: The value to be subtracted fromvariable.- The operation
variable -= valueis equivalent tovariable = variable - value.
Examples of the Subtraction Assignment Operator
1. Basic Usage of the Subtraction Assignment Operator
In this example, we will demonstrate the basic use of the -= operator by subtracting a value from an integer variable.
main.c
#include <stdio.h>
int main() {
int num = 20;
num -= 5; // Equivalent to num = num - 5
printf("Result: %d\n", num);
return 0;
}
Explanation:
- We declare an integer variable
numand initialize it with 20. - The statement
num -= 5subtracts 5 fromnumand assigns the new value tonum. - The final value of
numis 15, which is printed usingprintf().
Output:
Result: 15
2. Using Subtraction Assignment in a Loop
In this example, we will use the -= operator inside a loop to decrease a variable’s value repeatedly.
main.c
#include <stdio.h>
int main() {
int count = 10;
while (count > 0) {
printf("%d ", count);
count -= 2; // Subtract 2 in each iteration
}
return 0;
}
Explanation:
- We declare an integer variable
countand initialize it with 10. - The
whileloop runs as long ascountis greater than 0. - Inside the loop, the value of
countis printed. - The
count -= 2statement reduces the value ofcountby 2 in each iteration. - The loop terminates when
countbecomes 0 or negative.
Output:
10 8 6 4 2
3. Subtracting Float Values Using Subtraction Assignment
In this example, we will use the -= operator with floating-point numbers.
main.c
#include <stdio.h>
int main() {
float price = 50.75;
price -= 10.25; // Subtracting 10.25 from price
printf("Final Price: %.2f\n", price);
return 0;
}
Explanation:
- We declare a floating-point variable
priceand initialize it with 50.75. - The statement
price -= 10.25subtracts 10.25 frompriceand stores the result back inprice. - The final value of
priceis 40.50, which is printed usingprintf()with two decimal places.
Output:
Final Price: 40.50
Conclusion
In this tutorial, we covered the Subtraction Assignment -= operator in C:
- The
-=operator subtracts a value from a variable and assigns the result back to that variable. - It simplifies expressions like
variable = variable - value. - It can be used with different data types, such as integers and floating-point numbers.
- It is useful in loops and mathematical operations.
