Learning Objectives
- Understand the concept of functions and their importance in modular programming
- Learn to write both recursive and non-recursive functions
- Implement mathematical functions using recursion
- Develop problem-solving skills through function implementation
- Understand function parameters, return values, and function calls
Problem 1: Factorial and Binomial Coefficient
Theory
Factorial: The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.
Formula:
- FACT(n) = 1, if n = 0
- FACT(n) = n × FACT(n-1), if n > 0
Binomial Coefficient: The binomial coefficient C(n, r) or nCr represents the number of ways to choose r items from n items.
Formula: C(n, r) = n! / (r! × (n-r)!)
Algorithm (Recursive)
- Start
- If n == 0, return 1
- Else return n × FACT(n-1)
- End
C Program
// Program to calculate factorial and binomial coefficient #include <stdio.h> // Recursive function to calculate factorial long long fact_recursive(int n) { if (n == 0 || n == 1) return 1; else return n * fact_recursive(n - 1); } // Non-recursive function to calculate factorial long long fact_non_recursive(int n) { long long result = 1; for (int i = 2; i <= n; i++) { result *= i; } return result; } // Function to calculate binomial coefficient long long binomial_coefficient(int n, int r) { if (r > n) return 0; return fact_recursive(n) / (fact_recursive(r) * fact_recursive(n - r)); } int main() { int num; printf("Factorial Comparison (Recursive vs Non-Recursive)\n"); printf("================================================\n"); printf("Enter a number: "); scanf("%d", &num); printf("\nFactorial of %d (Recursive): %lld\n", num, fact_recursive(num)); printf("Factorial of %d (Non-Recursive): %lld\n", num, fact_non_recursive(num)); printf("\n\nBinomial Coefficient Table\n"); printf("==========================\n"); printf(" n\t r\t C(n,r)\n"); printf("==========================\n"); int test_cases[][2] = {{5,2}, {6,3}, {8,4}, {10,5}, {7,0}}; for (int i = 0; i < 5; i++) { int n = test_cases[i][0]; int r = test_cases[i][1]; printf(" %d\t %d\t %lld\n", n, r, binomial_coefficient(n, r)); } return 0; }
Factorial Comparison (Recursive vs Non-Recursive)
================================================
Enter a number: 5
Factorial of 5 (Recursive): 120
Factorial of 5 (Non-Recursive): 120
Binomial Coefficient Table
==========================
n r C(n,r)
==========================
5 2 10
6 3 20
8 4 70
10 5 252
7 0 1
Problem 2: Greatest Common Divisor (GCD)
Theory
GCD (Greatest Common Divisor): The largest positive integer that divides both numbers without a remainder.
Euclidean Algorithm:
- GCD(a, 0) = a
- GCD(a, b) = GCD(b, a % b)
Algorithm
- Start
- If num2 == 0, return num1
- Else return GCD(num2, num1 % num2)
- End
C Program
// Program to find GCD using recursion #include <stdio.h> // Recursive function to calculate GCD int GCD(int num1, int num2) { if (num2 == 0) return num1; else return GCD(num2, num1 % num2); } int main() { int num1, num2; printf("GCD Calculator (Euclidean Algorithm)\n"); printf("=====================================\n"); printf("Enter first number: "); scanf("%d", &num1); printf("Enter second number: "); scanf("%d", &num2); int result = GCD(num1, num2); printf("\nGCD of %d and %d is: %d\n", num1, num2, result); // Display additional examples printf("\n\nAdditional Examples:\n"); printf("====================\n"); printf("GCD(48, 18) = %d\n", GCD(48, 18)); printf("GCD(100, 50) = %d\n", GCD(100, 50)); printf("GCD(35, 14) = %d\n", GCD(35, 14)); printf("GCD(270, 192) = %d\n", GCD(270, 192)); return 0; }
GCD Calculator (Euclidean Algorithm)
=====================================
Enter first number: 56
Enter second number: 98
GCD of 56 and 98 is: 14
Additional Examples:
====================
GCD(48, 18) = 6
GCD(100, 50) = 50
GCD(35, 14) = 7
GCD(270, 192) = 6
Problem 3: Fibonacci Sequence
Theory
Fibonacci Sequence: A series of numbers where each number is the sum of the two preceding ones.
Formula:
- FIBO(0) = 0
- FIBO(1) = 1
- FIBO(n) = FIBO(n-1) + FIBO(n-2), for n > 1
Sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
Algorithm
- Start
- If n == 0, return 0
- If n == 1, return 1
- Else return FIBO(n-1) + FIBO(n-2)
- End
C Program
// Program to generate Fibonacci sequence #include <stdio.h> // Recursive function to calculate Fibonacci number int FIBO(int num) { if (num == 0) return 0; else if (num == 1) return 1; else return FIBO(num - 1) + FIBO(num - 2); } int main() { int num; printf("Fibonacci Sequence Generator\n"); printf("=============================\n"); printf("Enter the number of terms: "); scanf("%d", &num); printf("\nFibonacci Sequence up to %d terms:\n", num); printf("===================================\n"); for (int i = 0; i < num; i++) { printf("%d ", FIBO(i)); if ((i + 1) % 10 == 0) // New line after every 10 numbers printf("\n"); } printf("\n\nPosition-wise Fibonacci Numbers:\n"); printf("=================================\n"); printf("Position\tFibonacci Number\n"); printf("=================================\n"); for (int i = 0; i < num && i < 15; i++) { printf(" %2d\t\t %d\n", i, FIBO(i)); } return 0; }
Fibonacci Sequence Generator
=============================
Enter the number of terms: 12
Fibonacci Sequence up to 12 terms:
===================================
0 1 1 2 3 5 8 13 21 34 55 89
Position-wise Fibonacci Numbers:
=================================
Position Fibonacci Number
=================================
0 0
1 1
2 1
3 2
4 3
5 5
Problem 4: Prime Number Generator
Theory
Prime Number: A natural number greater than 1 that has no positive divisors other than 1 and itself.
Examples: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ...
Method: Check if the number is divisible by any number from 2 to √n.
Algorithm
- Start
- If num <= 1, return 0 (not prime)
- If num == 2, return 1 (prime)
- For i = 2 to √num
- If num % i == 0, return 0
- Return 1 (prime)
- End
C Program
// Program to generate prime numbers in a range #include <stdio.h> #include <math.h> // Function to check if a number is prime int ISPRIME(int num) { if (num <= 1) return 0; // Not prime if (num == 2) return 1; // Prime if (num % 2 == 0) return 0; // Not prime (even number) // Check odd divisors up to sqrt(num) for (int i = 3; i <= sqrt(num); i += 2) { if (num % i == 0) return 0; // Not prime } return 1; // Prime } int main() { int start, end, count = 0; printf("Prime Number Generator\n"); printf("======================\n"); printf("Enter start of range: "); scanf("%d", &start); printf("Enter end of range: "); scanf("%d", &end); printf("\nPrime numbers between %d and %d:\n", start, end); printf("====================================\n"); for (int i = start; i <= end; i++) { if (ISPRIME(i)) { printf("%d\t", i); count++; // Print 10 numbers per line if (count % 10 == 0) { printf("\n"); } } } printf("\n\nTotal prime numbers found: %d\n", count); return 0; }
Prime Number Generator
======================
Enter start of range: 10
Enter end of range: 50
Prime numbers between 10 and 50:
====================================
11 13 17 19 23 29 31 37 41 43
47
Total prime numbers found: 11
6. String Reversal using Functions
In this section, we'll create a function to reverse a string. The function REVERSE will accept a string as an argument and return the reversed string.
C Program
// Program to reverse a string using a function #include <stdio.h> #include <string.h> // Function to reverse a string void REVERSE(char str[]) { int length = strlen(str); int start = 0; int end = length - 1; while (start < end) { // Swap characters at start and end char temp = str[start]; str[start] = str[end]; str[end] = temp; // Move towards the center start++; end--; } } int main() { char str[100]; printf("String Reversal Program\n"); printf("========================\n"); printf("Enter a string: "); fgets(str, sizeof(str), stdin); // Remove the newline character from fgets str[strcspn(str, "\n")] = '\0'; printf("\nOriginal string: %s\n", str); // Call the REVERSE function REVERSE(str); printf("Reversed string: %s\n", str); return 0; }
String Reversal Program
========================
Enter a string: Hello, World!
Original string: Hello, World!
Reversed string: !dlroW ,olleH
Explanation:
- The program defines a function
REVERSEthat takes a character array (string) as an argument. - It uses a two-pointer approach to reverse the string in-place.
- The
mainfunction reads a string from the user, calls theREVERSEfunction, and displays the result. - The function modifies the original string directly since arrays are passed by reference in C.
Conclusion
This experiment demonstrated various aspects of functions in C programming, including function declaration, definition, and calling. We explored different types of functions through practical examples such as calculating factorials (both recursively and iteratively), finding the GCD of two numbers, generating Fibonacci series, and identifying prime numbers within a range.
Key concepts covered include:
- Function declaration and definition
- Function parameters and return types
- Recursive vs. iterative approaches
- Mathematical functions and algorithms
- Input/output operations within functions
These examples provide a solid foundation for understanding how to create and use functions effectively in C programming.
Exercises
- Modify the factorial program to handle larger numbers using a different data type. What's the largest factorial you can calculate?
- Enhance the GCD program to handle more than two numbers.
- Optimize the prime number generator to be more efficient for large ranges.
- Create a function to check if a number is an Armstrong number.
- Write a recursive function to calculate the sum of digits of a number.