C Variables

What are Variables in C?

Variables are used to store data in a program. A variable acts like a container that holds information which can be used and modified during program execution.

Each variable has:

• A name
• A data type
• A value

Before using a variable in C, it must be declared with a suitable data type.

Example

int age = 20;

Here,

• int is the data type
• age is the variable name
• 20 is the value stored in the variable

Rules for Naming Variables

A variable name in C must follow certain rules:

• It can contain letters, digits, and underscore (_)
• It cannot start with a digit
• It cannot contain spaces
• It cannot use C keywords such as int, float, if, while, etc.
• Variable names should be meaningful and easy to understand

Valid Variable Names:

✓ age
✓ student_name
✓ totalMarks
✓ num1

Invalid Variable Names:

✗ 1age
✗ student name
✗ int
✗ total-marks

Variable Declaration

A variable must be declared before it is used in a program.

Syntax:

data_type variable_name;

int age;
float salary;
char grade;

Explanation

• int age; → Declares an integer variable named age.

• float salary; → Declares a floating-point variable named salary that can store decimal values.

• char grade; → Declares a character variable named grade that can store a single character.

These variables are declared but no values are assigned yet.

Variable Initialization

Variable initialization means assigning a value to a variable at the time of declaration.

Syntax

data_type variable_name = value;

Example

int age = 20;
float salary = 25000.50;
char grade = ‘A’;

Explanation

• int age = 20; → Initializes the variable age with the value 20.

• float salary = 25000.50; → Initializes the variable salary with the value 25000.50.

• char grade = ‘A’; → Initializes the variable grade with the character A.

Example Program

Program

#include <stdio.h>

int main()
{
int age = 20;

printf(“Age = %d”, age);

return 0;
}

Output

Age = 20

Explanation

• #include <stdio.h> → Includes the standard input/output library.

• int main() → Starting point of the program execution.

• int age = 20; → Declares and initializes an integer variable named age with value 20.

• printf(“Age = %d”, age); → Displays the value stored in the variable age.

• %d → Format specifier used to print integer values.

• return 0; → Terminates the program successfully.

Key Points

• Variables are used to store data in a program.

• Every variable must have a data type.

• Variable names must follow naming rules.

• Variables should be declared before they are used.

• Variables can be initialized at the time of declaration.

• Meaningful variable names make programs easier to understand.