Change and Use Variables in C
- Changing Variable Values
Once you create a variable, you can change (update) its value later in the program.
When a new value is assigned, it overwrites the previous one.
Example:
int myNum = 15; // myNum is 15
myNum = 10; // Now myNum becomes 10
printf(“%d”, myNum);
✅ Output:
10
👉 Explanation:
The first value (15) is replaced by the new value (10).
- Assign One Variable’s Value to Another
You can assign (copy) the value of one variable to another.
Example:
int myNum = 15;
int myOtherNum = 23
// Assign value of myOtherNum (23) to myNum
myNum = myOtherNum;
printf(“%d”, myNum);
✅ Output:
23
👉 Explanation:
myNum took the value of myOtherNum, so myNum is now 23
- Copy Values into Empty Variables
You can also assign a value from one variable to another empty variable.
Example:
int myNum = 15;
int myOtherNum
myOtherNum = myNum; // Copy valu
printf(“%d”, myOtherNum);
✅ Output:
15
- Add Variables Together
You can perform math operations with variables — like addition, subtraction, multiplication, etc.
Example:
int x = 5;
int y = 6;
int sum = x + y;
printf(“%d”, sum);
✅ Output:
11
Quick Summary
|
Action |
Description |
Example |
Result |
|
Change variable value |
Overwrites old value |
myNum = 10; |
Updates value |
|
Copy one variable to another |
Assigns value |
myNum = myOtherNum; |
Same value |
|
Assign to empty variable |
Copies existing value |
myOtherNum = myNum; |
Gets copied value |
|
Add variables |
Performs arithmetic |
sum = x + y; |
Adds values |