Search

배열1_문제06_랜덤홀수합

대분류
STEP04 배열
소분류
배열1_문제

영상

문제

package 배열1_문제; /* [문제] 아래 배열에서 랜덤 값 -100 ~ 100을 4개 저장 후 그 값 중 홀수의 합만 출력하시오. [예시] arr = {-11, 4, 73, -2}; 결과 : -11 + 73 = 62 */ public class 배열1_문제06_랜덤홀수합_문제 { public static void main(String[] args) { int[] arr = new int[4]; } }
Java
복사

해설

package 배열1_문제; import java.util.Random; /* [문제] 아래 배열에서 랜덤 값 -100 ~ 100을 4개 저장 후 그 값 중 홀수의 합만 출력하시오. [예시] arr = {-11, 4, 73, -2}; 결과 : -11 + 73 = 62 */ public class 배열1_문제06_랜덤홀수합_정답 { public static void main(String[] args) { Random ran = new Random(); int[] arr = new int[4]; for(int i=0; i<4; i++) { int r = ran.nextInt(201) - 100; arr[i] = r; System.out.print(arr[i] + " "); } System.out.println(); /* [풀이] arr = [-11, 4, 73, -2] i = 0 arr[0]:-11 % 2 != 0 true total = 0 + -11 i = 1 arr[1]: 4 % 2 != 0 false total = -11 i = 2 arr[2]: 73 % 2 != 0 true total = -11 + 73 i = 3 arr[3]: -2 % 2 != 0 false total = 62 */ int total = 0; for(int i=0; i<4; i++) { if(arr[i] % 2 != 0) { total += arr[i]; System.out.print(arr[i] + " "); } } System.out.println(" = " + total); } }
Java
복사