Вы находитесь на странице: 1из 16

DEPARTMENT OF TECHNICAL EDUCATION

ANDHRA PRADESH
Name : Murali Krishna Chintala
Designation : Lecturer in CME
Branch : Computer Engineering
Institution : SUVR & SR GPW, Ethamukkala
Year/ Semester : III Semester
Subject Name : Unix & C
Subject Code : CM – 304
Major Topic : Understand Modular Programming
Duration : 50 Min
Sub Topic : Recursion.
Teaching Aids : PPT, Animations
CM304.68 1
Objective

On completion of this period, you would be able to


know :

• Understand the concept of Recursion.

CM304.68 2
Recursion

• A function is recursive if a statement in the


body of the function calls itself.

• It is the process of defining something in


terms of itself.

CM304.68 3
Advantage of recursion

Recursive function is

• Clear.

• Short.

• Contains simple programs.

CM304.68 4
Advantage of recursion
Contd..

• Commonly used example of a recursive


procedure is finding the factorial of a
number.

• Factorial of number N is defined as

N! = N*(N-1)*(N-2)*……..1

CM304.68 5
Advantage of recursion
Contd..

• Recursive definition should have a stopping


condition i.e., 0! =1.

• Complete definition of factorial function is

N! = N*(N-1)! with 0! = 1

CM304.68 6
Program for factorial of a number
#include<stdio.h>
int fact(int);
main()
{
int n;
scanf(“%d”,&n);
printf(“factorial of number %d is %d\n”,n,fact(n));
}

CM304.68 7
Program for factorial of a number
int fact (int x) contd,..

{
int f =1;
if(x==1)
return(1);
else if(x>0)
f=x*fact(x-1);
return(f);
}

CM304.68 8
Program to find sum of digits of a number

#include<stdio.h>
int sumdigit(int);
main()
{
int n;
scanf(“%d”,&n);
printf(“sum of digits is %d:”,sumdigit(n));
}

CM304.68 9
Program to find sum of digits of a number
Contd..
int sumdigit(int x)
{
int sum =0;
if(x==0)
return(sum);
else
sum=(x%10 + sumdigit(x/10));
return(sum);
}

CM304.68 10
Summary

In this class, we have learnt about..

• A function calling itself is known as recursion.

CM304.68 11
Quiz

1. A Function calls itself is called..

a. Recursion

b. Excursion

c. None

CM304.68 12
Quiz

1. A Function calls itself is called..

a. Recursion

b. Excursion

c. None

CM304.68 13
Quiz

2. Recursion program is..


a. Short
b. Simple
c. Both

CM304.68 14
Quiz

2. Recursion program is..

a. Short
b. Simple
c. Both

CM304.68 15
Frequently Asked Questions

1.Explain recursion with an example.


(Apr ’04, Oct ’04)

CM304.68 16