JirR02 950098d35e Exercise 8
Added Exercise 8 to repository
2025-04-21 19:08:07 +02:00
..
2025-04-21 19:08:07 +02:00

Task 1: Reverse Digits

Task

The goal of this task is to implement a program to read a number and print its reverse.

You should complete the implementation of the reverse function in reverse.cpp. This function gets an int as input parameter, and it should print the digits of the number in reverse.

The reverse function must be implemented recursively (without any loop). To enforce this, we disallow the use of for or while.

Input

The input is a single non-negative int number.

An input example:

  321231

Output

For the above input, the output should be:

  132123

Note: You are not allowed to use the string library to solve this task!

Solution

#include "reverse.h"
#include <iostream>

// PRE: n >= 0
// POST: print the digits of the input in reverse order to std::cout
void reverse(int n) {

  int res = n % 10;
  std::cout << res;

  int new_int = n / 10;

  if (new_int == 0) {
    return;
  }

  reverse(new_int);
}

Made by JirR02 in Switzerland 🇨🇭