0% found this document useful (0 votes)
15 views

Cse 11-1

This document provides examples of using recursion to calculate the sum of natural numbers, find the factorial of a number, and print odd numbers within a range. It includes code snippets and explanations for recursive functions to calculate sums and factorials, as well as a function to print odd numbers between two numbers by recursively incrementing a variable by 2 on each call until it exceeds the maximum value.

Uploaded by

Shakil hosen
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)
15 views

Cse 11-1

This document provides examples of using recursion to calculate the sum of natural numbers, find the factorial of a number, and print odd numbers within a range. It includes code snippets and explanations for recursive functions to calculate sums and factorials, as well as a function to print odd numbers between two numbers by recursively incrementing a variable by 2 on each call until it exceeds the maximum value.

Uploaded by

Shakil hosen
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/ 8

CSE 101: Computer Programming

Recursion
Recursion
A function that calls itself is known as a recursive function. And, this
technique is known as recursion.
Example: Sum of natural numbers
Use recursion to calculate the sum of natural numbers

Example: if n = 8,

Sum = 1+2+3+4+5+6+7+8
Example: Sum of natural numbers
#include<stdio.h> Explanation of this code is give here.
Google Drive Link
int sum(int x)
{
if(x>0)
return x+sum(x-1); Recursive function
else
return 0;
}
int main()
{
int n = 5;
int s = sum(n);
printf("sum of natural numbers=%d",s);
}
Example: Factorial using recursion
#include<stdio.h>

int factorial(int x)
{
if(x>0)
return x*factorial(x-1); Recursive function
else
return 1;
}

int main()
{
int n = 5;
int f = factorial(n);
printf("factorial of %d = %d\n",n,f);
}
Print odd numbers between an interval
Example:

input: n = 4, m = 11
output: 5, 7, 9, 11

Here, the output is the odd numbers between 4 and 11


Recursive function to print odd numbers in a range
#include<stdio.h> int main()
void print_odd(int x, int y) {
{ int n = 6, m = 18;
print_odd(n,m); // function to print odd numbers
if(x%2==0) return 0;
{ }
x = x + 1;
}
if(x>y) The function ends when x>y
{
return;
}
else
{ The function calls itself and the value of x is
printf("%d ",x);
incremented by 2 in each invocation
print_odd(x+2,y);
}
}
Explain how the following code works
#include<stdio.h> Explanation of this code is give here.
void func(int a) Google Drive Link
{
if(a <= 0)
return;
a = a-2;
printf("%d\n",a);
func(a);
a = a*5;
printf("%d\n",a);
}

int main()
{
func(3);
}

You might also like