Skip to content

Assignment statements

Once you have a variable, you can use it to store a value and then change that value over time. Use an assignment statement to store a value in the variable. The variable will retain that value until you use another assignment statement to change it.

The basic form of the assignment statement has the name of the variable to change, an = and then the value to store. There are also several shorthand methods for changing the value:

  • a = b; will store the value b in the variable a.
  • a += b; will store the value a + b in the variable a. With similar options for -=, *=, and /=.
  • a++; will store the value a + 1 in the variable a. Can also be written as ++a;.

An illustration of assignment statements

Example

This code includes some assignment statements that store values in the name, userInput, balance, and transaction variables.

using static SplashKitSDK.SplashKit;
using static System.Convert;
string name, userInput;
int balance;
int transaction;
Write("Please enter your name: ");
name = ReadLine();
Write("Enter initial balance: ");
userInput = ReadLine();
balance = ToInt32(userInput);
Write("Enter transaction amount: ");
userInput = ReadLine();
transaction = ToInt32(userInput);
balance += transaction;
WriteLine($"{name}, the new balance is now: {balance}");

Activities

What will the following do?

  1. age = 21;
  2. name = ReadLine();
  3. interestPayment = balance * rate;
  4. age = age + 1;
  5. age += 1;
  6. age++;
Answers
  • 1: Stores 21 in the age variable.
  • 2: Calls ReadLine and stores the result in the name variable.
  • 3: Calculates balance * rate and stores the result in interestPayment.
  • 4: Reads the current value of age, adds one to it, and stores the result back into age.
  • 5: This is the same as 4.
  • 6: This is the same as 4.