JAVA40 23. 재귀호출 펙토리얼 public static void main(String[] args) { System.out.println("4: " + fact(4)); System.out.println("4: " + fact2(4)); } static int fact(int a){ if(a == 1) { return 1; }else { return a * fact(a - 1); } } static int fact2(int a){ int result = 1; for(int i = a; i >= 1; i--) { result = result *i; } return result; } 다음은 두가지 방법으로 4펙토리얼을 하는 방법인데 첫번째 방법같은경우 a가1이될때까지 else부분을 반복시켜주는건데 a-1인 이유는 펙토리얼이 한번 돌때마다.. 2023. 8. 2. 22. 재귀호출 재귀호출 간단하게 메서드 안에서 메서드를 부르는것이라고한다 public static void main(String[] args) { show(3); // 호출 } static void show(int cnt){ System.out.println("Hi~" + cnt); if(cnt == 1) { // cnt가 1이 될때까지 반복 return; } show(--cnt); } 재귀함수를 이용해 cnt가 1이 될때까지 반복한 후 메인 메서드로 간다 따라서 결과는 --cnt를 했기때문에 3에서 1까지 반복한 후 메인 메서드로 간 Hi~3 Hi~2 Hi~1 2023. 8. 2. 21. 클래스와 메서드 활용 import java.util.Scanner; class Test{ void dan() { Scanner sc = new Scanner(System.in); System.out.print("단을 입력해 주세요: "); int num = sc.nextInt(); System.out.println(num + "단"); for(int i = 1; i 2023. 8. 1. 20. 메서드 메서드란 특정한 작업을 수행하도록 독립적으로 작성된 프로그램이며 코드의 분할과 재사용을하며 반복할 코드를 만들어놓고 필요할때 호출한다 형식 리턴타입 메서드이름(타입 변수명, 타입 변수명, ...) { 메서드 호출시 수행될코드 } public class Ex04_메서드 { public static void main(String[] args) { add(3, 4); double d = sub(10, 4.7, 1); int f = gob(7, 5); int result = max(10,3); System.out.println("sub:" + d); System.out.println("gob:" + f); System.out.println("max:" + result); } static int max(int a.. 2023. 8. 1. 이전 1 2 3 4 5 6 7 8 ··· 10 다음