C Addition Assignment Operator
In C, the Addition Assignment += operator is a compound assignment operator that adds the right operand to the left operand and assigns the result to the left operand.
Addition Assignment is a shorthand for writing variable = variable + value. The += operator is commonly used in loops, arithmetic operations, and counter updates.
Syntax of the Addition Assignment Operator
The syntax to use the Addition Assignment operator is:
variable += value;
Explanation:
variable: The left operand that stores the result.+=: The addition assignment operator.value: The right operand to be added tovariable.
Examples of the Addition Assignment Operator
1. Using Addition Assignment on an Integer
In this example, we will use the += operator to add a value to an integer variable.
main.c
#include <stdio.h>
int main() {
int num = 10;
num += 5; // Equivalent to num = num + 5
printf("Updated value of num: %d\n", num);
return 0;
}
Explanation:
- We declare an integer variable
numand initialize it to 10. - We use the addition assignment operator
+=to add 5 tonum. - The updated value of
numbecomes10 + 5 = 15. - The final value of
numis printed usingprintf().
Output:
Updated value of num: 15
2. Using Addition Assignment in a Loop
In this example, we will use the += operator in a loop to calculate the sum of numbers from 1 to 5.
main.c
#include <stdio.h>
int main() {
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum += i; // Adds i to sum in each iteration
}
printf("Sum of numbers from 1 to 5: %d\n", sum);
return 0;
}
Explanation:
- We declare an integer variable
sumand initialize it to 0. - We use a
forloop to iterate from 1 to 5. - Inside the loop,
sum += iadds the current value ofitosum. - The loop continues until
ireaches 5, and the total sum is stored insum. - The final value of
sumis printed usingprintf().
Output:
Sum of numbers from 1 to 5: 15
3. Using Addition Assignment with Floating-Point Numbers
In this example, we will use the += operator with floating-point numbers.
main.c
#include <stdio.h>
int main() {
float price = 100.50;
price += 9.75; // Adding a floating-point value
printf("Updated price: %.2f\n", price);
return 0;
}
Explanation:
- We declare a floating-point variable
priceand initialize it to 100.50. - We use the addition assignment operator
+=to add 9.75 toprice. - The updated value of
pricebecomes100.50 + 9.75 = 110.25. - The final value of
priceis printed usingprintf()with two decimal places.
Output:
Updated price: 110.25
Conclusion
In this tutorial, we covered the Addition Assignment += operator in C:
- The
+=operator is used to add a value to a variable and assign the result to the same variable. - It is a shorthand for
variable = variable + value. - It can be used with different data types, such as integers and floating-point numbers.
- It is commonly used in loops, counters, and arithmetic operations.
