Java SE/Self-Invocation

Self-Invocation

Soul-Learner 2009. 4. 21. 17:41

/* 재귀호출은 한개의 메소드 안에서 모든 작업이 이루어지는 것이 아니라
* 호출된 회수만큼 메소드가 복사되어 별개의 메소드가 호출되는 원리이다.
* 재귀호출로 하고자 하는 일을 산술식, 도표, 그림 등으로 표현해 놓고
* 반복되는 부분을 한개의 메소드로 구현해 주고 다음 메소드를 호출해 주면 된다.
*/
class SelfInvocation
{
 public static void main(String[] args)
 {
  System.out.println(sigma(10));
 }

 /*
 0부터 주어진 숫자(n)까지의 수열의 합을 구하는 재귀호출 메소드 작성요령
 n+(--n)+(--n)+..........0 으로 표현할 수 있으며 n+가 반복되는 구간이므로 'n+다음메소드호출' 형식이다.
 메소드로 표현할 때는 total = n+sigma(--n) 으로 하면 된다.
 */

  static int sigma(int n)
 {
  int total = 0;
  if(n>0) total = n+sigma(--n);
  return total;
 }

  // factorial 을 구하는 경우
  static int factorial(int n)
 {
  int total = 1;
  if(n>0) total = n*factorial(--n);
  return total;
 }

}

다양한 형태의 재귀호출

/* 재귀호출을 이용하는 다양한 예 */
public class Recursive {

 /*재귀호출을 이용하여 일련의 숫자를 출력한다(리턴값을 사용하지 않는 경우)
 * 호출할 때는 recursive01(1) */
 static void recursive01(int n){
  System.out.print(n);
  if(n<10)recursive01(n+1);
 }
 
 /* 재귀호출과 파라미터를 이용하여 일련의 숫자들을 합산한다
  * 호출할 때는 recursive02(1,0) */
 static void recursive02(int n, int sum){
  sum += n;
  if(n<10) recursive02(n+1, sum);
  else System.out.println("\n합산한 결과:"+sum);
 }
 
 /* 재귀호출과 리턴값을 이용하여 일련의 숫자를 출력한다
  * 호출할 때는 recursive03(10) */
 static int recursive03(int n){
  if(n==1) return n;
  else {
   System.out.print(recursive03(n-1));
   return n;
  }
 }

 /* 재귀호출과  리턴값을 이용하여 일련의 숫자를 합산한 결과를 출력한다
  * 호출할 때는 recursive04(10) */
 static int recursive04(int n){
  if(n==1) return n;
  else {
   return n+recursive04(--n);
  }
 }
 
 public static void main(String[] args){
  recursive01(1);
  recursive02(1, 0);
  System.out.println(recursive03(10));
  System.out.println(recursive04(10));
 }
}