Data Types and Formatted Output
Declare integer and floating-point values and print them safely.
What is Data Types and Formatted Output?
C and C++ share fundamental numeric types, but their preferred formatting mechanisms differ.
Important points
- Compile with warnings enabled and fix every warning.
- Know the lifetime and type of every value.
- Validate input and keep array bounds explicit.
C and C++ code examples
#include <stdio.h>
int main(void) {
int items = 7;
double price = 3.5;
printf("items=%d total=%.2f\n", items, items * price);
return 0;
}
items=7 total=24.50
#include <iomanip>
#include <iostream>
int main() {
int items = 7;
double price = 3.5;
std::cout << "items=" << items << " total="
<< std::fixed << std::setprecision(2) << items * price << '\n';
}
items=7 total=24.50
C and C++ comparison
printf requires a format specifier that matches each promoted argument. C++ stream insertion selects an overload from the value type and iomanip controls precision.
C exposes small procedural APIs and makes representation details explicit.
C++ retains the low-level model while adding safer library types and abstractions.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Add invalid and boundary-value inputs.
- Compile with -Wall -Wextra -Wpedantic.
- Move reusable declarations into a header and implementation file.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Hours, Minutes, and Seconds Convert a duration in seconds to a compact readable string. Easy
- Celsius to Fahrenheit Convert a temperature from Celsius to Fahrenheit. Easy