使用递归查找 N 个数字之和的 Java 程序
javaobject oriented programmingprogramming更新于 2024/4/15 18:20:17
在本文中,我们将了解如何使用递归查找 N 个数字之和。递归函数是多次调用自身直到满足特定条件的函数。
递归是以自相似方式重复项目的过程。在编程语言中,如果程序允许您在同一函数内调用函数,则称为函数的递归调用。
许多编程语言通过堆栈实现递归。通常,每当一个函数(调用者)调用另一个函数(被调用者)或自身作为被调用者时,调用者函数都会将执行控制权转移给被调用者。此传输过程还可能涉及从调用者传递给被调用者的一些数据。
下面是相同的演示 −
输入
假设我们的输入是 −
输入 N 的值:6 输入数组的元素: 15 30 45 80 100 140
输出
所需的输出将是 −
N 个数字的总数为:410
算法
步骤 1 - 开始 步骤 2 - 声明两个整数值,即 N 、 my_sum 和 i 以及一个整数数组‘my_array’ 步骤 3 - 从用户处读取所需值/定义值 步骤 4 - 定义递归函数 ‘RecursiveSum,该函数以两个整数作为输入。该函数通过多次重复该函数来计算余数,直到达到基本条件。 步骤 5 - 调用递归函数 ‘RecursiveSum 并存储其结果 步骤 6 - 显示结果 步骤 7 - 停止
示例 1
import java.util.Scanner;
public class ArraySum {
public static int RecursiveSum(int my_array[], int i,int N){
if (i == N)
return 0;
return my_array[i] + RecursiveSum(my_array, i + 1,N);
}
public static void main(String[] args){
int N, my_sum, i;
N = 6;
my_sum = 0;
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 value of N : ");
N = my_scanner.nextInt();
int my_array[] = new int[N];
System.out.println("Enter the elements of the array :" );
for ( i = 0 ; i < N ; i++ ){
my_array[i] = my_scanner.nextInt();
}
my_sum = RecursiveSum(my_array, 0, N);
System.out.println("\n The total of N numbers is : " + my_sum);
}
}
输出
Required packages have been imported A reader object has been defined Enter the value of N : 6 Enter the elements of the array : 15 30 45 80 100 140 The total of N numbers is : 410
示例 2
这里,整数已经被预先定义,并且它的值被访问并显示在控制台上。
public class Main {
public static void main(String[] args) {
int[] my_array = {15, 20, 25, 30, 35, 40};
int my_input , i, array_size;
array_size = 5;
my_input = 25;
boolean my_check = false;
System.out.println("The number is defined as " +my_input);
System.out.println("The elements in the integer array is defined as :" );
for ( i = 0 ; i < array_size ; i++ ){
System.out.print(my_array[i] +" ");
}
for ( i = 0 ; i < array_size ; i++ ) {
if (my_array[i] == my_input) {
my_check = true;
break;
}
}
if(my_check)
System.out.println("\nThe array contains the given value");
else
System.out.println("\nThe array doesnot contain the given value");
}
}
输出
The number is defined as 25 The elements in the integer array is defined as : 15 20 25 30 35 The array contains the given value
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

