7.
FUNCTIONS
DATE: 7/11/25
L03
AIM:
To understand and implement user-defined functions in C by
writing programs to:
1. Calculate nCr (Combination) using functions.
2. Calculate the factorial of a number using recursion.
THEORY:
1. Functions in C
A function is a reusable block of code that performs a specific task.
Functions improve:
• Code reusability
• Clarity and readability
[Link]
The factorial of a number n (written as n!) is:
n! = n \times (n-1) \times (n-2) \times \ldots \times 1
Example:
5! = 120
3. Recursion
Recursion is a technique where a function calls itself.
A recursive function must have:
• Base condition → stops recursion
• Recursive step → calls itself with smaller value
4. nCr (Combination)
The formula to calculate nCr is:
nCr = n!/{r!(n-r)!}
PROGRAM 1:
nCr USING FUNCTION:
#include <stdio.h>
int factorial(int n) {
int i, fact = 1;
for (i = 1; i <= n; i++) {
fact = fact * i;
}
return fact;
}
int nCr(int n, int r) {
return factorial(n) / (factorial(r) * factorial(n - r));
}
int main() {
int n, r;
printf("Enter value of n: ");
scanf("%d", &n);
printf("Enter value of r: ");
scanf("%d", &r);
if (r > n)
printf("Invalid Input! r cannot be greater than n.\n");
else
printf("nCr = %d\n", nCr(n, r));
return 0;
}
OUTPUT:
PROGRAM 2:
FACTORIAL USING RECURSIVE FUNCTION
#include <stdio.h>
int factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num < 0)
printf("Factorial of negative numbers is not defined.\n");
else
printf("Factorial of %d = %d\n", num, factorial(num));
return 0;
}
OUTPUT:
CONCLUSION:
In this assignment, the concept of functions in C was understood
and applied successfully.
• The first program used functions to calculate nCr, which
also relies on factorial calculations.
• The second program demonstrated recursion by computing
the factorial of a number.