Java/기타 알고리즘

1부터 50까지의 홀수와 짝수의 총합 구하기

은찡안찡 2023. 4. 5. 17:42

문제 > 1부터 50까지의 홀수와 짝수의 총합 구하기

 

package com.dream.controls;

public class OverLapEx05 {
	public static void main(String[] args) {
		//변수 선언 단계
		int oddTotal = 0, evenTotal = 0;

		//for 반복문 수행 단계
		for(int i=1; i<=50; i++) {
			if(i % 2 == 0) evenTotal += i; //evenTotal = evenTotal + i;
			else oddTotal += i;
		}

		/*
		for(int i=2; i<=50; i+=2) evenTotal += i;
		for(int i=1; i<=50; i+=2) oddTotal += i;
		*/
		//결괏값을 출력하는 단계
		System.out.println("짝수의 총합: "+evenTotal);
		System.out.println("홀수의 총합: "+oddTotal);
	}
}