본문 바로가기
728x90
반응형

Algorithm7

[Algorithm] 배열 모든 요소 합계 //모든 요소 더 하는 메서드 static int sumOf(int[] a){ int sum = 0; for (int i = 0; i < a.length; i++) { sum += a[i]; } return sum; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("n = "); int n = sc.nextInt(); int[] a = new int[n]; for(int i = 0; i < n; i++) { System.out.print("a["+i+"] = "); a[i] = sc.nextInt(); } System.out.println("sum = " + sumOf(a)); }.. 2023. 12. 5.
[Algorithm] 배열 역순 정렬 Scanner sc = new Scanner(System.in); System.out.print("n : "); int n = sc.nextInt(); int[] a = new int[n]; //배열에 값을 넣는다 for (int i = 0; i < n; i++) { System.out.print("x["+i+"] : "); a[i] = sc.nextInt(); } //교환횟수 = 요소 개수 / 2 for(int i = 0; i < a.length / 2; i++){ int temp = a[i]; a[i] = a[a.length - i - 1]; a[a.length - i - 1] = temp; System.out.println(); System.out.println("a[" + i + "]과 a[" +.. 2023. 12. 5.
[Algorithm] 재귀함수(피보나치 수열, 팩토리) 재귀함수란? 정의 단계에서 자신을 재참조하는 함수를 뜻한다. 예제 public Main{ public static void func(int count) { if (count == 3) { return; } func(count + 1); System.out.println("count : " + count); } public static void main(String[] args) { func(0); } } 결과값이 어떨까요? 결과는 count : 2 count : 1 count : 0 이렇게 나오는데 그 이유는 재귀 호출을 한 후에 count가 출력하도록 되어있기 때문에 콜스택에 차근 차근 쌓이며 func(0) 호출 -> func(1) 호출 -> func(2) 호출 -> func(3) 에서 조건에 의해 중.. 2023. 11. 27.
728x90
반응형