Generating PDF…

Preparing…
← Back

C++ Practice Session

Microcontrollers 2 — Week 1

10 exercises · Easy → Hard · Work at your own pace

How to Use This Session

For each exercise, you'll see starter code in an editable text box. Write your solution, then compile and run it in your preferred environment:

  • Option 1: Replit — Go to replit.com, create a new C++ Repl, paste your code, and hit Run
  • Option 2: VS Code — Save as .cpp, compile with g++ -o prog file.cpp, run with ./prog
  • Option 3: Arduino IDE — For the last exercise, use Arduino IDE with your Uno board

Each exercise has a Show Solution button — try solving it yourself first!

💡 Tip: Start from the top. Each exercise builds on concepts from the previous ones.

Exercise 1: Hello World

Easy

Task: Write a program that prints "Hello, Microcontrollers 2!" followed by a new line, then prints "Let's review C++!"

Expected output:
Hello, Microcontrollers 2!
Let's review C++!

#include <iostream>
using namespace std;

int main() {
    cout << "Hello, Microcontrollers 2!" << endl;
    cout << "Let's review C++!" << endl;
    return 0;
}

Exercise 2: Variables & Arithmetic

Easy

Task: Declare two integer variables a = 15 and b = 4. Print their sum, difference, product, integer division result, and remainder (modulo).

Expected output:
Sum: 19 · Diff: 11 · Product: 60 · Division: 3 · Remainder: 3

#include <iostream>
using namespace std;

int main() {
    int a = 15;
    int b = 4;

    cout << "Sum: " << (a + b) << endl;
    cout << "Diff: " << (a - b) << endl;
    cout << "Product: " << (a * b) << endl;
    cout << "Division: " << (a / b) << endl;
    cout << "Remainder: " << (a % b) << endl;

    return 0;
}

Exercise 3: If / Else

Easy

Task: Ask the user for an integer. Print whether the number is positive, negative, or zero.

Example: Input -7 → Output: The number is negative

#include <iostream>
using namespace std;

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;

    if (num > 0) {
        cout << "The number is positive" << endl;
    } else if (num < 0) {
        cout << "The number is negative" << endl;
    } else {
        cout << "The number is zero" << endl;
    }

    return 0;
}

Exercise 4: For Loop — Multiplication Table

Easy

Task: Ask the user for a number, then print its multiplication table from 1 to 10.

Example: Input 5 → Output: 5 x 1 = 5, 5 x 2 = 10, ... 5 x 10 = 50

#include <iostream>
using namespace std;

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;

    for (int i = 1; i <= 10; i++) {
        cout << num << " x " << i << " = " << (num * i) << endl;
    }

    return 0;
}

Exercise 5: While Loop — Countdown

Medium

Task: Ask the user for a starting number N. Count down from N to 1, printing each number. After the countdown, print "Launch!". If N is negative or zero, print "Invalid countdown".

Example: Input 3 → Output: 3, 2, 1, Launch!

#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "Enter countdown start: ";
    cin >> n;

    if (n <= 0) {
        cout << "Invalid countdown" << endl;
    } else {
        while (n > 0) {
            cout << n << endl;
            n--;
        }
        cout << "Launch!" << endl;
    }

    return 0;
}

Exercise 6: Functions — Prime Checker

Medium

Task: Write a function bool isPrime(int n) that returns true if n is a prime number, false otherwise. Test it by checking numbers 1 through 20.

Expected primes: 2, 3, 5, 7, 11, 13, 17, 19

#include <iostream>
using namespace std;

bool isPrime(int n) {
    if (n < 2) return false;
    for (int i = 2; i <= n / 2; i++) {
        if (n % i == 0) return false;
    }
    return true;
}

int main() {
    cout << "Primes from 1 to 20: ";
    for (int i = 1; i <= 20; i++) {
        if (isPrime(i)) {
            cout << i << " ";
        }
    }
    cout << endl;
    return 0;
}

Exercise 7: Arrays — Find the Maximum

Medium

Task: Given an array of 10 integers, write a function int findMax(int arr[], int size) that returns the largest value. Also find and print the index of the maximum value.

#include <iostream>
using namespace std;

int findMax(int arr[], int size) {
    int maxVal = arr[0];
    for (int i = 1; i < size; i++) {
        if (arr[i] > maxVal) {
            maxVal = arr[i];
        }
    }
    return maxVal;
}

int main() {
    int data[] = {23, 7, 45, 12, 89, 34, 56, 3, 67, 41};
    int size = 10;

    int maxVal = findMax(data, size);
    cout << "Maximum value: " << maxVal << endl;

    // Find index of max
    for (int i = 0; i < size; i++) {
        if (data[i] == maxVal) {
            cout << "Found at index: " << i << endl;
            break;
        }
    }
    return 0;
}
// Output: Maximum value: 89
//         Found at index: 4

Exercise 8: Pointers — Swap Function

Hard

Task: Write a function void swap(int* a, int* b) that swaps the values of two integers using pointers. Print the values before and after swapping to verify it works.

Key concept: passing by pointer allows the function to modify variables in the caller's scope.

#include <iostream>
using namespace std;

void swap(int* a, int* b) {
    int temp = *a;  // Store value at address a
    *a = *b;        // Put value at b into a
    *b = temp;      // Put stored value into b
}

int main() {
    int x = 10, y = 20;
    cout << "Before: x=" << x << ", y=" << y << endl;

    swap(&x, &y);  // Pass addresses

    cout << "After:  x=" << x << ", y=" << y << endl;
    return 0;
}
// Output:
// Before: x=10, y=20
// After:  x=20, y=10

Exercise 9: Classes — Sensor Object

Hard

Task: Create a Sensor class with:

  • Private members: string name, float value, float minVal, float maxVal
  • Constructor: takes name, min and max; sets value to 0
  • Method: void read(float v) — sets value, but clamps to [min, max]
  • Method: void display() — prints name and current value
#include <iostream>
#include <string>
using namespace std;

class Sensor {
private:
    string name;
    float value;
    float minVal;
    float maxVal;

public:
    Sensor(string n, float mn, float mx)
        : name(n), value(0), minVal(mn), maxVal(mx) {}

    void read(float v) {
        if (v < minVal) value = minVal;
        else if (v > maxVal) value = maxVal;
        else value = v;
    }

    void display() {
        cout << name << ": " << value << endl;
    }
};

int main() {
    Sensor temp("Temperature", 0.0, 100.0);
    temp.read(25.5);
    temp.display();  // Temperature: 25.5

    temp.read(150.0);
    temp.display();  // Temperature: 100 (clamped)

    temp.read(-10.0);
    temp.display();  // Temperature: 0 (clamped)
    return 0;
}

Exercise 10: Arduino — Non-blocking Blink

Hard

Task: Write an Arduino sketch that blinks two LEDs at different rates without using delay(). LED on pin 13 blinks every 500ms, LED on pin 12 blinks every 1200ms. Also read a button on pin 2 and print "Pressed" to Serial when pushed.

Use this in Arduino IDE with your Uno board — or just write the code here and verify the logic.

const int LED1 = 13;
const int LED2 = 12;
const int BTN  = 2;

unsigned long prevMs1 = 0, prevMs2 = 0;
bool state1 = false, state2 = false;

void setup() {
    pinMode(LED1, OUTPUT);
    pinMode(LED2, OUTPUT);
    pinMode(BTN, INPUT_PULLUP);
    Serial.begin(9600);
}

void loop() {
    unsigned long now = millis();

    // Task 1: Blink LED1 every 500ms
    if (now - prevMs1 >= 500) {
        prevMs1 = now;
        state1 = !state1;
        digitalWrite(LED1, state1);
    }

    // Task 2: Blink LED2 every 1200ms
    if (now - prevMs2 >= 1200) {
        prevMs2 = now;
        state2 = !state2;
        digitalWrite(LED2, state2);
    }

    // Task 3: Check button (non-blocking)
    if (digitalRead(BTN) == LOW) {
        Serial.println("Pressed");
        delay(200); // simple debounce
    }
}