recursion

mail@pastecode.io avatar
unknown
java
2 months ago
1.5 kB
8
Indexable
Never
//cw1

public class ClassworkOne {
    public static void main(String[] args) {
        ntoOne(5);
        System.out.println();
        oneToN(5);
        System.out.println();
        System.out.println(recurSum(10));


    }

    public static void ntoOne(int num) {

        if (num >= 1) {
            System.out.print(num + " ");
            ntoOne(num - 1);

        }
    }

    public static void oneToN (int num) {

        if (num >= 1) {
            oneToN(num - 1);
            System.out.print(num + " ");
        }
    }




    public static int recurSum(int n) {   //5
        if (n <= 1) {  // base condition
            return n;
        }
        return n + recurSum(n - 1); // 4 + ( 3 + 2 + 1  )
    }


}




//cw2

import java.util.*;
import java.lang.Math;

public class ClassworkTwo {

    public static void main(String[] args) {
        reverseDigits(123456);
    }

    public static void reverseDigits(int n) {
        if (n < 10) {
            System.out.println(n);  // 1
        }
        else {
            System.out.println(n % 10); // 6 5 4 3 2
            reverseDigits(n / 10); // 1
        }
    }
}



//cw3

public class ClassworkThree {
    public static void main(String[] args) {
        System.out.println(sumDigits(649));
    }

    public static int sumDigits (int n) {
        if (n < 10) {
            return n;
        }
        else {
            return n % 10 + sumDigits(n / 10);
        }
    }
 }
Leave a Comment