RECURSIONS JAVA What is recursion o Noniterative approach

RECURSIONS

JAVA

·       What is recursion?

o   ? Non-iterative approach to address programming problems

o   ? Recursion is a method calling itself

o   ? Java supports recursion

o   ? Another form of programming technique

·       ? So far we have been using “iterative approach” to address programming problems

Recursion (examples in this lecture slide)

Solution

Recursion is supported by java which solves many programming problems .all the 4 options are true.

lets see an example,where we calculate the sum of n terms by using Recursion.

SumOfNValues.java

import java.util.Scanner;

public class SumOfNValues {

   public static void main(String[] args) {
      
       //Declaring variables
       int n,sum=0;
      
       //Scanner class object is used to read the values entered by the user
               Scanner sc = new Scanner(System.in);
              
               //Getting the number entered by the user
               System.out.print(\"Enter no of Positive Integers You want to add :\");
               n=sc.nextInt();
              
               //Calling te method by passing the number as argument
               sum=SumOfNos(n);
              
               //Displaying the sum of the numbers till the number entered by the user
               System.out.println(\"Sum of first \"+n+\" numbers is :\"+sum);

   }

   //This method is used to return the sum of numbers recursively.
   private static int SumOfNos(int n) {
if(n>0)
       return n+SumOfNos(n-1);
else
   return 0;
      
   }

}

_____________________________________

Output:

Enter no of Positive Integers You want to add :8
Sum of first 8 numbers is :36

RECURSIONS JAVA · What is recursion? o ? Non-iterative approach to address programming problems o ? Recursion is a method calling itself o ? Java supports recur
RECURSIONS JAVA · What is recursion? o ? Non-iterative approach to address programming problems o ? Recursion is a method calling itself o ? Java supports recur

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site