Variables
A variable is a named memory location used to store data. The value of a variable can change during program execution.
Syntax
data_type variable_name;
Examples
int age;
float salary;
char grade;
Or with initialization:
int age = 20;
float salary = 35000.50;
char grade = 'A';
Rules for Naming Variables
- Must begin with a letter (A–Z, a–z) or underscore (_).
- Cannot begin with a digit.
- Can contain letters, digits, and underscores.
- Cannot contain spaces or special characters.
- Cannot use C keywords (e.g.,
int,float,if,while) as variable names. - Variable names are case-sensitive (
Ageandageare different).
Valid Variable Names
int marks;
float total_marks;
char studentName;
int _count;
Invalid Variable Names
int 2marks; // Starts with a digit
float total marks; // Contains a space
char int; // Keyword used as variable name
Data Types in C
A data type specifies the type of data a variable can store and the amount of memory allocated to it.
1. Basic (Primary) Data Types
| Data Type | Description | Typical Size | Example |
|---|---|---|---|
int | Stores integer values | 4 bytes | int age = 25; |
char | Stores a single character | 1 byte | char grade = 'A'; |
float | Stores decimal numbers | 4 bytes | float price = 99.99; |
double | Stores large decimal numbers | 8 bytes | double pi = 3.14159265; |
void | Represents no value | – | void display(); |
2. Derived Data Types
- Arrays
- Pointers
- Functions
Example
int numbers[5];
int *ptr;
3. User-Defined Data Types
structunionenumtypedef
Example
struct Student
{
int roll;
char name[30];
};
Example Program
#include <stdio.h>
int main()
{
int age = 21;
float salary = 45000.75;
char grade = 'A';
double pi = 3.1415926535;
printf("Age = %d\n", age);
printf("Salary = %.2f\n", salary);
printf("Grade = %c\n", grade);
printf("Value of PI = %.10lf\n", pi);
return 0;
}
Output
Age = 21
Salary = 45000.75
Grade = A
Value of PI = 3.1415926535
Summary
- A variable is a named memory location used to store data.
- A data type determines the type of data a variable can hold.
- Common data types include
int,char,float,double, andvoid. - C also supports derived and user-defined data types for more complex programming needs.
Category: MCA
