Spl lab 3
Spl lab 3
A. Description:
The problem is to calculate the factorial of a given number using recursion in C.
Factorial of a number (n) is the product of all positive integers less than or equal to
n. The recursive approach involves the function calling itself with a smaller value
until it reaches the base case (n = 1).
Steps:
• Take an integer input from the user using the scanf function.
• Create a function factorial() that calls itself recursively with (n-1) until n
equals 1.
3. Base Case:
• If n == 1, return 1.
• Call the factorial() function with the given input and print the result.
B. Source Code:
#include <stdio.h>
int factorial(int n) {
if (n == 1)
return 1;
return n * factorial(n - 1);
}
int main() {
666-63-65 2
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num < 1)
printf("Factorial is not defined for negative numbers or zero.\n");
else
printf("Factorial of %d is %d\n", num, factorial(num));
return 0;
}
C. Program Input/Output:
A. Description:
The goal is to determine if a number is prime. A prime number is greater than 1 and
divisible only by 1 and itself.
Steps:
666-63-65 3
B. Source Code:
#include <stdio.h>
#include <math.h>
int isPrime(int num)
{
if (num <= 1)
return 0;
for (int i = 2; i <= sqrt(num); i++)
{
if (num % i == 0)
return 0;
}
return 1;
}
int main()
{
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (isPrime(num))
printf("%d is a prime number.\n", num);
else
printf("%d is not a prime number.\n", num);
return 0;
}
C. Program input/output:
666-63-65 4
Program 3: Find the Sum of Natural Numbers (Upto n).
A. Description:
The task is to find the sum of natural numbers up to n using recursion. The sum of
natural numbers is given by the formula S = 1 + 2 + 3 + ... + n.
Steps:
B. Source Code:
#include <stdio.h>
int sumOfNatural(int n)
{
if (n == 0)
return 0;
return n + sumOfNatural(n - 1);
}
int main()
{
int n;
printf("Enter a number: ");
scanf("%d", &n);
if (n < 1)
printf("Sum is not defined for negative numbers or zero.\n");
else
printf("Sum of natural numbers up to %d is %d\n", n, sumOfNatural(n));
return 0;
}
666-63-65 5
C. Program Input/Output:
II. Discussion:
From this lab, I learned how to implement user-defined functions and recursion in C
programming. I understood how recursion can simplify complex problems like
factorial calculation and summing natural numbers. Moreover, I practiced writing
prime number checks using loops and conditional statements. This knowledge can
be applied in real-life scenarios where mathematical computations or iterative tasks
are required, such as in developing algorithms or solving engineering problems.
666-63-65 6