Programming lesson
Mastering File I/O, Functions, and Randomization in C++: A Practical Guide for Assignment 06
Learn how to tackle C++ assignments involving file input/output, user-defined functions, and random number generation with real-world examples and step-by-step explanations.
Introduction to C++ File I/O and Functions
In computer science, reading data from files and writing functions are fundamental skills. This tutorial covers four common programming tasks: reading numbers from a file, calculating retail price with markup, simulating gravity's effect on falling objects, and tossing a virtual coin. These problems mirror real-world applications like analyzing sensor data, pricing products, physics simulations, and game randomness. By mastering these, you'll be ready for more complex projects, including AI data processing or mobile app development.
Program 1: Reading Numbers from a File
The first program requires opening a text file (e.g., Random.txt), reading all numbers, and computing count, sum, and average. This is essential for handling datasets in fields like finance, sports analytics, or scientific research.
File Streams and Error Handling
Use ifstream to open the file. Always check if the file opened successfully:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
const string FILENAME = "Random.txt";
ifstream inputFile(FILENAME);
if (!inputFile) {
cout << "Error opening file.\n";
return 1;
}
// ...
}Reading and Calculating
Read numbers in a loop until EOF. Keep running total and count:
int number, count = 0;
double sum = 0.0;
while (inputFile >> number) {
count++;
sum += number;
}
inputFile.close();
double average = sum / count;
cout << "Number of numbers: " << count << endl;
cout << "Sum of the numbers: " << sum << endl;
cout << "Average: " << average << endl;This pattern is similar to how a sports app calculates a player's average score over a season. For example, imagine reading game scores from a file to compute a basketball player's average points per game.
Program 2: Retail Price Calculator
This program asks for wholesale cost and markup percentage, then displays retail price. It uses a function to encapsulate the calculation, promoting code reuse.
Function Definition
Create calculateRetail that takes two double parameters and returns the retail price:
double calculateRetail(double wholesale, double markupPercent) {
if (wholesale < 0 || markupPercent < 0) {
cout << "Negative values not allowed.\n";
return -1;
}
return wholesale * (1 + markupPercent / 100);
}Input Validation
Do not accept negative values. In the main function, validate before calling:
double cost, markup;
cout << "Enter wholesale cost: ";
cin >> cost;
cout << "Enter markup percentage: ";
cin >> markup;
if (cost < 0 || markup < 0) {
cout << "Invalid input.\n";
} else {
double retail = calculateRetail(cost, markup);
cout << fixed << setprecision(2);
cout << "Retail price: $" << retail << endl;
}This function is like a pricing algorithm in e-commerce apps, such as those used by online retailers to calculate final prices after discounts or taxes.
Program 3: Falling Distance Simulation
Using physics formula d = 0.5 * g * t^2 with g = 9.8, this program prints distances for times 1 through 10.
Function Implementation
double fallingDistance(double time) {
const double G = 9.8;
return 0.5 * G * time * time;
}Loop and Output
In main, loop from 1 to 10, call the function, and display with two decimal places:
cout << fixed << setprecision(2);
for (int t = 1; t <= 10; t++) {
double dist = fallingDistance(t);
cout << t << " " << dist << " meters" << endl;
}This mirrors how simulation games (e.g., flight simulators) compute object movement. It's also relevant to physics engines in modern video games like "Fortnite" or "Minecraft" where gravity affects projectiles.
Program 4: Coin Toss Simulation
Simulate coin tosses using random numbers. The function prints "heads" or "tails" and does not return a value.
Random Number Generation
Seed with current time for randomness:
#include <cstdlib>
#include <ctime>
unsigned seed = time(0);
srand(seed);
void coinToss() {
int result = 1 + rand() % 2;
if (result == 1)
cout << "heads";
else
cout << "tails";
}User Input Loop
Ask how many tosses and call the function that many times:
int tosses;
cout << "How many tosses? ";
cin >> tosses;
for (int i = 1; i <= tosses; i++) {
cout << i << ": ";
coinToss();
cout << endl;
}Randomization is key in gaming (e.g., loot boxes, dice rolls) and AI simulations (e.g., Monte Carlo methods). This simple coin toss is a building block for more complex probability-based programs.
Bringing It All Together
Each program teaches a core concept: file I/O, functions with return values, mathematical functions, and random number generation. These are essential for tackling assignments in C++ and beyond, whether you're building a data analysis tool, a pricing calculator, a physics simulation, or a game. Practice by modifying the examples: try reading different file formats, adding more validation, or extending the coin toss to simulate a dice roll.
Remember to test edge cases: empty files, negative inputs, zero time, and large numbers. Good coding habits like using constants, validating input, and separating logic into functions will serve you well in future projects, including those involving AI and machine learning where data preprocessing is crucial.