Printing Individual Digits of an Integer
The following recursive function separates and prints each digit of an unsigned integer.
#include <stdio.h>
void displayDigits(unsigned int num)
{
if (num > 9)
{
displayDigits(num / 10);
}
printf("%u ", num % 10);
}
int main()
{
unsigned int value = 0;
printf("Enter a number to split: ");
scanf("%u", &value);
displayDigits(value);
return 0;
}
Key principles for writing recursive functions include:
- A terminating condition must exist to stop the recursion.
- Each recursive call must progress toward that terminating condition.
Potential issues include stack overflow. To prevent this, avoid infinite recursion, ensure progress toward the base case, and limit recursion depth.
Calculating String Length Without Temporary Variables
The standard iterative method uses a counter variable.
#include <stdio.h>
int computeLengthIterative(char* strPtr)
{
int counter = 0;
while (*strPtr != '\0')
{
counter++;
strPtr++;
}
return counter;
}
int main()
{
char text[] = "hello";
printf("%d\n", computeLengthIterative(text));
return 0;
}
A recursive solution eliminates the need for a local counter variable.
#include <stdio.h>
int computeLengthRecursive(char* strPtr)
{
if (*strPtr != '\0')
{
return 1 + computeLengthRecursive(strPtr + 1);
}
else
{
return 0;
}
}
int main()
{
char text[] = "recursion";
printf("%d\n", computeLengthRecursive(text));
return 0;
}
Computing Factorial Using Recursion
This example calculates n! (n factorial).
#include <stdio.h>
int factorial(int n)
{
if (n > 1)
return factorial(n - 1) * n;
else
return 1;
}
int main()
{
int n = 5;
printf("Factorial of %d is %d\n", n, factorial(n));
return 0;
}
Summing an Alternating Series
This code computes 1/1 - 1/2 + 1/3 - ... up to 1/n.
#include <stdio.h>
void calculateSeries(int terms)
{
int i = 1;
int sign = 1;
double total = 0.0;
for (i = 1; i <= terms; i++)
{
total = total + sign * (1.0 / i);
sign = -sign;
}
printf("Series sum: %lf\n", total);
}
int main()
{
int n = 100;
calculateSeries(n);
return 0;
}
Finding the Maximum Value in an Array
A simple loop identifies the largest integer in an array.
#include <stdio.h>
int main()
{
int numbers[] = { 3, 5, 8, 1, 97, 64, 24, 45, 8, 25 };
int size = sizeof(numbers) / sizeof(numbers[0]);
int maxVal = numbers[0];
int index;
for (index = 1; index < size; index++)
{
if (maxVal < numbers[index])
{
maxVal = numbers[index];
}
}
printf("Maximum value is: %d\n", maxVal);
return 0;
}
Printing a 9x9 Multiplication Table
Nested loops generate a formatted multiplicasion table.
#include <stdio.h>
int main()
{
int row, col, result;
for (row = 1; row < 10; row++)
{
for (col = 1; col <= row; col++)
{
result = row * col;
printf("%d*%d=%2d ", col, row, result);
}
printf("\n");
}
return 0;
}
Reversing a String In-Place
This function reverses the order of characters in a character array.
#include <stdio.h>
void reverseString(char str[])
{
int start = 0;
int end = 0;
char swap;
while (str[end] != '\0')
{
end++;
}
end--;
while (start < end)
{
swap = str[start];
str[start] = str[end];
str[end] = swap;
start++;
end--;
}
}
int main()
{
char message[] = "HelloWorld";
printf("Original: %s\n", message);
reverseString(message);
printf("Reversed: %s\n", message);
return 0;
}
An alternative implementation uses pointer arithmetic.
void reverseStringPtr(char *str)
{
char *begin = str;
char *end = str;
char temp;
while (*end)
end++;
end--;
while (begin < end)
{
temp = *begin;
*begin = *end;
*end = temp;
begin++;
end--;
}
}
A recursive approach for string reversal.
#include <stdio.h>
int strLength(char* s)
{
int len = 0;
while (s[len] != '\0')
len++;
return len;
}
void reverseRecursive(char* s)
{
int len = strLength(s);
char firstChar = s[0];
if (len > 1)
{
s[0] = s[len - 1];
s[len - 1] = '\0';
reverseRecursive(s + 1);
s[len - 1] = firstChar;
}
}
int main()
{
char text[] = "Recursive";
printf("%s\n", text);
reverseRecursive(text);
printf("%s\n", text);
return 0;
}
Summing the Digits of an Integer
A recursive function calculates the sum of an integer's digits.
#include <stdio.h>
int digitSum(int n)
{
if (n > 9)
{
return (n % 10) + digitSum(n / 10);
}
else
{
return n;
}
}
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d", &number);
printf("Sum of digits: %d\n", digitSum(number));
return 0;
}
Computing Integer Exponentiation
This recursive function calculates n raised to the power k (n^k).
#include <stdio.h>
int power(int base, int exponent)
{
if (exponent > 0)
{
return base * power(base, exponent - 1);
}
else
{
return 1;
}
}
int main()
{
int base, exp;
printf("Enter base and exponent: ");
scanf("%d %d", &base, &exp);
printf("%d^%d = %d\n", base, exp, power(base, exp));
return 0;
}
An extended vertion handles negative exponents.
#include <stdio.h>
double powerExtended(int base, int exponent)
{
if (exponent > 0)
{
return base * powerExtended(base, exponent - 1);
}
else if (exponent == 0)
{
return 1.0;
}
else
{
return 1.0 / powerExtended(base, -exponent);
}
}
int main()
{
int base, exp;
printf("Enter base and exponent: ");
scanf("%d %d", &base, &exp);
printf("%d^%d = %lf\n", base, exp, powerExtended(base, exp));
return 0;
}