0% found this document useful (0 votes)
4 views4 pages

Lab 18

Uploaded by

sadmannsulibrary
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views4 pages

Lab 18

Uploaded by

sadmannsulibrary
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

lab18.

md 2024-11-18

CSE115L Week:11(Recursion)
Name:
ID:
Section:

Example 01 C program of a recursive function to find the sum of n natural numbers. For example:
the number 5 will give an output of 15 since 5+4+3+2+1 = 15.
#include<stdio.h>
int sum(int n)
{
if (n == 0)
return 0;
else
return n + sum (n - 1);
}
int main ()
{

int num, res;


printf ("Enter a positive integer:\n");
scanf ("%d", &num);
res = sum (num);
printf ("sum=%d", res);
}

Example 02: C Program that computes Factorial of a number using recursive function.

#include<stdio.h>
long long int factorial (int n)
{
// Base Case
if (n == 0 || n == 1)
return 1;
// Grenral case
return n * factorial (n - 1);
}

1/4
lab18.md 2024-11-18

int main ()
{
int num;
long long int result;

printf ("Enter a positive integer:\n");


scanf ("%d", &num);
result = factorial (num);
printf ("%d! = %lld", num, result);
}

Online visualization
Example 03: C Program that computes nth Fibonacci number using recursive function.

#include<stdio.h>
int fib(int n)
{
// Base Case
if (n == 0 || n == 1)
return n;
// General Case
return fib(n-1) + fib(n-2);
}

int main ()
{

int num, result;

printf ("Enter a positive integer:\n");

scanf ("%d", &num);

result = fib (num);

printf ("%d! = %d", num, result);

2/4
lab18.md 2024-11-18

Example 04 :C program to calculate sum of digits using recursion.

#include <stdio.h>
int sumOfDigits(int n)
{
// Base condition
if(n == 0)
return 0;
// general condition
return ((n % 10) + sumOfDigits(n / 10));
}
int main()
{
int num, sum;
printf("Enter any number to find sum of digits: ");
scanf("%d", &num);

sum = sumOfDigits(num);

printf("Sum of digits of %d = %d", num, sum);


return 0;
}

Example 05 : C program to find GCD (HCF) of two numbers using recursion.

#include <stdio.h>
int gcd(int a, int b)
{
// Base Case
if(b == 0)
return a;
// General Case
return gcd(b, a%b);
}

int main()
{
int num1, num2, hcf;
printf("Enter any two numbers to find GCD: ");
scanf("%d%d", &num1, &num2);
hcf = gcd(num1, num2);
printf("GCD of %d and %d = %d", num1, num2, hcf);
return 0;
}

3/4
lab18.md 2024-11-18

Example :
Enter any two numbers to find GCD: 8,12
GCD of 8 and 12 = 4

viz
Q a b R
1 8 12 4
0 12 4 4
1 4 4 0
4 0

4/4

You might also like