Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

재귀를 사용하여 숫자의 합을 찾는 Java 프로그램

<시간/>

이 기사에서는 재귀를 사용하여 숫자의 자릿수 합을 찾는 방법을 이해합니다. 재귀 함수는 특정 조건이 충족될 때까지 자신을 여러 번 호출하는 함수입니다.

재귀는 자기 유사 방식으로 항목을 반복하는 프로세스입니다. 프로그래밍 언어에서 프로그램이 동일한 함수 내에서 함수를 호출하도록 허용하는 경우 이를 함수의 재귀 호출이라고 합니다.

많은 프로그래밍 언어는 스택을 통해 재귀를 구현합니다. 일반적으로 함수(호출자)가 다른 함수(피호출자) 또는 자신을 피호출자로 호출할 때마다 호출자 함수는 실행 제어를 피호출자에게 넘깁니다. 이 전송 프로세스에는 호출자에서 호출 수신자에게 전달할 일부 데이터가 포함될 수도 있습니다.

아래는 동일한 데모입니다 -

입력

입력이 -

라고 가정합니다.
Enter the number : 12131415

출력

원하는 출력은 -

The Sum of digits of 12131415 is 18

알고리즘

Step 1 - START
Step 2 - Declare two integer values namely my_input and my_result
Step 3 - Read the required values from the user/ define the values
Step 4 - A recursive function ‘digitSum’ is defined which takes an integer as input. The function computes the reminder by re-iterating over the function multiple times, until the base condition is reached.
Step 5 - The recursive function ‘digitSum’ is called and its result is assigned to ‘my_result’
Step 6 - Display the result
Step 7 - Stop

예시 1

여기에서 입력은 프롬프트에 따라 사용자가 입력하고 있습니다. 우리코딩 그라운드 도구에서 이 예제를 라이브로 사용해 볼 수 있습니다. 재귀를 사용하여 숫자의 합을 찾는 Java 프로그램 .

import java.util.Scanner;
public class Sum{
   public static void main(String args[]){
      int my_input, my_result;
      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 = my_scanner.nextInt();
      my_result = digitSum(my_input);
      System.out.println("The Sum of digits of " + my_input + " is " + my_result);
   }
   static int digitSum(int n){
      if (n == 0)
         return 0;
      return (n % 10 + digitSum(n / 10));
   }
}

출력

Required packages have been imported
A reader object has been defined
Enter the number : 12131415
The Sum of digits of 12131415 is 18

예시 2

여기서 정수는 이전에 정의되었으며 그 값은 콘솔에 액세스되어 표시됩니다.

public class Sum{
   public static void main(String args[]){
      int my_input = 12131415;
      System.out.println("The number is defined as : " +my_input);
      int my_result = digitSum(my_input);
      System.out.println("The Sum of digits of " + my_input + " is " + my_result);
   }
   static int digitSum(int n){
      if (n == 0)
         return 0;
      return (n % 10 + digitSum(n / 10));
   }
}

출력

The number is defined as : 12131415
The Sum of digits of 12131415 is 18