C-Program
Variables and Data Types
Last Updated on: 23rd Jan 2025 11:24:04 AM
1. What is a Variable?
In simple terms, a variable is a named storage location in the computer's memory that holds a value. Think of it as a container that can hold different types of data.
- Name (Identifier): Every variable has a name that uniquely identifies it. This name is used to access the variable's value.
- Type: A variable has a type that determines the kind of data it can store (e.g., integer, floating-point number, character).
- Value: The actual data stored in the variable. This value can change during the program's execution (hence the name "variable").
2. Declaring Variables
Before using a variable in C, you must declare it. Declaration tells the compiler the variable's name and its data type. The general syntax is:
data_type variable_name;
Examples:
int age; // Declares an integer variable named age
float price; // Declares a floating-point variable named price
char initial; // Declares a character variable named initial
You can also declare and initialize a variable in the same line:
int score = 100; // Declares an integer variable score and initializes it to 100
float pi = 3.14159; // Declares a float variable pi and initializes it
char grade = 'A'; // Declares a char variable grade and initializes it to 'A'
3.Data Types in C
C provides several built-in data types:
- Primitive Types:
-
Integer Types: Used for whole numbers (without decimal points).
int
: The most common integer type. Typically 4 bytes (but can vary depending on the system).short int
(orshort
): Smaller integer type, usually 2 bytes.long int
(orlong
): Larger integer type, usually 4 or 8 bytes.long long int
(orlong long
): Even larger integer type, usually 8 bytes.unsigned int
,unsigned short
,unsigned long
,unsigned long long
: These are the unsigned versions of the above types. They can only store non-negative values (0 and positive numbers), effectively doubling the positive range.
- Derived Types:
- Arrays, Pointers, Structures, etc.
Example:
#include <stdio.h>
int main() {
int number = 10;
char grade = 'A';
float percentage = 85.5;
printf("Number: %d\n", number);
printf("Grade: %c\n", grade);
printf("Percentage: %.1f\n", percentage);
return 0;
}
Become a first user to comment