Variables in C
In C programming, a variable is a named location in memory used to store data that can change during program execution.
Simply put, variables allow us to store information, reuse it, modify it, and work with it logically.
Why Variables Are Important
Without variables, programs would be useless. Variables help us:
- Store user input
- Perform calculations
- Reuse values multiple times
- Make programs dynamic instead of fixed
Declaring a Variable
Before using a variable in C, it must be declared. Declaration tells the compiler:
- What type of data the variable will store
- The name of the variable
int age;
float salary;
char grade;
Here:
intis the data typeageis the variable name
Initializing Variables
Initialization means assigning a value to a variable.
int age = 25;
float salary = 35000.50;
char grade = 'A';
It is always a good habit to initialize variables before using them.
Rules for Naming Variables
C follows strict rules for variable names:
- Must start with a letter or underscore
- Cannot start with a number
- No spaces allowed
- Only letters, digits, and underscore allowed
- Keywords cannot be used as variable names
Examples:
- Valid:
totalMarks,_count,salary1 - Invalid:
1value,total marks,int
Using Variables in a Program
Let us see a practical example where variables are used for calculation.
#include <stdio.h>
int main() {
int a = 10;
int b = 20;
int sum;
sum = a + b;
printf("Sum = %d", sum);
return 0;
}
Here, variables a and b store numbers,
and sum stores the result of addition.
Real-World Example
Think of variables like labeled containers.
age→ stores agebalance→ stores bank balancescore→ stores game score
The label (variable name) stays the same, but the value inside can change.
Mini Practice
- Create variables for two numbers
- Calculate their sum and difference
- Print both results
Quick Quiz
Q1. What is a variable?
A variable is a named memory location used to store data.
Q2. Why must variables be declared?
Declaration tells the compiler the data type and memory size.
Q3. Which of these is a valid variable name: 1value or value1?
value1 is valid; variable names cannot start with numbers.
Q4. What happens if a variable is used without initialization?
It may contain garbage (unpredictable) values.
Q5. Can a variable value change during program execution?
Yes, variables are designed to store changeable values.