C ProgrammingUnit 211 min read
Data Types, Variables, Constants: Fundamentals & Usage in C
Unit 2 of C Programming covers fundamental building blocks—data types, variables, and constants—explaining their syntax, storage, and practical applications in programs, with real-world ties to Nepalese tech (e.g., Ncell billing, Daraz inventory) and exam-focused traces.
Core Concepts: Data Types, Variables, and Constants
1. Data Types: The Blueprint of Data
Data types define the kind of data a variable can hold and the operations it supports. In C, they are categorized into basic (primitive) and derived types.
Basic Data Types
| Data Type | Keyword | Size (bytes) | Range (Approx.) | Example Values |
|---|---|---|---|---|
| Integer | int |
2 or 4 | to (2B) or to (4B) | 42, -7, 0 |
| Character | char |
1 | to (signed) or to (unsigned) | 'A', 'x', '$' |
| Floating-point | float |
4 | to | 3.14, -0.001 |
| Double | double |
8 | to | 3.1415926535 |
| Void | void |
0 | No value; used for functions returning nothing | N/A |
Why does this matter?
- Precision:
floatvs.doubleaffects financial calculations (e.g., NEPSE stock prices). - Memory: Smaller types (e.g.,
char) save memory in large datasets (e.g., Daraz product IDs).
(Shows how int occupies 4 bytes, float 4 bytes, and char 1 byte, with bit patterns for 42, 3.14, and 'A'.)
2. Variables: Named Storage Locations
Variables are containers that store data. They must be declared before use.
Rules for Variable Names
- Start with a letter or underscore (
_). - No spaces or special characters (except
_). - Case-sensitive (
age≠Age). - Cannot be a C keyword (e.g.,
int,float).
Example: Declaring Variables
int age = 25; // Integer variable
float salary = 35000.50; // Floating-point variable
char grade = 'A'; // Character variable
Trace: Variable Initialization
| Variable | Initial Value | Memory Address (Hypothetical) | Explanation |
|---|---|---|---|
age |
25 |
0x7ffd42a1b3ac |
Stores integer 25 |
salary |
35000.50 |
0x7ffd42a1b3b0 |
Stores floating-point value |
grade |
'A' |
0x7ffd42a1b3b4 |
Stores ASCII value 65 |
In the real world
- Ncell Billing System: Uses
intfor call duration (minutes) andfloatfor billing amounts (e.g.,3.50NPR/minute). - Daraz Inventory: Stores product quantities as
int(e.g.,stock[1001] = 50for 50 units of a product). - Bank Loan Calculations: Uses
doublefor precise interest rates (e.g.,5.75%annual interest).
3. Constants: Immutable Values
Constants are fixed values that cannot be modified after initialization. They improve code readability and prevent accidental changes.
stateDiagram-v2 [*] --> ReadOnly ReadOnly --> [*]: const variable state "ReadOnly" as RO RO --> RO : Attempt to modify note right of RO: Compile-time error note left of RO: Stored in read-only memory segment
Behavior of const variables in C (e.g., TAXRATE = 0.13 in Khalti transactions)
Types of Constants
- Literal Constants: Direct values in code.
int max_students = 100; // Literal constant - Symbolic Constants: Defined using
#define(preprocessor directive).#define PI 3.14159 #define MAX_SPEED 120 constKeyword: Ensures a variable’s value cannot be changed.const float TAX_RATE = 0.13; // VAT rate in Nepal
Example: Using Constants in a Program
#include <stdio.h>
#define DISCOUNT 0.10 // 10% discount for bulk orders
int main() {
const int ORDER_LIMIT = 50; // Minimum order for discount
int order_quantity = 60;
float total = 1000.0;
if (order_quantity >= ORDER_LIMIT) {
total *= (1 - DISCOUNT);
}
printf("Final amount: %.2f\n", total);
return 0;
}
Trace: Execution Flow
| Step | order_quantity |
total |
Condition Check | Output |
|---|---|---|---|---|
| Start | 60 |
1000.0 |
60 >= 50 → true |
N/A |
| After discount | 60 |
900.0 |
N/A | Final amount: 900.00 |
(Shows const variables in read-only memory segments, while regular variables can be modified.)
4. Type Modifiers: Extending Data Types
Modifiers alter the range or behavior of basic data types.
| Modifier | Effect | Example | Use Case |
|---|---|---|---|
signed |
Default for integers (includes negatives) | signed int x = -5; |
General-purpose integers |
unsigned |
Only non-negative values | unsigned int y = 10; |
Counting (e.g., array indices) |
short |
Smaller range (2 bytes) | short temp = 300; |
Memory-efficient small numbers |
long |
Larger range (4 or 8 bytes) | long population = 30000000L; |
Large datasets (e.g., Nepal census) |
Example: Using unsigned for Counts
unsigned int product_count = 1000; // Cannot be negative
Why?
- NEPSE Stock Ticker: Uses
unsigned intfor share quantities (e.g.,1000shares of NABIL). - Khalti Transactions: Uses
unsigned longfor transaction IDs to avoid overflow.
5. Type Conversion: Explicit and Implicit
Implicit Conversion (Automatic)
Occurs when operands of different types are mixed. C promotes smaller types to larger ones to avoid data loss.
int a = 5;
float b = 3.14;
float result = a + b; // `a` is converted to `float` implicitly
Trace: Implicit Conversion
| Operation | a (int) |
b (float) |
result (float) |
Explanation |
|---|---|---|---|---|
a + b |
5 |
3.14 |
8.14 |
5 promoted to 5.0 |
Explicit Conversion (Casting)
Forces a type change using (type) syntax.
float price = 99.99;
int discount = (int)price; // Truncates decimal part
Example: NTC Electricity Bill Calculation
float units_consumed = 250.5;
int billable_units = (int)units_consumed; // Truncate to 250 units
float cost = billable_units * 4.50; // 4.50 NPR/unit
printf("Bill: %.2f NPR\n", cost); // Output: 1125.00 NPR
flowchart TD
A["Operation: int + float"] --> B["Implicit: int → float"]
C["Operation: float → int"] --> D["Explicit: (int)float"]
B --> E["Result: float"]
D --> F["Result: int (truncated)"]6. Variable Scope and Lifetime
Scope: Where a Variable is Accessible
| Scope | Keyword/Block | Example | Lifetime |
|---|---|---|---|
| Local | Inside a function | int x = 10; in main() |
Exists while function runs |
| Global | Outside functions | int global_var; at file level |
Entire program |
| Block | Inside {} |
for (int i = 0; ...) |
Until block ends |
Example: Scope in Action
#include <stdio.h>
int global = 10; // Global variable
void func() {
int local = 20; // Local variable
printf("Local: %d, Global: %d\n", local, global);
}
int main() {
printf("Global in main: %d\n", global);
func();
return 0;
}
Output:
Global in main: 10
Local: 20, Global: 10
In the real world
- Pathao Driver App: Uses local variables for real-time trip details (e.g.,
float distance = 5.2;insidecalculate_fare()). - NTC Call Center: Global variables store system-wide constants (e.g.,
const float PENALTY_RATE = 0.20;for late payments).
In the real world
- Ncell Billing System: Uses
intfor call duration (minutes) andfloatfor billing amounts (e.g.,3.50NPR/minute) to balance precision and memory efficiency. - Daraz Inventory: Stores product quantities as
int(e.g.,stock[1001] = 50for 50 units of a product) to ensure non-negative counts and fast arithmetic. - NTC Electricity Bill Calculation: Uses explicit casting (
int) to truncate fractional units (e.g.,250.5→250units) before applying the4.50NPR/unit rate.
Exam Tip
- Memorize Key Ranges: Know the approximate ranges of
int,float, anddoublefor questions on overflow/underflow. - Practice Declarations: Write declarations for all basic types and modifiers (e.g.,
unsigned short int). - Trace Variable Changes: For programs with assignments/loops, show the state of variables after each step (like the traces above).
- Constant Usage: Always use
#defineorconstfor magic numbers (e.g.,3.14→#define PI 3.14). - Type Conversion Pitfalls: Watch for implicit conversions in arithmetic (e.g.,
int / inttruncates decimals). - Scope Questions: Identify whether a variable is local/global and its lifetime in multi-function programs.
Worked Example for Exam Practice Problem: Write a program to calculate the total cost of a Daraz order with a 10% discount if the order exceeds 500 NPR. Use constants for the discount rate and threshold. Solution:
#include <stdio.h>
#define DISCOUNT_RATE 0.10
#define MIN_AMOUNT 500.0
int main() {
float item_price = 250.0;
int quantity = 3;
float total = item_price * quantity;
if (total >= MIN_AMOUNT) {
total *= (1 - DISCOUNT_RATE);
}
printf("Total cost: %.2f NPR\n", total);
return 0;
}
Trace:
| Step | item_price |
quantity |
total |
Condition Check | Output |
|---|---|---|---|---|---|
| Start | 250.0 |
3 |
750.0 |
750.0 >= 500.0 → true |
N/A |
| After discount | 250.0 |
3 |
675.0 |
N/A | Total cost: 675.00 |
Visual Summary
mindmap
root((Data Types, Variables, Constants))
Basic Types
int["int: -2^31 to 2^31-1"]
float["float: ±3.4e-38 to ±3.4e38"]
char["char: -128 to 127 (signed)"]
Modifiers
unsigned["unsigned int: 0 to 2^32-1"]
short["short int: -32768 to 32767"]
long["long int: -2^63 to 2^63-1"]
Variables
Declaration["int age = 25;"]
Scope["Local vs. Global"]
Constants
Literal["#define PI 3.14"]
const["const float TAX = 0.13;"]
Conversion
Implicit["int + float → float"]
Explicit["(int)float → truncated"]Based on the TU BIM syllabus for C Programming (IT232), unit 2.
Discussion
Loading…