C++ Recursive Function Examples: Counting, Summation, Power

Classified in Computers

Written on in English with a size of 3.18 KB

C++ Recursive Function Examples

countUp — Print Increasing Numbers

#include <iostream>
using namespace std;

void countUp(int n) {
    if (n == 0) return;
    countUp(n - 1);
    cout << n << " ";
}

int main() {
    int n;
    cout << "Enter a positive integer: ";
    cin >> n;
    countUp(n);
    return 0;
}

summation — Sum of 1 to n

#include <iostream>
using namespace std;

int summation(int n) {
    if (n == 0) return 0;
    return n + summation(n - 1);
}

int main() {
    int n;
    cout << "Enter a positive integer: ";
    cin >> n;
    cout << summation(n);
    return 0;
}

power — Exponentiation (Recursive)

#include <iostream>
using namespace std;

int power(int n, int e) {
    if (e == 0) return 1;
    return n * power(n, e - 1);
}

int main() {
    int n, e;
    cout << "Enter a positive integer and exponent: ";
    cin >> n >> e;
    cout << power(n, e);
    return 0;
}

printReverse — Reverse a String

#include <iostream>
#include <string>
using namespace std;

void printReverse(string str, int i = 0) {
    if (i == str.length()) return;
    printReverse(str, i + 1);
    cout << str[i];
}

int main() {
    string s;
    cout << "Enter a string: ";
    cin >> s;
    printReverse(s);
    return 0;
}

sumDigits — Sum of All Digits

#include <iostream>
using namespace std;

int sumDigits(int n) {
    if (n == 0) return 0;
    return n % 10 + sumDigits(n / 10);
}

int main() {
    int n;
    cout << "Enter a positive integer: ";
    cin >> n;
    cout << sumDigits(n);
    return 0;
}

interleave — Interleave Two Numbers

#include <iostream>
using namespace std;

int interleave(int n1, int n2) {
    if (n1 == 0 && n2 == 0) return 0;

    int last1 = n1 % 10;
    int last2 = n2 % 10;
    return interleave(n1 / 10, n2 / 10) * 100 + last1 * 10 + last2;
}

int main() {
    int n1, n2;
    cout << "Enter two positive integers: ";
    cin >> n1 >> n2;
    cout << interleave(n1, n2);
    return 0;
}

palindrome — Check If String Is Palindrome

#include <iostream>
#include <string>
using namespace std;

bool palindrome(string s, int start, int end) {
    if (start >= end) return true;
    if (s[start] != s[end]) return false;
    return palindrome(s, start + 1, end - 1);
}

int main() {
    string s;
    cout << "Enter a string: ";
    cin >> s;
    cout << palindrome(s, 0, s.length() - 1);
    return 0;
}

hasDigit — Check for a Digit in a Number

#include <iostream>
using namespace std;

bool hasDigit(int number, int digit) {
    if (number == 0) return false;
    if (number % 10 == digit) return true;
    return hasDigit(number / 10, digit);
}

int main() {
    int number, digit;
    cout << "Enter a number and a digit: ";
    cin >> number >> digit;
    cout << hasDigit(number, digit);
    return 0;
}

Related entries: