Change Variable Values
If you assign a new value to an existing variable, the new value will replace the old one:
Example
int myNum = 15; // myNum is 15
myNum = 10; // Now myNum is 10
Note: This is normal and expected. Variables are meant to change while a program runs.
You can also assign the value of one variable to another:
Example
int myNum = 15;
int myOtherNum = 23;
// Assign the value of myOtherNum (23) to myNum
myNum = myOtherNum;
// myNum is now 23 (was 15)
printf("%d", myNum);
You can even copy values into variables that were declared earlier without a value:
Example
// Create a variable and assign a value
int myNum = 15;
// Declare a variable without assigning a value
int myOtherNum;
// Copy the value from myNum
myOtherNum = myNum;
// myOtherNum is now 15
printf("%d", myOtherNum);
Add Variables Together
You can use mathematical operators to work with variables.
For example, to add one variable to another, use the + operator:
Example
int x = 5;
int y = 6;
int sum = x + y;
printf("%d", sum);
You can also update a variable using its current value:
Example
int x = 5;
x = x + 1;
printf("%d", x);
Tip: Writing
x = x + 1means "take the current value of x and add 1 to it". Note: You will learn much more about operators in a later chapter.