Practical Examples
Temperature Tracking System
#include <iostream>
#include <iomanip>
class TemperatureLogger {
private:
static const int DAYS = 7;
double temperatures[DAYS];
public:
void recordTemperatures() {
double dailyTemps[DAYS] = {22.5, 23.1, 21.8, 24.0, 22.7, 23.3, 21.9};
std::copy(std::begin(dailyTemps), std::end(dailyTemps), temperatures);
}
void analyzeTemperatures() {
double total = 0;
for (int i = 0; i < DAYS; ++i) {
total += temperatures[i];
}
double average = total / DAYS;
std::cout << "Weekly Temperature Analysis:" << std::endl;
std::cout << "Average Temperature: " << std::fixed << std::setprecision(2)
<< average << "ยฐC" << std::endl;
}
};
int main() {
TemperatureLogger logger;
logger.recordTemperatures();
logger.analyzeTemperatures();
return 0;
}
Student Grade Management
#include <iostream>
#include <algorithm>
class GradeTracker {
private:
static const int CLASS_SIZE = 5;
int grades[CLASS_SIZE];
public:
void inputGrades() {
int studentGrades[CLASS_SIZE] = {85, 92, 78, 95, 88};
std::copy(std::begin(studentGrades), std::end(studentGrades), grades);
}
void calculateStatistics() {
int highest = *std::max_element(grades, grades + CLASS_SIZE);
int lowest = *std::min_element(grades, grades + CLASS_SIZE);
std::cout << "Grade Statistics:" << std::endl;
std::cout << "Highest Grade: " << highest << std::endl;
std::cout << "Lowest Grade: " << lowest << std::endl;
}
};
int main() {
GradeTracker tracker;
tracker.inputGrades();
tracker.calculateStatistics();
return 0;
}
Memory Visualization
graph TD
A[Fixed Length Array] --> B[Contiguous Memory Block]
B --> C[Element Storage]
C --> D[Direct Index Access]
D --> E[Efficient Processing]
Array Type |
Access Time |
Memory Overhead |
Flexibility |
Fixed Length |
O(1) |
Low |
Limited |
Dynamic Array |
O(1) |
Higher |
Flexible |
std::array |
O(1) |
Controlled |
Safer |
Error Handling Example
#include <stdexcept>
class SafeArray {
private:
static const int MAX_SIZE = 10;
int data[MAX_SIZE];
public:
int& at(int index) {
if (index < 0 || index >= MAX_SIZE) {
throw std::out_of_range("Index out of bounds");
}
return data[index];
}
};
Best Practices with LabEx
- Always initialize arrays
- Use bounds checking
- Prefer std::array for modern C++
- Understand memory implications
Compilation and Execution
To compile these examples on Ubuntu 22.04:
g++ -std=c++11 example.cpp -o example
./example