cpp

exercises

exercises.cpp⚙️
/**
 * Pointers in C++ - Exercises
 * 
 * Practice problems for understanding pointers.
 * Each exercise includes TODO sections to complete.
 * 
 * Compile: g++ -std=c++17 -Wall -Wextra exercises.cpp -o exercises
 * Run: ./exercises
 */

#include <iostream>
#include <string>

using namespace std;

// ============================================================
// Exercise 1: Basic Pointer Operations ⭐
// ============================================================
/**
 * Create a pointer to an integer and use it.
 */
void exercise1() {
    int value = 42;
    
    // TODO: Declare a pointer and initialize it to point to 'value'
    int* ptr = nullptr;  // Fix this
    
    // TODO: Print the value using the pointer (dereference)
    cout << "Value through pointer: " << 0 << " (expected: 42)" << endl;
    
    // TODO: Modify 'value' through the pointer to 100
    
    cout << "Modified value: " << value << " (expected: 100)" << endl;
}

// ============================================================
// Exercise 2: Pointer Address Practice ⭐
// ============================================================
/**
 * Understand the relationship between variables and addresses.
 */
void exercise2() {
    int x = 10;
    int* ptr = &x;
    
    // TODO: Complete the comparisons (replace 'false' with correct expression)
    bool addressMatch = false;  // Compare ptr with &x
    bool valueMatch = false;    // Compare *ptr with x
    
    cout << "Address match: " << boolalpha << addressMatch << " (expected: true)" << endl;
    cout << "Value match: " << valueMatch << " (expected: true)" << endl;
}

// ============================================================
// Exercise 3: Swap Using Pointers ⭐⭐
// ============================================================
/**
 * Implement a swap function using pointers.
 */
void swapPointers(int* a, int* b) {
    // TODO: Swap the values that a and b point to
    
}

void exercise3() {
    int x = 10;
    int y = 20;
    
    cout << "Before swap: x = " << x << ", y = " << y << endl;
    swapPointers(&x, &y);
    cout << "After swap: x = " << x << ", y = " << y << " (expected: 20, 10)" << endl;
}

// ============================================================
// Exercise 4: Array Traversal with Pointers ⭐⭐
// ============================================================
/**
 * Traverse an array using pointer arithmetic.
 */
void exercise4() {
    int arr[] = {10, 20, 30, 40, 50};
    int size = 5;
    
    // TODO: Create a pointer to the first element
    int* ptr = nullptr;  // Fix this
    
    cout << "Array elements using pointer arithmetic: ";
    // TODO: Use pointer arithmetic in a loop to print all elements
    // Don't use arr[i] - use pointer dereference and increment
    for (int i = 0; i < size; i++) {
        // Print *(ptr + i) or use ptr[i]
    }
    cout << endl;
    cout << "(expected: 10 20 30 40 50)" << endl;
}

// ============================================================
// Exercise 5: Find Maximum Using Pointers ⭐⭐
// ============================================================
/**
 * Find the maximum value in an array using pointers.
 * Return a pointer to the maximum element.
 */
int* findMax(int* arr, int size) {
    // TODO: Return pointer to the maximum element
    // Use pointer arithmetic to traverse
    return nullptr;
}

void exercise5() {
    int arr[] = {23, 45, 12, 67, 34, 89, 56};
    int size = 7;
    
    int* maxPtr = findMax(arr, size);
    
    if (maxPtr != nullptr) {
        cout << "Maximum value: " << *maxPtr << " (expected: 89)" << endl;
    }
}

// ============================================================
// Exercise 6: Reverse Array Using Pointers ⭐⭐
// ============================================================
/**
 * Reverse an array in place using two pointers.
 */
void reverseArray(int* arr, int size) {
    // TODO: Use two pointers (start and end) to reverse the array
    // Hint: int* start = arr; int* end = arr + size - 1;
    
}

void exercise6() {
    int arr[] = {1, 2, 3, 4, 5};
    int size = 5;
    
    cout << "Before reverse: ";
    for (int i = 0; i < size; i++) cout << arr[i] << " ";
    cout << endl;
    
    reverseArray(arr, size);
    
    cout << "After reverse: ";
    for (int i = 0; i < size; i++) cout << arr[i] << " ";
    cout << endl;
    cout << "(expected: 5 4 3 2 1)" << endl;
}

// ============================================================
// Exercise 7: Pointer to Pointer ⭐⭐
// ============================================================
/**
 * Modify a pointer through a pointer-to-pointer.
 */
void setToNull(int** pptr) {
    // TODO: Set the pointer that pptr points to, to nullptr
    
}

void exercise7() {
    int x = 42;
    int* ptr = &x;
    
    cout << "Before setToNull: ptr = " << ptr << endl;
    cout << "                  *ptr = " << *ptr << endl;
    
    setToNull(&ptr);
    
    cout << "After setToNull: ptr = " << ptr << " (expected: 0 or nullptr)" << endl;
}

// ============================================================
// Exercise 8: Const Pointer Practice ⭐⭐
// ============================================================
/**
 * Understand const with pointers.
 */
void exercise8() {
    int x = 10;
    int y = 20;
    
    // TODO: Declare 'ptr1' as pointer to const int, pointing to x
    // const int* ptr1 = ...;
    
    // TODO: Declare 'ptr2' as const pointer to int, pointing to x
    // int* const ptr2 = ...;
    
    // TODO: Which of these operations are valid? (Uncomment valid ones)
    // *ptr1 = 15;    // Modify data through ptr1
    // ptr1 = &y;     // Change ptr1 to point to y
    // *ptr2 = 15;    // Modify data through ptr2
    // ptr2 = &y;     // Change ptr2 to point to y
    
    cout << "Const pointer exercise - check comments for valid operations" << endl;
    cout << "ptr1 (pointer to const): can change pointer, cannot modify data" << endl;
    cout << "ptr2 (const pointer): cannot change pointer, can modify data" << endl;
}

// ============================================================
// Exercise 9: Sum Array Elements ⭐⭐
// ============================================================
/**
 * Calculate sum using pointer traversal.
 */
int sumArray(int* start, int* end) {
    // TODO: Sum all elements from start to end (exclusive)
    // Use pointer comparison and arithmetic
    int sum = 0;
    
    return sum;
}

void exercise9() {
    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int size = 10;
    
    int sum = sumArray(arr, arr + size);
    cout << "Sum of array: " << sum << " (expected: 55)" << endl;
}

// ============================================================
// Exercise 10: Copy Array Using Pointers ⭐⭐
// ============================================================
/**
 * Copy elements from source to destination.
 */
void copyArray(const int* src, int* dest, int size) {
    // TODO: Copy 'size' elements from src to dest using pointers
    
}

void exercise10() {
    int source[] = {10, 20, 30, 40, 50};
    int dest[5] = {0};
    
    copyArray(source, dest, 5);
    
    cout << "Copied array: ";
    for (int i = 0; i < 5; i++) {
        cout << dest[i] << " ";
    }
    cout << endl;
    cout << "(expected: 10 20 30 40 50)" << endl;
}

// ============================================================
// Exercise 11: Count Occurrences ⭐⭐⭐
// ============================================================
/**
 * Count how many times a value appears using pointers.
 */
int countOccurrences(const int* arr, int size, int target) {
    // TODO: Count occurrences of target in array using pointers
    return 0;
}

void exercise11() {
    int arr[] = {1, 2, 3, 2, 4, 2, 5, 2};
    int size = 8;
    
    int count = countOccurrences(arr, size, 2);
    cout << "Count of 2: " << count << " (expected: 4)" << endl;
}

// ============================================================
// Exercise 12: String Length Using Pointer ⭐⭐⭐
// ============================================================
/**
 * Calculate string length using pointer traversal.
 */
int myStrlen(const char* str) {
    // TODO: Count characters until null terminator
    // Use pointer arithmetic
    return 0;
}

void exercise12() {
    const char* str1 = "Hello";
    const char* str2 = "Hello, World!";
    const char* str3 = "";
    
    cout << "Length of 'Hello': " << myStrlen(str1) << " (expected: 5)" << endl;
    cout << "Length of 'Hello, World!': " << myStrlen(str2) << " (expected: 13)" << endl;
    cout << "Length of '': " << myStrlen(str3) << " (expected: 0)" << endl;
}

// ============================================================
// Exercise 13: Find Element Return Pointer ⭐⭐⭐
// ============================================================
/**
 * Find an element and return pointer to it (or nullptr).
 */
int* findElement(int* arr, int size, int target) {
    // TODO: Return pointer to target if found, nullptr if not
    return nullptr;
}

void exercise13() {
    int arr[] = {10, 20, 30, 40, 50};
    int size = 5;
    
    int* found = findElement(arr, size, 30);
    if (found != nullptr) {
        cout << "Found 30 at address: " << found << ", value: " << *found << endl;
    }
    
    found = findElement(arr, size, 100);
    if (found == nullptr) {
        cout << "100 not found (as expected)" << endl;
    }
}

// ============================================================
// Exercise 14: Pointer Distance ⭐⭐⭐
// ============================================================
/**
 * Calculate the number of elements between two pointers.
 */
void exercise14() {
    int arr[] = {10, 20, 30, 40, 50, 60, 70};
    
    int* p1 = arr + 1;      // Points to 20
    int* p2 = arr + 5;      // Points to 60
    
    // TODO: Calculate the number of elements between p1 and p2
    int distance = 0;  // Fix this using pointer subtraction
    
    cout << "p1 points to: " << *p1 << endl;
    cout << "p2 points to: " << *p2 << endl;
    cout << "Distance: " << distance << " elements (expected: 4)" << endl;
}

// ============================================================
// Exercise 15: Modify Through Double Pointer ⭐⭐⭐
// ============================================================
/**
 * Allocate and return an integer through a double pointer.
 */
void createValue(int** pptr, int value) {
    // TODO: Allocate a new int with 'value' and store in *pptr
    // Use: *pptr = new int(value);
    
}

void exercise15() {
    int* ptr = nullptr;
    
    createValue(&ptr, 42);
    
    if (ptr != nullptr) {
        cout << "Created value: " << *ptr << " (expected: 42)" << endl;
        delete ptr;
        ptr = nullptr;
    }
}

// ============================================================
// TEST RUNNER
// ============================================================

int main() {
    cout << "╔════════════════════════════════════════════════════════════╗" << endl;
    cout << "║               POINTERS - EXERCISES                         ║" << endl;
    cout << "╚════════════════════════════════════════════════════════════╝" << endl;
    
    cout << "\n=== Exercise 1: Basic Pointer Operations ===" << endl;
    exercise1();
    
    cout << "\n=== Exercise 2: Pointer Address Practice ===" << endl;
    exercise2();
    
    cout << "\n=== Exercise 3: Swap Using Pointers ===" << endl;
    exercise3();
    
    cout << "\n=== Exercise 4: Array Traversal with Pointers ===" << endl;
    exercise4();
    
    cout << "\n=== Exercise 5: Find Maximum Using Pointers ===" << endl;
    exercise5();
    
    cout << "\n=== Exercise 6: Reverse Array Using Pointers ===" << endl;
    exercise6();
    
    cout << "\n=== Exercise 7: Pointer to Pointer ===" << endl;
    exercise7();
    
    cout << "\n=== Exercise 8: Const Pointer Practice ===" << endl;
    exercise8();
    
    cout << "\n=== Exercise 9: Sum Array Elements ===" << endl;
    exercise9();
    
    cout << "\n=== Exercise 10: Copy Array Using Pointers ===" << endl;
    exercise10();
    
    cout << "\n=== Exercise 11: Count Occurrences ===" << endl;
    exercise11();
    
    cout << "\n=== Exercise 12: String Length Using Pointer ===" << endl;
    exercise12();
    
    cout << "\n=== Exercise 13: Find Element Return Pointer ===" << endl;
    exercise13();
    
    cout << "\n=== Exercise 14: Pointer Distance ===" << endl;
    exercise14();
    
    cout << "\n=== Exercise 15: Modify Through Double Pointer ===" << endl;
    exercise15();
    
    cout << "\n╔════════════════════════════════════════════════════════════╗" << endl;
    cout << "║         Complete the TODO sections and re-run!             ║" << endl;
    cout << "╚════════════════════════════════════════════════════════════╝" << endl;
    
    return 0;
}

// ============================================================
// ANSWER KEY
// ============================================================
/*
// Exercise 1
int* ptr = &value;
cout << "Value through pointer: " << *ptr << endl;
*ptr = 100;

// Exercise 2
bool addressMatch = (ptr == &x);
bool valueMatch = (*ptr == x);

// Exercise 3
void swapPointers(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

// Exercise 4
int* ptr = arr;
for (int i = 0; i < size; i++) {
    cout << *(ptr + i) << " ";
}

// Exercise 5
int* findMax(int* arr, int size) {
    if (size == 0) return nullptr;
    int* maxPtr = arr;
    for (int i = 1; i < size; i++) {
        if (*(arr + i) > *maxPtr) {
            maxPtr = arr + i;
        }
    }
    return maxPtr;
}

// Exercise 6
void reverseArray(int* arr, int size) {
    int* start = arr;
    int* end = arr + size - 1;
    while (start < end) {
        int temp = *start;
        *start = *end;
        *end = temp;
        start++;
        end--;
    }
}

// Exercise 7
void setToNull(int** pptr) {
    *pptr = nullptr;
}

// Exercise 8
const int* ptr1 = &x;
int* const ptr2 = &x;
// Valid: ptr1 = &y; and *ptr2 = 15;
// Invalid: *ptr1 = 15; and ptr2 = &y;

// Exercise 9
int sumArray(int* start, int* end) {
    int sum = 0;
    while (start != end) {
        sum += *start;
        start++;
    }
    return sum;
}

// Exercise 10
void copyArray(const int* src, int* dest, int size) {
    for (int i = 0; i < size; i++) {
        *(dest + i) = *(src + i);
    }
}

// Exercise 11
int countOccurrences(const int* arr, int size, int target) {
    int count = 0;
    const int* end = arr + size;
    while (arr != end) {
        if (*arr == target) count++;
        arr++;
    }
    return count;
}

// Exercise 12
int myStrlen(const char* str) {
    int len = 0;
    while (*str != '\0') {
        len++;
        str++;
    }
    return len;
}

// Exercise 13
int* findElement(int* arr, int size, int target) {
    for (int i = 0; i < size; i++) {
        if (*(arr + i) == target) {
            return arr + i;
        }
    }
    return nullptr;
}

// Exercise 14
int distance = p2 - p1;

// Exercise 15
void createValue(int** pptr, int value) {
    *pptr = new int(value);
}
*/
Exercises - C++ Tutorial | DeepML