Breaking News
yeni film izle hd film seyret film izle

Recursive Functions In Java Script

A function which calls itself, is called a recursive function. When A function calls itself it gets repeatedagain and again until the desired condition meets. Recursive functions are such type of functions which calls themselves. A provision to escape from indefinite loop is made in the program.
 
Example:
 
<html>

<head>

</head>

<body onclick=”recur()”>

<h1 align=center> Click on me please </h1>

<script type=”text/javascript”>

var a,sum a=sum=0   function recur()

{

if(a<101)

{

sum=sum+a a++ recur()

}

else

{

document.write(“Sum of counts from 0-100 is “+sum)

}

}

</script>

</body>

</html>

 
Syntax:
 
function functionname(var1, var2,..)

{

lines to be kept under this name return(variablename)

}

 
Example:
 
<html>

<head>

</head>

<body>

<script type=”text/javascript”>

function max(m)

{

var x,y

y=m[0];

for(x=0;x<m.length;x++)

{

if(m[x]>y)

{

y=m[x]

}

}

return(y)

}

var m=new Array()

m[0]=50

m[1]=12

m[2]=99

m[3]=45

m[4]=120

m[5]=110

m[6]=22

m[7]=106

i=max(m)

document.write(“Maximum Value is “+i)

</script>

</body>

</html>

 
Understanding program:
In the above given program we have declared two variables named a and sum a function is there name recur which is being called onclick event (discussed in events section), when user clicks on the web page this function will be called this function is adding the incremented value of a to sum variable and calling again the recur function which again adds the new value of a to sum a condition check is there to check the value of a. when it will become 101 the statement typed under else scope will get executed.
 
Output is:
Sum of counts from 0-100 is 5050
Click here to view result of this program on browser
 
Example:
 
<html>

<head>

</head>

<body onclick=”recur()”>

<h1 align=center> Click on me please </h1>

<script type=”text/javascript”>

var a=5 fact=1

function recur()

{

if(a>0)

{

fact=fact*a a– recur()

}

else

{

document.write(“<br> Factorial of “+a+” is “+ fact)

}

}

</script>

</body>

</html>

 
Output is:
Factorial of 0 is 120

Check Also

Functions Returning Values In Java Script

Function is a set of statements recognized by a name and can be used as …