Menu
Coddy logo textTech

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 8

We can simplify it by writing:

int a = 5;
a += 3; // a now holds 8

The += is adding 3 to a and then assigning the result back to a.

challenge icon

Challenge

Easy

Write a C program that demonstrates the use of assignment operators. Your program should:

  1. Declare an integer variable num and initialize it with the value 10.
  2. Use the += operator to add 5 to num.
  3. Use the -= operator to subtract 3 from num.
  4. Use the *= operator to multiply num by 2.
  5. Use the /= operator to divide num by 3.
  6. Use the %= operator to get the remainder of num divided 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 in printf. 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;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals