Beginner C/C++ Exercises

Reverse a String

String reversal is useful practice for indexing and in-place swaps.

What is Reverse a String?

String reversal is useful practice for indexing and in-place swaps.

Reverse text without changing its characters.

Important points

  • Compile with warnings enabled and fix every warning.
  • Know the lifetime and type of every value.
  • Validate input and keep array bounds explicit.

C and C++ code examples

C
Run code →
main.c
#include <stdio.h>
#include <string.h>
int main(void) {
    char text[] = "CodeUtility"; size_t length = strlen(text);
    // Swap mirrored characters in place.
    for (size_t i = 0; i < length / 2; ++i) {
        char temporary = text[i]; text[i] = text[length - 1 - i]; text[length - 1 - i] = temporary;
    }
    puts(text);
}
Expected output
ytilitUedoC
C++
Run code →
main.cpp
#include <algorithm>
#include <iostream>
#include <string>
int main() {
    std::string text = "CodeUtility";
    // reverse applies swaps across the selected range.
    std::reverse(text.begin(), text.end());
    std::cout << text << '\n';
}
Expected output
ytilitUedoC

C and C++ comparison

Swap mirrored characters until the two indexes meet in the center.

C

C exposes small procedural APIs and makes representation details explicit.

C++

C++ retains the low-level model while adding safer library types and abstractions.

Practice exercises

Run both versions, then modify them to observe the different language guarantees.

  • Add invalid and boundary-value inputs.
  • Compile with -Wall -Wextra -Wpedantic.
  • Move reusable declarations into a header and implementation file.