In this guide, we’ll go over variables in C, which are fundamental to storing data in programming. We’ll learn how to declare, initialize, and work with variables.
Understanding Variables in C
What Are Variables?
Variables in C hold data that we can use and manipulate. Here’s how to declare a variable in C:
// Declaring variables in C
int age = 25; // integer variable
float height = 5.9; // float variable
char grade = 'A'; // character variable
Different types of variables hold different types of data, such as integers, floats, and characters.
Example: Using Variables in a Program
Let's see an example where we declare and print different variable types:
#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;
}
Modifying Variable Values
Variables in C can be modified after declaration. Example:
#include <stdio.h>
int main() {
int age = 25;
age = age + 10;
printf("Age in 10 years: %d\n", age);
return 0;
}
Key Takeaways
- Variables store data that can be used and changed.
- Every variable has a specific data type (e.g.,
int
,float
,char
). - Variables must be declared before use.
- Variable values can be modified after declaration.