c
exercises
exercises.c🔧c
/**
* @file exercises.c
* @brief Recursion Exercises
*
* Practice recursive functions in C.
*
* Compile: gcc -Wall exercises.c -o exercises
* Run: ./exercises
*/
#include <stdio.h>
#include <string.h>
/* ============================================================
* EXERCISE 1: SUM OF FIRST N NATURAL NUMBERS
* ============================================================
* Difficulty: Easy
*
* Task: Write a recursive function to sum 1 + 2 + ... + n
*/
int sumN(int n) {
// TODO: Return sum of 1 to n recursively
// Your code here
return 0; // Replace this
}
void exercise_1() {
printf("\n=== Exercise 1: Sum of First N ===\n");
printf("sum(5) = %d (should be 15)\n", sumN(5));
printf("sum(10) = %d (should be 55)\n", sumN(10));
printf("sum(100) = %d (should be 5050)\n", sumN(100));
}
/* ============================================================
* EXERCISE 2: COUNT DIGITS
* ============================================================
* Difficulty: Easy
*
* Task: Count number of digits in a number recursively.
*/
int countDigits(int n) {
// TODO: Return number of digits
// Your code here
return 0; // Replace this
}
void exercise_2() {
printf("\n=== Exercise 2: Count Digits ===\n");
printf("digits(12345) = %d (should be 5)\n", countDigits(12345));
printf("digits(7) = %d (should be 1)\n", countDigits(7));
printf("digits(1000000) = %d (should be 7)\n", countDigits(1000000));
}
/* ============================================================
* EXERCISE 3: REVERSE NUMBER
* ============================================================
* Difficulty: Medium
*
* Task: Reverse a number recursively.
* Hint: Use a helper function with accumulator.
*/
int reverseHelper(int n, int rev);
int reverseNumber(int n) {
// TODO: Return reversed number
// Your code here
return 0; // Replace this
}
void exercise_3() {
printf("\n=== Exercise 3: Reverse Number ===\n");
printf("reverse(12345) = %d (should be 54321)\n", reverseNumber(12345));
printf("reverse(100) = %d (should be 1)\n", reverseNumber(100));
}
/* ============================================================
* EXERCISE 4: ARRAY MAXIMUM
* ============================================================
* Difficulty: Easy
*
* Task: Find maximum element in array recursively.
*/
int arrayMax(int arr[], int size) {
// TODO: Return maximum element
// Your code here
return 0; // Replace this
}
void exercise_4() {
printf("\n=== Exercise 4: Array Maximum ===\n");
int arr[] = {3, 7, 2, 9, 5, 1};
printf("max = %d (should be 9)\n", arrayMax(arr, 6));
}
/* ============================================================
* EXERCISE 5: PRODUCT OF ARRAY
* ============================================================
* Difficulty: Easy
*
* Task: Calculate product of all elements recursively.
*/
int productArray(int arr[], int size) {
// TODO: Return product of all elements
// Your code here
return 0; // Replace this
}
void exercise_5() {
printf("\n=== Exercise 5: Product of Array ===\n");
int arr[] = {1, 2, 3, 4, 5};
printf("product = %d (should be 120)\n", productArray(arr, 5));
}
/* ============================================================
* EXERCISE 6: STRING LENGTH
* ============================================================
* Difficulty: Easy
*
* Task: Calculate string length recursively (no strlen).
*/
int strLenRecursive(char str[]) {
// TODO: Return length of string
// Your code here
return 0; // Replace this
}
void exercise_6() {
printf("\n=== Exercise 6: String Length ===\n");
printf("len('Hello') = %d (should be 5)\n", strLenRecursive("Hello"));
printf("len('') = %d (should be 0)\n", strLenRecursive(""));
printf("len('Recursion') = %d (should be 9)\n", strLenRecursive("Recursion"));
}
/* ============================================================
* EXERCISE 7: CHECK IF SORTED
* ============================================================
* Difficulty: Medium
*
* Task: Check if array is sorted in ascending order.
*/
int isSorted(int arr[], int size) {
// TODO: Return 1 if sorted ascending, 0 otherwise
// Your code here
return 0; // Replace this
}
void exercise_7() {
printf("\n=== Exercise 7: Check if Sorted ===\n");
int sorted[] = {1, 2, 3, 4, 5};
int unsorted[] = {1, 3, 2, 4, 5};
printf("isSorted({1,2,3,4,5}) = %d (should be 1)\n", isSorted(sorted, 5));
printf("isSorted({1,3,2,4,5}) = %d (should be 0)\n", isSorted(unsorted, 5));
}
/* ============================================================
* EXERCISE 8: COUNT OCCURRENCES
* ============================================================
* Difficulty: Medium
*
* Task: Count occurrences of target in array.
*/
int countOccurrences(int arr[], int size, int target) {
// TODO: Return count of target in array
// Your code here
return 0; // Replace this
}
void exercise_8() {
printf("\n=== Exercise 8: Count Occurrences ===\n");
int arr[] = {1, 2, 3, 2, 4, 2, 5};
printf("count(2) = %d (should be 3)\n", countOccurrences(arr, 7, 2));
printf("count(6) = %d (should be 0)\n", countOccurrences(arr, 7, 6));
}
/* ============================================================
* EXERCISE 9: NTH POWER OF 2
* ============================================================
* Difficulty: Easy
*
* Task: Calculate 2^n recursively.
*/
int powerOf2(int n) {
// TODO: Return 2^n
// Your code here
return 0; // Replace this
}
void exercise_9() {
printf("\n=== Exercise 9: Power of 2 ===\n");
printf("2^0 = %d (should be 1)\n", powerOf2(0));
printf("2^5 = %d (should be 32)\n", powerOf2(5));
printf("2^10 = %d (should be 1024)\n", powerOf2(10));
}
/* ============================================================
* EXERCISE 10: LCM USING GCD
* ============================================================
* Difficulty: Medium
*
* Task: Calculate LCM using recursive GCD.
*/
int gcdRecursive(int a, int b) {
// TODO: Implement GCD first
// Your code here
return 0; // Replace
}
int lcmRecursive(int a, int b) {
// TODO: Return LCM using formula: LCM = (a*b) / GCD(a,b)
// Your code here
return 0; // Replace this
}
void exercise_10() {
printf("\n=== Exercise 10: LCM ===\n");
printf("LCM(4, 6) = %d (should be 12)\n", lcmRecursive(4, 6));
printf("LCM(15, 20) = %d (should be 60)\n", lcmRecursive(15, 20));
}
/* ============================================================
* EXERCISE 11: MULTIPLY WITHOUT * OPERATOR
* ============================================================
* Difficulty: Medium
*
* Task: Multiply two numbers using only addition.
*/
int multiply(int a, int b) {
// TODO: Return a * b using only + recursively
// Your code here
return 0; // Replace this
}
void exercise_11() {
printf("\n=== Exercise 11: Multiply without * ===\n");
printf("5 * 4 = %d (should be 20)\n", multiply(5, 4));
printf("7 * 3 = %d (should be 21)\n", multiply(7, 3));
printf("0 * 5 = %d (should be 0)\n", multiply(0, 5));
}
/* ============================================================
* EXERCISE 12: PRINT ARRAY REVERSE
* ============================================================
* Difficulty: Easy
*
* Task: Print array elements in reverse order.
*/
void printArrayReverse(int arr[], int size) {
// TODO: Print array in reverse
// Your code here
}
void exercise_12() {
printf("\n=== Exercise 12: Print Array Reverse ===\n");
int arr[] = {1, 2, 3, 4, 5};
printf("Reverse: ");
printArrayReverse(arr, 5);
printf("\n(should be 5 4 3 2 1)\n");
}
/* ============================================================
* EXERCISE 13: IS POWER OF TWO
* ============================================================
* Difficulty: Medium
*
* Task: Check if n is a power of 2.
*/
int isPowerOfTwo(int n) {
// TODO: Return 1 if n is power of 2, 0 otherwise
// Your code here
return 0; // Replace this
}
void exercise_13() {
printf("\n=== Exercise 13: Is Power of Two ===\n");
printf("isPowerOfTwo(16) = %d (should be 1)\n", isPowerOfTwo(16));
printf("isPowerOfTwo(15) = %d (should be 0)\n", isPowerOfTwo(15));
printf("isPowerOfTwo(1) = %d (should be 1)\n", isPowerOfTwo(1));
}
/* ============================================================
* EXERCISE 14: SUM OF EVEN NUMBERS IN ARRAY
* ============================================================
* Difficulty: Medium
*
* Task: Sum only even numbers in array.
*/
int sumEven(int arr[], int size) {
// TODO: Return sum of even numbers only
// Your code here
return 0; // Replace this
}
void exercise_14() {
printf("\n=== Exercise 14: Sum of Even Numbers ===\n");
int arr[] = {1, 2, 3, 4, 5, 6};
printf("sumEven = %d (should be 12)\n", sumEven(arr, 6));
}
/* ============================================================
* EXERCISE 15: DECIMAL TO BINARY STRING
* ============================================================
* Difficulty: Hard
*
* Task: Fill a string with binary representation.
*/
void toBinaryHelper(int n, char result[], int index);
void toBinary(int n, char result[]) {
// TODO: Fill result with binary representation
// Your code here
result[0] = '\0'; // Default empty
}
void exercise_15() {
printf("\n=== Exercise 15: Decimal to Binary ===\n");
char binary[33];
toBinary(10, binary);
printf("10 in binary: %s (should be 1010)\n", binary);
toBinary(255, binary);
printf("255 in binary: %s (should be 11111111)\n", binary);
}
/* ============================================================
* MAIN FUNCTION
* ============================================================ */
int main() {
printf("╔════════════════════════════════════════════════╗\n");
printf("║ RECURSION - EXERCISES ║\n");
printf("║ Practice recursive functions ║\n");
printf("╚════════════════════════════════════════════════╝\n");
// Uncomment exercises as you complete them:
// exercise_1();
// exercise_2();
// exercise_3();
// exercise_4();
// exercise_5();
// exercise_6();
// exercise_7();
// exercise_8();
// exercise_9();
// exercise_10();
// exercise_11();
// exercise_12();
// exercise_13();
// exercise_14();
// exercise_15();
printf("\n=== Uncomment exercises in main() to run them ===\n");
return 0;
}
/* ============================================================
* ANSWER KEY
* ============================================================
*
* EXERCISE 1:
* int sumN(int n) {
* if (n <= 0) return 0;
* return n + sumN(n - 1);
* }
*
* EXERCISE 2:
* int countDigits(int n) {
* if (n < 0) n = -n;
* if (n < 10) return 1;
* return 1 + countDigits(n / 10);
* }
*
* EXERCISE 3:
* int reverseHelper(int n, int rev) {
* if (n == 0) return rev;
* return reverseHelper(n / 10, rev * 10 + n % 10);
* }
* int reverseNumber(int n) {
* return reverseHelper(n, 0);
* }
*
* EXERCISE 4:
* int arrayMax(int arr[], int size) {
* if (size == 1) return arr[0];
* int maxRest = arrayMax(arr, size - 1);
* return (arr[size - 1] > maxRest) ? arr[size - 1] : maxRest;
* }
*
* EXERCISE 5:
* int productArray(int arr[], int size) {
* if (size <= 0) return 1;
* return arr[size - 1] * productArray(arr, size - 1);
* }
*
* EXERCISE 6:
* int strLenRecursive(char str[]) {
* if (str[0] == '\0') return 0;
* return 1 + strLenRecursive(str + 1);
* }
*
* EXERCISE 7:
* int isSorted(int arr[], int size) {
* if (size <= 1) return 1;
* if (arr[size - 2] > arr[size - 1]) return 0;
* return isSorted(arr, size - 1);
* }
*
* EXERCISE 8:
* int countOccurrences(int arr[], int size, int target) {
* if (size <= 0) return 0;
* int count = (arr[size - 1] == target) ? 1 : 0;
* return count + countOccurrences(arr, size - 1, target);
* }
*
* EXERCISE 9:
* int powerOf2(int n) {
* if (n == 0) return 1;
* return 2 * powerOf2(n - 1);
* }
*
* EXERCISE 10:
* int gcdRecursive(int a, int b) {
* if (b == 0) return a;
* return gcdRecursive(b, a % b);
* }
* int lcmRecursive(int a, int b) {
* return (a / gcdRecursive(a, b)) * b;
* }
*
* EXERCISE 11:
* int multiply(int a, int b) {
* if (b == 0) return 0;
* if (b < 0) return -multiply(a, -b);
* return a + multiply(a, b - 1);
* }
*
* EXERCISE 12:
* void printArrayReverse(int arr[], int size) {
* if (size <= 0) return;
* printf("%d ", arr[size - 1]);
* printArrayReverse(arr, size - 1);
* }
*
* EXERCISE 13:
* int isPowerOfTwo(int n) {
* if (n <= 0) return 0;
* if (n == 1) return 1;
* if (n % 2 != 0) return 0;
* return isPowerOfTwo(n / 2);
* }
*
* EXERCISE 14:
* int sumEven(int arr[], int size) {
* if (size <= 0) return 0;
* int add = (arr[size - 1] % 2 == 0) ? arr[size - 1] : 0;
* return add + sumEven(arr, size - 1);
* }
*
* EXERCISE 15:
* void toBinaryHelper(int n, char result[], int *index) {
* if (n == 0) return;
* toBinaryHelper(n / 2, result, index);
* result[(*index)++] = (n % 2) + '0';
* result[*index] = '\0';
* }
* void toBinary(int n, char result[]) {
* if (n == 0) { result[0] = '0'; result[1] = '\0'; return; }
* int index = 0;
* toBinaryHelper(n, result, &index);
* }
*
* ============================================================
*/