ในบทความนี้ เราจะทำความเข้าใจวิธี หาผลรวมของ N ตัวเลขด้วยการเรียกซ้ำ (Recursion)
Recursion (การเรียกซ้ำ) คือกระบวนการที่ฟังก์ชันเรียกตัวมันเองซ้ำๆ จนกว่าเงื่อนไขฐาน (base case) จะเป็นจริง ใน Java การทำงานของ Recrosis ใช้ Stack ในการจัดเก็บสถานะของแต่ละการเรียก
ตัวอย่าง Input และ Output
Input:
Enter the value of N : 6 Enter the elements of array : 15 30 45 80 100 140
Output:
The total of N numbers is : 410
อัลกอริธึม
ขั้นตอนที่ 1 - เริ่มต้น ขั้นตอนที่ 2 - ประกาศตัวแปร N, my_sum, i และอาเรย์ my_array ขั้นตอนที่ 3 - อ่านค่าจากผู้ใช้ หรือกำหนดค่าเริ่มต้น ขั้นตอนที่ 4 - สร้างฟังก์ชัน RecursiveSum ที่รับอาเรย์, index, N คืนค่าผลรวม โดยเรียกตัวเองจน index == N ขั้นตอนที่ 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("\nThe total of N numbers is : " + my_sum);
}
}
Output
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 does not contain the given value");
}
}
Output
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