1~100까지의 수 중에 홀수는 홀수로 출력, 짝수는 짝수로 출력하는 프로그램을 작성하시오.
어떤 수를 2로 나눈 나머지가 0이면 짝수, 아니면 홀수
1. 절차 작성
package algo;
public class OddEven {
public static void main(String[] args) {
// 1~5까지 홀수/짝수 출력하는 프로그램
// 1. 1은 홀수 출력
System.out.println("1은 홀수입니다.");
// 2. 2는 짝수 출력
System.out.println("2는 짝수입니다.");
// 3. 3은 홀수 출력
System.out.println("3은 홀수입니다.");
// 4. 4는 짝수 출력
System.out.println("4는 짝수입니다.");
}
}
2. 공통 모듈 찾기
package algo;
public class OddEven {
public static void main(String[] args) {
// 1~5까지 홀수/짝수 출력하는 프로그램
int a = 0;
a++;
// 1. 1은 홀수 출력
System.out.println(a + "은 홀수입니다.");
a++;
// 2. 2는 짝수 출력
System.out.println(a + "는 짝수입니다.");
a++;
// 3. 3은 홀수 출력
System.out.println(a + "은 홀수입니다.");
a++;
// 4. 4는 짝수 출력
System.out.println(a + "는 짝수입니다.");
}
}
package algo;
public class OddEven {
public static void main(String[] args) {
// 1~5까지 홀수/짝수 출력하는 프로그램
int a = 0;
String s = "";
a++;
s = a % 2 == 0 ? "짝수" : "홀수";
// 1. 1은 홀수 출력
System.out.println(a + "은 " + s + "입니다.");
a++;
s = a % 2 == 0 ? "짝수" : "홀수";
// 2. 2는 짝수 출력
System.out.println(a + "은 " + s + "입니다.");
a++;
s = a % 2 == 0 ? "짝수" : "홀수";
// 3. 3은 홀수 출력
System.out.println(a + "은 " + s + "입니다.");
a++;
s = a % 2 == 0 ? "짝수" : "홀수";
// 4. 4는 짝수 출력
System.out.println(a + "은 " + s + "입니다.");
}
}
3. 반복문
package algo;
public class OddEven {
public static void main(String[] args) {
// 1~5까지 홀수/짝수 출력하는 프로그램
int a = 0;
String s = "";
for (int i = 1; i <= 100; i++) {
a++;
s = a % 2 == 0 ? "짝수" : "홀수";
System.out.println(a + "은 " + s + "입니다.");
}
}
}

Share article