Numeric Data Types in C
Numeric data types in C are used to store numbers. They are divided into integer types for whole numbers and floating-point types for real numbers with fractional parts.
Key Topics
1. Integer Types
Integer types are used to store whole numbers, both positive and negative.
Type | Keyword | Size (bytes) | Range |
---|---|---|---|
Short Integer | short | 2 | -32,768 to 32,767 |
Integer | int | 2 or 4 | Depends on system |
Long Integer | long | 4 | -2,147,483,648 to 2,147,483,647 |
Long Long Integer | long long | 8 | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
Example: Using Integer Types
short s = 32000;
int i = 100000;
long l = 2000000000;
long long ll = 9000000000000000000;
printf("Short: %d\n", s);
printf("Int: %d\n", i);
printf("Long: %ld\n", l);
printf("Long Long: %lld\n", ll);
Output:
Short: 32000 Int: 100000 Long: 2000000000 Long Long: 9000000000000000000
Code Explanation: Different integer types are used to store numbers of varying sizes. Format specifiers like %d
, %ld
, and %lld
are used for printing.
2. Floating-Point Types
Floating-point types are used to store real numbers with decimal points.
Type | Keyword | Size (bytes) | Precision |
---|---|---|---|
Float | float | 4 | 6 decimal places |
Double | double | 8 | 15 decimal places |
Long Double | long double | 10, 12, or 16 | 19 decimal places |
Example: Using Floating-Point Types
float f = 3.14159f;
double d = 2.7182818284;
long double ld = 1.6180339887;
printf("Float: %.5f\n", f);
printf("Double: %.10lf\n", d);
printf("Long Double: %.10Lf\n", ld);
Output:
Float: 3.14159 Double: 2.7182818284 Long Double: 1.6180339887
Code Explanation: Floating-point numbers are declared and printed with specified precision using format specifiers like %.5f
, %.10lf
, and %.10Lf
.
3. Type Modifiers
Type modifiers like signed
, unsigned
, short
, and long
alter the size and range of basic data types.
Example: Unsigned Integer
unsigned int u = 4000000000;
printf("Unsigned Int: %u\n", u);
Output:
Unsigned Int: 4000000000
Code Explanation: The unsigned int
type allows for larger positive values by excluding negative numbers.
Best Practices
- Choose the appropriate data type based on the range of values you expect.
- Use type modifiers to optimize memory usage and performance.
- Be mindful of integer overflow and underflow.
Don'ts
- Don't mix signed and unsigned types without proper handling.
- Don't assume the size of data types; use
sizeof()
to confirm. - Don't neglect floating-point precision errors in calculations.
Key Takeaways
- Numeric data types are essential for storing and manipulating numbers in C.
- Understanding the size and range of each type helps prevent errors.
- Type modifiers allow for customization of data types to fit specific needs.