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

Recursion

Recursion is a programming technique that allows a method to call itself to solve problems iteratively. Some examples of problems that can be solved recursively include calculating the sum of integers from 1 to n, computing factorials, and performing binary searches on sorted arrays. Recursive methods contain a base case that stops the recursion and returns a value, and a recursive case that calls the method on a smaller problem until the base case is reached.

Uploaded by

dogan20021907
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)
16 views

Recursion

Recursion is a programming technique that allows a method to call itself to solve problems iteratively. Some examples of problems that can be solved recursively include calculating the sum of integers from 1 to n, computing factorials, and performing binary searches on sorted arrays. Recursive methods contain a base case that stops the recursion and returns a value, and a recursive case that calls the method on a smaller problem until the base case is reached.

Uploaded by

dogan20021907
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/ 6

Recursion

• Recursion is a fundamental programming


technique that can provide an elegant solution
certain kinds of problems
Recursive Programming

// This method returns the sum of 1 to num


// 1 + 2 + 3 + … + num

public int sum (int num){


Problem?
return num + sum (num-1);

}
Recursive Programming

// This method returns the sum of 1 to num


// 1 + 2 + 3 + … + num

public int sum (int num){

if ( num == 1 )
return 1;
else
return num + sum (n-1);

}
Recursive Programming

result = 6
main
sum(3)

result = 3
sum
sum(2)
// 1 + 2 + 3 + … + num

public int sum (int num){


result = 1
sum
if ( num == 1 )
return 1; sum(1)
else
return num + sum (n-1);

}
sum
Recursive Factorial

// This method returns the n!


// 1 * 2 * 3 * … * n

int fact( int n ){

if( n <= 1 ){
return 1;
} else {
return n * fact( n-1 );
}

}
Recursive Binary Search
int BinarySearch( int[] array, int start, int end, int target ){

int middle = ( start + end ) / 2;

if( end < start ) return -1;

if( target == array[ middle ] ){


return middle;
}

else if( target < array[ middle ] ){


return BinarySearch( array, start, middle-1, target );
}

else {
return BinarySearch( array, middle+1, end, target );
}
}

You might also like