cpp
exercises
exercises.cpp⚙️cpp
/**
* Function Parameters - Exercises
*
* Practice problems for understanding parameter passing in C++.
* Each exercise includes TODO sections to complete.
*
* Compile: g++ -std=c++17 -Wall -Wextra exercises.cpp -o exercises
* Run: ./exercises
*/
#include <iostream>
#include <string>
#include <vector>
#include <cmath>
using namespace std;
// ============================================================
// Exercise 1: Swap Two Integers ⭐
// ============================================================
/**
* Swap two integers using references.
*
* Example:
* int a = 5, b = 10;
* swapInts(a, b);
* // Now a = 10, b = 5
*/
void swapInts(int& a, int& b) {
// TODO: Implement swap using a temporary variable
}
// ============================================================
// Exercise 2: Triple Value ⭐
// ============================================================
/**
* Multiply a value by 3 using reference.
*
* Example:
* int x = 5;
* triple(x);
* // Now x = 15
*/
void triple(int& value) {
// TODO: Implement
}
// ============================================================
// Exercise 3: Clamp Value ⭐
// ============================================================
/**
* Clamp a value between min and max using reference.
* If value < min, set to min. If value > max, set to max.
*
* Example:
* int x = 15;
* clamp(x, 0, 10);
* // Now x = 10
*/
void clamp(int& value, int minVal, int maxVal) {
// TODO: Implement
}
// ============================================================
// Exercise 4: Safe Division ⭐⭐
// ============================================================
/**
* Divide a by b and store result in pointer.
* Return false if b is 0 or result is nullptr.
*
* Example:
* double result;
* bool ok = safeDivide(10, 3, &result); // ok=true, result≈3.33
* ok = safeDivide(5, 0, &result); // ok=false
*/
bool safeDivide(int a, int b, double* result) {
// TODO: Implement with null and zero checks
return false;
}
// ============================================================
// Exercise 5: Get Statistics ⭐⭐
// ============================================================
/**
* Calculate min, max, and sum of a vector.
* Use pointer parameters for outputs (can be nullptr).
* Return false if vector is empty.
*
* Example:
* vector<int> v = {3, 1, 4, 1, 5};
* int min, max, sum;
* getStats(v, &min, &max, &sum); // min=1, max=5, sum=14
* getStats(v, &min, nullptr, nullptr); // Only get min
*/
bool getStats(const vector<int>& v, int* outMin, int* outMax, int* outSum) {
// TODO: Implement with null checks for each output
return false;
}
// ============================================================
// Exercise 6: Normalize String ⭐⭐
// ============================================================
/**
* Convert string to lowercase and trim spaces from ends.
* Modify in place using reference.
*
* Example:
* string s = " Hello World ";
* normalize(s);
* // Now s = "hello world"
*/
void normalize(string& s) {
// TODO: Convert to lowercase and remove leading/trailing spaces
}
// ============================================================
// Exercise 7: Fill Vector Range ⭐⭐
// ============================================================
/**
* Clear vector and fill with values from start to end.
* Use default step of 1.
*
* Example:
* vector<int> v;
* fillRange(v, 1, 5); // v = {1, 2, 3, 4, 5}
* fillRange(v, 0, 10, 2); // v = {0, 2, 4, 6, 8, 10}
*/
void fillRange(vector<int>& v, int start, int end, int step = 1) {
// TODO: Implement with default step
}
// ============================================================
// Exercise 8: Remove Element ⭐⭐
// ============================================================
/**
* Remove all occurrences of value from vector.
* Modify vector in place.
* Return count of removed elements via pointer (optional).
*
* Example:
* vector<int> v = {1, 2, 3, 2, 4, 2};
* int removed;
* removeAll(v, 2, &removed); // v = {1, 3, 4}, removed = 3
*/
void removeAll(vector<int>& v, int value, int* removedCount = nullptr) {
// TODO: Implement
}
// ============================================================
// Exercise 9: Parse Integer ⭐⭐⭐
// ============================================================
/**
* Parse string to integer. Return true if successful.
* Store result in pointer. Handle nullptr.
*
* Example:
* int num;
* bool ok = parseInt("123", &num); // ok=true, num=123
* ok = parseInt("abc", &num); // ok=false
* ok = parseInt("-45", &num); // ok=true, num=-45
*/
bool parseInt(const string& str, int* result) {
// TODO: Implement (handle negative numbers, invalid input)
return false;
}
// ============================================================
// Exercise 10: Binary Search ⭐⭐⭐
// ============================================================
/**
* Perform binary search on sorted vector.
* Return true if found. Store index in pointer.
*
* Example:
* vector<int> v = {1, 3, 5, 7, 9, 11};
* int idx;
* bool found = binarySearch(v, 7, &idx); // found=true, idx=3
* found = binarySearch(v, 6, &idx); // found=false
*/
bool binarySearch(const vector<int>& v, int target, int* outIndex) {
// TODO: Implement binary search
return false;
}
// ============================================================
// Exercise 11: Quadratic Formula ⭐⭐⭐
// ============================================================
/**
* Solve ax² + bx + c = 0.
* Return number of real solutions (0, 1, or 2).
* Store solutions in pointers (can be nullptr).
*
* Example:
* double x1, x2;
* int n = solveQuadratic(1, -5, 6, &x1, &x2); // n=2, x1=2, x2=3
* n = solveQuadratic(1, 2, 1, &x1, &x2); // n=1, x1=-1
* n = solveQuadratic(1, 0, 1, &x1, &x2); // n=0 (no real roots)
*/
int solveQuadratic(double a, double b, double c, double* x1, double* x2) {
// TODO: Use discriminant to find solutions
// d = b² - 4ac
// d > 0: two solutions
// d = 0: one solution
// d < 0: no real solutions
return 0;
}
// ============================================================
// Exercise 12: Matrix Multiply Row ⭐⭐⭐
// ============================================================
/**
* Multiply a specific row of a 2D vector by a scalar.
* Modify in place. Return false if row index invalid.
*
* Example:
* vector<vector<int>> matrix = {{1, 2}, {3, 4}, {5, 6}};
* scaleRow(matrix, 1, 2); // matrix = {{1, 2}, {6, 8}, {5, 6}}
*/
bool scaleRow(vector<vector<int>>& matrix, size_t row, int scalar) {
// TODO: Implement with bounds checking
return false;
}
// ============================================================
// TEST FUNCTIONS
// ============================================================
void testExercise1() {
cout << "\n=== Exercise 1: Swap Integers ===" << endl;
int a = 5, b = 10;
cout << "Before: a=" << a << ", b=" << b << endl;
swapInts(a, b);
cout << "After: a=" << a << ", b=" << b;
cout << (a == 10 && b == 5 ? " ✓" : " ✗") << endl;
}
void testExercise2() {
cout << "\n=== Exercise 2: Triple Value ===" << endl;
int x = 5;
triple(x);
cout << "triple(5) = " << x;
cout << (x == 15 ? " ✓" : " ✗") << endl;
}
void testExercise3() {
cout << "\n=== Exercise 3: Clamp Value ===" << endl;
int x = 15;
clamp(x, 0, 10);
cout << "clamp(15, 0, 10) = " << x;
cout << (x == 10 ? " ✓" : " ✗") << endl;
x = -5;
clamp(x, 0, 10);
cout << "clamp(-5, 0, 10) = " << x;
cout << (x == 0 ? " ✓" : " ✗") << endl;
}
void testExercise4() {
cout << "\n=== Exercise 4: Safe Division ===" << endl;
double result;
bool ok = safeDivide(10, 4, &result);
cout << "safeDivide(10, 4) = " << result << ", ok=" << boolalpha << ok;
cout << (ok && abs(result - 2.5) < 0.001 ? " ✓" : " ✗") << endl;
ok = safeDivide(5, 0, &result);
cout << "safeDivide(5, 0) ok=" << ok;
cout << (!ok ? " ✓" : " ✗") << endl;
}
void testExercise5() {
cout << "\n=== Exercise 5: Get Statistics ===" << endl;
vector<int> v = {3, 1, 4, 1, 5, 9, 2, 6};
int minV, maxV, sumV;
bool ok = getStats(v, &minV, &maxV, &sumV);
cout << "min=" << minV << ", max=" << maxV << ", sum=" << sumV;
cout << (ok && minV == 1 && maxV == 9 && sumV == 31 ? " ✓" : " ✗") << endl;
ok = getStats({}, &minV, &maxV, &sumV);
cout << "Empty vector returns false: " << (!ok ? "✓" : "✗") << endl;
}
void testExercise6() {
cout << "\n=== Exercise 6: Normalize String ===" << endl;
string s = " Hello World ";
normalize(s);
cout << "normalize(\" Hello World \") = \"" << s << "\"";
cout << (s == "hello world" ? " ✓" : " ✗") << endl;
}
void testExercise7() {
cout << "\n=== Exercise 7: Fill Range ===" << endl;
vector<int> v;
fillRange(v, 1, 5);
cout << "fillRange(1, 5): ";
for (int n : v) cout << n << " ";
cout << (v == vector<int>{1, 2, 3, 4, 5} ? "✓" : "✗") << endl;
fillRange(v, 0, 10, 2);
cout << "fillRange(0, 10, 2): ";
for (int n : v) cout << n << " ";
cout << (v == vector<int>{0, 2, 4, 6, 8, 10} ? "✓" : "✗") << endl;
}
void testExercise8() {
cout << "\n=== Exercise 8: Remove Element ===" << endl;
vector<int> v = {1, 2, 3, 2, 4, 2};
int removed;
removeAll(v, 2, &removed);
cout << "After removeAll(2): ";
for (int n : v) cout << n << " ";
cout << ", removed=" << removed;
cout << (v == vector<int>{1, 3, 4} && removed == 3 ? " ✓" : " ✗") << endl;
}
void testExercise9() {
cout << "\n=== Exercise 9: Parse Integer ===" << endl;
int num;
bool ok = parseInt("123", &num);
cout << "parseInt(\"123\") = " << num << ", ok=" << boolalpha << ok;
cout << (ok && num == 123 ? " ✓" : " ✗") << endl;
ok = parseInt("-45", &num);
cout << "parseInt(\"-45\") = " << num << ", ok=" << ok;
cout << (ok && num == -45 ? " ✓" : " ✗") << endl;
ok = parseInt("abc", &num);
cout << "parseInt(\"abc\") ok=" << ok;
cout << (!ok ? " ✓" : " ✗") << endl;
}
void testExercise10() {
cout << "\n=== Exercise 10: Binary Search ===" << endl;
vector<int> v = {1, 3, 5, 7, 9, 11, 13};
int idx;
bool found = binarySearch(v, 7, &idx);
cout << "binarySearch(7) found=" << boolalpha << found << ", idx=" << idx;
cout << (found && idx == 3 ? " ✓" : " ✗") << endl;
found = binarySearch(v, 6, &idx);
cout << "binarySearch(6) found=" << found;
cout << (!found ? " ✓" : " ✗") << endl;
}
void testExercise11() {
cout << "\n=== Exercise 11: Quadratic Formula ===" << endl;
double x1, x2;
int n = solveQuadratic(1, -5, 6, &x1, &x2);
cout << "x²-5x+6=0: n=" << n;
if (n == 2) {
cout << ", x1=" << min(x1, x2) << ", x2=" << max(x1, x2);
bool correct = (abs(min(x1,x2) - 2) < 0.001 && abs(max(x1,x2) - 3) < 0.001);
cout << (correct ? " ✓" : " ✗");
}
cout << endl;
n = solveQuadratic(1, 0, 1, &x1, &x2);
cout << "x²+1=0: n=" << n << (n == 0 ? " ✓" : " ✗") << endl;
}
void testExercise12() {
cout << "\n=== Exercise 12: Scale Matrix Row ===" << endl;
vector<vector<int>> matrix = {{1, 2}, {3, 4}, {5, 6}};
bool ok = scaleRow(matrix, 1, 2);
cout << "scaleRow(row=1, scalar=2): ";
for (const auto& row : matrix) {
cout << "[";
for (int n : row) cout << n << " ";
cout << "] ";
}
bool correct = ok && matrix[1][0] == 6 && matrix[1][1] == 8;
cout << (correct ? "✓" : "✗") << endl;
}
// ============================================================
// MAIN FUNCTION
// ============================================================
int main() {
cout << "╔════════════════════════════════════════════════════════════╗" << endl;
cout << "║ FUNCTION PARAMETERS - EXERCISES ║" << endl;
cout << "╚════════════════════════════════════════════════════════════╝" << endl;
testExercise1();
testExercise2();
testExercise3();
testExercise4();
testExercise5();
testExercise6();
testExercise7();
testExercise8();
testExercise9();
testExercise10();
testExercise11();
testExercise12();
cout << "\n╔════════════════════════════════════════════════════════════╗" << endl;
cout << "║ Complete the TODO sections and re-run! ║" << endl;
cout << "╚════════════════════════════════════════════════════════════╝" << endl;
return 0;
}
// ============================================================
// ANSWER KEY
// ============================================================
/*
void swapInts(int& a, int& b) {
int temp = a; a = b; b = temp;
}
void triple(int& value) { value *= 3; }
void clamp(int& value, int minVal, int maxVal) {
if (value < minVal) value = minVal;
else if (value > maxVal) value = maxVal;
}
bool safeDivide(int a, int b, double* result) {
if (b == 0 || result == nullptr) return false;
*result = static_cast<double>(a) / b;
return true;
}
bool getStats(const vector<int>& v, int* outMin, int* outMax, int* outSum) {
if (v.empty()) return false;
int minV = v[0], maxV = v[0], sum = 0;
for (int n : v) {
if (n < minV) minV = n;
if (n > maxV) maxV = n;
sum += n;
}
if (outMin) *outMin = minV;
if (outMax) *outMax = maxV;
if (outSum) *outSum = sum;
return true;
}
void normalize(string& s) {
for (char& c : s) c = tolower(c);
size_t start = s.find_first_not_of(' ');
size_t end = s.find_last_not_of(' ');
if (start == string::npos) { s = ""; return; }
s = s.substr(start, end - start + 1);
}
void fillRange(vector<int>& v, int start, int end, int step) {
v.clear();
for (int i = start; i <= end; i += step) v.push_back(i);
}
void removeAll(vector<int>& v, int value, int* removedCount) {
int count = 0;
auto it = v.begin();
while (it != v.end()) {
if (*it == value) { it = v.erase(it); count++; }
else ++it;
}
if (removedCount) *removedCount = count;
}
bool parseInt(const string& str, int* result) {
if (str.empty()) return false;
int sign = 1, start = 0;
if (str[0] == '-') { sign = -1; start = 1; }
else if (str[0] == '+') start = 1;
if (start >= str.size()) return false;
int num = 0;
for (size_t i = start; i < str.size(); i++) {
if (!isdigit(str[i])) return false;
num = num * 10 + (str[i] - '0');
}
if (result) *result = sign * num;
return true;
}
bool binarySearch(const vector<int>& v, int target, int* outIndex) {
int left = 0, right = v.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (v[mid] == target) {
if (outIndex) *outIndex = mid;
return true;
}
if (v[mid] < target) left = mid + 1;
else right = mid - 1;
}
return false;
}
int solveQuadratic(double a, double b, double c, double* x1, double* x2) {
double d = b*b - 4*a*c;
if (d < 0) return 0;
if (d == 0) {
if (x1) *x1 = -b / (2*a);
return 1;
}
double sqrtD = sqrt(d);
if (x1) *x1 = (-b + sqrtD) / (2*a);
if (x2) *x2 = (-b - sqrtD) / (2*a);
return 2;
}
bool scaleRow(vector<vector<int>>& matrix, size_t row, int scalar) {
if (row >= matrix.size()) return false;
for (int& val : matrix[row]) val *= scalar;
return true;
}
*/