متدی بازگشتی که دو عدد a و b را با هم جمع کند و نتیجه را برگرداند.
/* Recursive Sum - 1 14 Oct 2015 Java Language By: Sina Moradi http://Samiantec.ir */ import java.util.*; public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); System.out.println("Enter a :"); int a=input.nextInt(); System.out.println("Enter b :"); int b=input.nextInt(); System.out.println("a+b= " + sum(a, b)); } public static int sum(int x, int y) { if (y == 0) return x; return 1 + sum(x, y - 1); } }
/* Recursive Sum - 2 14 Oct 2015 Java Language By: Sina Moradi http://Samiantec.ir */ import java.util.*; public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); System.out.println("Enter a :"); int a=input.nextInt(); System.out.println("Enter b :"); int b=input.nextInt(); System.out.println("a+b= " + sum(a, b)); } public static int sum(int x, int y) { if (y == 0) return x; return sum(x + 1, y - 1); } }