Exercise: Reverse a Number
Write a program that takes an integer and reverses its digits. For example, 12345 becomes 54321.
#include <iostream>
int reverseNumber(int n) {
int rev = 0;
while (n > 0) {
rev = rev * 10 + n % 10;
n /= 10;
}
return rev;
}
int main() {
int num = 12345;
std::cout << reverseNumber(num);
return 0;
}
Try it Yourself →
Exercise: Find Maximum
Write a program that finds the largest element in an array.
#include <iostream>
int findMax(int arr[], int n) {
int max = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > max) max = arr[i];
}
return max;
}
int main() {
int nums[] = {12, 45, 7, 89, 23};
int n = sizeof(nums) / sizeof(nums[0]);
std::cout << "Max: " << findMax(nums, n);
return 0;
}
Try it Yourself →
Exercise: Factorial
Write a program that calculates the factorial of a given number using recursion.
#include <iostream>
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
int main() {
int n = 6;
std::cout << n << "! = " << factorial(n);
return 0;
}
Try it Yourself →