使用递归查找两个数字的乘积的 Java 程序

javaobject oriented programmingprogramming更新于 2024/4/15 17:48:17

在本文中,我们将了解如何使用递归查找两个数字的乘积。递归函数是多次调用自身直到满足特定条件的函数。

递归是以自相似方式重复项目的过程。在编程语言中,如果程序允许您在同一函数内调用函数,则称为函数的递归调用。

许多编程语言通过堆栈实现递归。通常,每当一个函数(调用者)调用另一个函数(被调用者)或自身作为被调用者时,调用者函数都会将执行控制权转移给被调用者。此传输过程还可能涉及从调用者传递给被调用者的一些数据。

下面是相同的演示 −

输入

假设我们的输入是 −

输入两个数字:12 和 9

输出

所需的输出将是

12 和 9 的乘积是 108

算法

步骤 1 - 开始
步骤 2 - 声明两个整数值,即 my_input 和 my_result
步骤 3 - 从用户那里读取所需值/定义值
步骤 4 - 递归函数"getproduct"被定义为以两个整数作为输入。该函数通过多次重复该函数来计算余数,直到达到基本条件。
步骤 5 - 调用递归函数"getproduct"并存储其结果
步骤 6 - 显示结果
步骤 7 - 停止

示例 1

import java.util.Scanner;
public class ProductRecursion{
   public static void main (String[] args){
      int my_input_1, my_input_2;
      System.out.println("Required packages have been imported");
      Scanner my_scanner = new Scanner(System.in);
      System.out.println("A reader object has been defined ");
      System.out.print("Enter the number : ");
      my_input_1 = my_scanner.nextInt();
      System.out.print("Enter the number : ");
      my_input_2 = my_scanner.nextInt();
      System.out.println("The product of "+my_input_1 +" and " +my_input_2 +" is " +getproduct(my_input_1, my_input_2));
   }
   static int getproduct(int my_input_1, int my_input_2){
      if (my_input_1 < my_input_2)
         return getproduct(my_input_2, my_input_1);
      else if (my_input_2 != 0)
          return (my_input_1 + getproduct(my_input_1, my_input_2 - 1));
      else
         return 0;
   }
}

输出

Required packages have been imported
A reader object has been defined
Enter the number : 12
Enter the number : 9
The product of 12 and 9 is 108

示例 2

这里,整数已经被预先定义,并且它的值被访问并显示在控制台上。

public class ProductRecursion{
   public static void main (String[] args){
      int my_input_1, my_input_2;
      my_input_1 = 12;
      my_input_2 = 9;
      System.out.println("The two numbers are defined as " +my_input_1 +" and " +my_input_2);
      System.out.println("The product of "+my_input_1 +" and " +my_input_2 +" is " +getproduct(my_input_1, my_input_2));
   }
   static int getproduct(int my_input_1, int my_input_2){
      if (my_input_1 < my_input_2)
         return getproduct(my_input_2, my_input_1);
      else if (my_input_2 != 0)
         return (my_input_1 + getproduct(my_input_1, my_input_2 - 1));
      else
         return 0;
   }
}

输出

The two numbers are defined as 12 and 9
The product of 12 and 9 is 108

相关文章


有用资源