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 -= value
is 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
num
and initialize it with 20. - The statement
num -= 5
subtracts 5 fromnum
and assigns the new value tonum
. - The final value of
num
is 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
count
and initialize it with 10. - The
while
loop runs as long ascount
is greater than 0. - Inside the loop, the value of
count
is printed. - The
count -= 2
statement reduces the value ofcount
by 2 in each iteration. - The loop terminates when
count
becomes 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
price
and initialize it with 50.75. - The statement
price -= 10.25
subtracts 10.25 fromprice
and stores the result back inprice
. - The final value of
price
is 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.