0
0
C Sharp (C#)programming~5 mins

Assignment and compound assignment in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Assignment lets you store a value in a variable. Compound assignment helps you update that value quickly.

When you want to save a number or text to use later.
When you want to add or subtract from a value already stored.
When you want to multiply or divide a value and keep the result.
When you want to update a variable without writing it twice.
Syntax
C Sharp (C#)
variable = value;
variable += value;
variable -= value;
variable *= value;
variable /= value;
variable %= value;

The single equals sign = means 'store this value'.

Compound assignments like += mean 'add and store', so x += 3 is like x = x + 3.

Examples
This sets x first to 5, then changes it to 10.
C Sharp (C#)
int x = 5;
x = 10;
This adds 3 to x, so x becomes 8.
C Sharp (C#)
int x = 5;
x += 3;
This subtracts 4 from x, so x becomes 6.
C Sharp (C#)
int x = 10;
x -= 4;
This multiplies x by 4, so x becomes 12.
C Sharp (C#)
int x = 3;
x *= 4;
Sample Program

This program shows how to use assignment and compound assignment to change the value of score. It prints the value after each change so you can see how it updates.

C Sharp (C#)
using System;

class Program
{
    static void Main()
    {
        int score = 10;
        Console.WriteLine($"Initial score: {score}");

        score += 5;  // Add 5
        Console.WriteLine($"After adding 5: {score}");

        score -= 3;  // Subtract 3
        Console.WriteLine($"After subtracting 3: {score}");

        score *= 2;  // Multiply by 2
        Console.WriteLine($"After multiplying by 2: {score}");

        score /= 4;  // Divide by 4
        Console.WriteLine($"After dividing by 4: {score}");

        score %= 3;  // Remainder after dividing by 3
        Console.WriteLine($"After modulo 3: {score}");
    }
}
OutputSuccess
Important Notes

Compound assignments save time and make code easier to read.

Be careful with division and modulo to avoid dividing by zero.

Summary

Use = to store a value in a variable.

Use compound assignments like +=, -=, *= to update values quickly.

Compound assignments combine an operation and assignment in one step.