DEV Community

Yesh Rajawat
Yesh Rajawat

Posted on

3 Basic Questions on Recursion

Print you Name N times

public class N_times {

    public static void printNTimes(int n, String name) {
        if(n==0) {
            return ;
        }
        else {
            System.out.println(name);
            printNTimes(n-1,name);
        }

    }

    public static void main(String ...args) {

        printNTimes(10,"yesh");

    }
}
Enter fullscreen mode Exit fullscreen mode

Print 1 TO N in recursion

package recursion;

public class Print_N {


    public static void print_1_to_N(int n) {

        if(n==0) {
            return ;
        }
        else {

            print_1_to_N(n-1);
            System.out.println(n);
        }
    }



    public static void main(String ... args)
{

        print_1_to_N(10);
}
}

Enter fullscreen mode Exit fullscreen mode

Sum of an Array


public class Sum_Of_Array {
 public static int sum_Array(int n, int[]arr){

     if(n==-1) {
         return 0;
     }
     else {

         int sum = sum_Array(n-1,arr);
         System.out.println(arr[n]+ sum);
         return arr[n] + sum;
     }

}


    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int arr[] = {1,2,3,4,5,-7};
        System.out.println(sum_Array(5,arr));
    }

}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)