使用遞迴計算N個數之和的Java程式
在本文中,我們將學習如何使用遞迴在Java中求N個數之和。遞迴是指一個方法重複呼叫自身,直到滿足基本條件。在Java中,每個遞迴呼叫都會被放入堆疊中,直到達到基本情況,之後返回值用於計算結果。
問題陳述
給定一個整數陣列,編寫一個Java程式使用遞迴查詢所有N個數之和。輸入
The user provides the value of N, the number of integers to sum.
The user inputs N integers to be summed.
輸出
The program should output the sum of the N numbers.
使用遞迴求N個數之和的步驟。
以下是使用遞迴求N個數之和的步驟。
- 宣告兩個整數值和一個整數陣列
- 從使用者讀取所需的值/定義值
- 定義一個遞迴函式“RecursiveSum”,它接收兩個整數作為輸入。該函式透過多次重複迭代自身來計算餘數,直到達到基本條件。
- 呼叫遞迴函式“RecursiveSum”並將結果儲存起來
- 將最終的和輸出給使用者。
使用遞迴計算N個數之和的Java程式
下面是一個使用遞迴計算N個數之和的Java程式示例
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
訪問並顯示之前在控制檯中定義的整數的Java程式。
以下是訪問並顯示之前在控制檯中定義的整數的Java程式示例。
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
程式碼解釋
程式定義了一個遞迴函式RecursiveSum來計算陣列的和。它會一直呼叫自身直到達到基本情況,並將當前元素新增到總和中。在main()函式中,使用者輸入陣列大小和元素,最後程式使用RecursiveSum顯示總和。廣告