In C, variables must be declared before they are used, and they can be initialized at the time of declaration. Here’s how you can declare and initialize variables in C:
1. Declaring a Variable
To declare a variable, you specify the type of the variable followed by its name:
int number; float decimal; char character;
2. Initializing a Variable
You can initialize a variable at the time of declaration by assigning it a value:
int number = 10; float decimal = 3.14; char character = 'A';
3. Multiple Declarations and Initializations
You can declare and initialize multiple variables of the same type in a single line:
int a = 5, b = 10, c = 15; float x = 1.1, y = 2.2, z = 3.3;
4. Constant Variables
You can also declare variables as constants, which means their values cannot be changed after initialization:
const int constantNumber = 100;
Example Program
Here’s an example program that demonstrates variable declaration and initialization in C:
#include <stdio.h> int main() { int age = 25; float height = 5.9; char grade = 'A'; printf("Age: %d\n", age); printf("Height: %.1f\n", height); printf("Grade: %c\n", grade); return 0; };
This program declares and initializes three variables (age
, height
, and grade
) and prints their values.