Assignment Operators
Part of the Fundamentals section of Coddy's C journey — lesson 19 of 63.
Assignment operators in C are used to assign values to variables. The most basic assignment operator is the equals sign =. However, C also provides compound assignment operators that combine arithmetic operations with assignment.
Here are the common assignment operators:
=: Simple assignment
+=: Add and assign-=: Subtract and assign
*=: Multiply and assign/=: Divide and assign%=: Modulo and assign
For example, instead of writing:
int a = 5;
a = a + 3; // a now holds 8We can simplify it by writing:
int a = 5;
a += 3; // a now holds 8The += is adding 3 to a and then assigning the result back to a.
Challenge
EasyWrite a C program that demonstrates the use of assignment operators. Your program should:
- Declare an integer variable
numand initialize it with the value 10. - Use the
+=operator to add 5 tonum. - Use the
-=operator to subtract 3 fromnum. - Use the
*=operator to multiplynumby 2. - Use the
/=operator to dividenumby 3. - Use the
%=operator to get the remainder ofnumdivided by 4.
After each operation, print the value of num using printf() in the following format:
After += 5: [value]
After -= 3: [value]
After *= 2: [value]
After /= 3: [value]
After %= 4: [value]Note on Printing: In C, the
%character is a special symbol inprintf. If you want to print a literal%sign as text, you must use a double percent sign%%in your format string as in this example:printf("After %%= 4: %d\n", num);
Cheat sheet
Assignment operators in C are used to assign values to variables:
=: Simple assignment+=: Add and assign-=: Subtract and assign*=: Multiply and assign/=: Divide and assign%=: Modulo and assign
Compound assignment operators combine arithmetic operations with assignment:
int a = 5;
a += 3; // equivalent to: a = a + 3; (a now holds 8)Try it yourself
#include <stdio.h>
int main() {
int num = 10;
// 1. Add 5 to num using the += operator and print the result
// 2. Subtract 3 from num using the -= operator and print the result
// 3. Multiply num by 2 using the *= operator and print the result
// 4. Divide num by 3 using the /= operator and print the result
// 5. Get the remainder of num divided by 4 using the %= operator and print the result
// Remember to use %% in your printf statement to display the % symbol!
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
3Operators
Arithmetic OperatorsModulo OperatorIncrement/DecrementAssignment OperatorsRelational OperatorsLogical Operators Part 1Logical Operators Part 2Logical Operators Part 3Recap Challenge