Welcome to the first lesson in our C Programming series! Today, we're going to dive deep into one of the fundamental concepts: Variables. Variables are like containers in C programming that hold values.
Variables are named storage locations used to store data in a program. You can think of them as containers where you can put different values during the execution of a program.
C provides several types of variables:
int: Integer variables used to store whole numbers like 3, -12, etc.float: Floating-point variables used to store decimal numbers like 3.14, 0.001, etc.char: Character variables used to store single characters like 'A', 'b', etc.boolean: Although C doesn't have a specific Boolean data type, we can use int to represent Boolean values with 0 for false and any non-zero value for true.To use a variable in your program, you first need to declare it. Here's how to declare variables in C:
data_type variable_name;For example, to declare an integer variable named age, you would write:
int age;After declaring a variable, you can assign a value to it using the = operator.
variable_name = value;For example:
int age = 25;age and Age are different variables).You can declare multiple variables of the same type separated by commas.
data_type variable1, variable2, ..., variableN;For example:
int age, height, weight;The scope of a variable determines where it can be accessed in the program. Variables can have either global or local scope.
Global variables are accessible throughout the entire program. To declare a global variable, place it outside of any functions.
int global_age; // Declare global variable
void function() {
// You can access global_age here
}Local variables are only accessible within the function they are declared. To declare a local variable, place it inside a function.
void function() {
int local_age; // Declare local variable
// You can only access local_age inside this function
}Initializing a variable means giving it an initial value at the time of declaration.
data_type variable_name = initial_value;For example:
int age = 25; // Declare and initialize ageConstants are variables that cannot be changed during the execution of a program. In C, constants are declared using the const keyword.
const data_type variable_name = value;For example:
const int PI = 3.14; // Declare and initialize a constantWhat is the correct syntax to declare an integer variable named `age`?
Stay tuned for the next lesson, where we'll explore operators and expressions in C programming! 🎯