Real-Life Examples of Variables
How Variables Model Real Life
Variables represent real-world values in a program. For example, an `int age = 25;` models a person’s age.
Different types of variables help model different types of data: integers for counts, floats for measurements, chars for symbols, etc.
Examples in Context
• **Banking app**: `double balance = 1500.75;`
• **Game**: `int playerScore = 100;`
• **Weather system**: `float temperature = 29.5;`
• **School system**: `char grade = 'B';`
#include <stdio.h>
int main(void) {
int age = 21;
float temperature = 36.5f;
double bankBalance = 2450.75;
char grade = 'A';
// Print without using "\n" inside string literals
printf("Age: %d", age); puts("");
printf("Temp: %.1f", temperature); puts("");
printf("Balance: %.2f", bankBalance); puts("");
printf("Grade: %c", grade); puts("");
return 0;
}
Age: 21 Temp: 36.5 Balance: 2450.75 Grade: A
Choosing Types in Real Apps
• **Money**: prefer integer cents to avoid floating-point rounding (e.g., `long long cents = 245075;`).
• **Counts/IDs**: `int`/`unsigned int` (or wider types for large ranges).
• **Measurements**: `double` for precision (temperatures, distances).
• **Yes/No flags**: `_Bool`/`bool` from `
• **Single symbols**: `char`, and text strings as `char[]` (null-terminated).
Format Specifiers (printf/scanf) Cheatsheet
Type | printf | scanf | Notes |
---|---|---|---|
int | %d | %d | Basic integers |
long long | %lld | %lld | Very large integers |
float | %f | %f | printf promotes float to double; still use %f |
double | %f | %lf | %lf only in scanf |
char | %c | %c | Single character |
string (char*) | %s | %s | Null-terminated string |
Updating Values Over Time (Money in Cents)
This example models real bank operations safely using integer cents.
#include <stdio.h>
int main(void) {
long long balanceCents = 245075; // $2450.75
// Deposit $50.00
balanceCents += 5000;
// Purchase $12.50
balanceCents -= 1250;
// Pretty-print as dollars.cents without using "\n" in string literals
printf("Balance: $%lld.%02lld",
balanceCents / 100,
(long long)(balanceCents % 100));
puts("");
return 0;
}
Balance: $2488.25
Analogy
Think of variables as labeled jars. One jar may contain marbles (integers), another water (floats), and another a note (character). Each jar has a label (name) and can be refilled (value changed).