본문 바로가기
JAVA

13. For문(제어문)2

by NamGH 2023. 7. 27.
public static void main(String[] args) {
int dan;
System.out.print("단: ");
Scanner sc = new Scanner(System.in);
dan = sc.nextInt();
 
for(int i = 1; i <= 9; i++) {
System.out.printf("%d * %d : %d\n", dan, i, (dan * i));
}
 
for(char i = 'A'; i <= 'Z'; i++) {
System.out.println(i);
}
}

위의 코드는 scanner을 이용해 자신이 출력하고 싶은 구구단과 알파벳을 정렬하는 코드이다

for(int i = 1; i <= 9; i++) {
System.out.printf("%d * %d : %d\n", dan, i, (dan * i));
}를 이용해 9단까지 구현했으며 printf로 dan과 i의 값을 가져온다
알파벳의 경우 char을 이용하고 문자는 ' '을붙여줘야하며 증감식을 이용해서 A~Z까지 출력되게 하였다

public static void main(String[] args) {
int i, j;
 
for(i=9; i>=3; i-=3) {
for(j=3; j<=7; j+=2) {
System.out.println(i + "," +j);
}
System.out.println("---------------");
}
System.out.println("***************");
}

위 코드는 증감식을 이용해서 숫자가 배열처럼 보여지게 한 코드이다

i는 9~3까지 3씩 내려가게 하였고 j는 3~7까지 2씩 증가하게하였다 다음 코드의 결과를 보면 다음과 같다

9,3
9,5
9,7
---------------
6,3
6,5
6,7
---------------
3,3
3,5
3,7
---------------
***************

for문 밖에 ***************이 나오게 설정했기때문에 마지막에 한번만 출력되는것을 알 수있다.

'JAVA' 카테고리의 다른 글

15. While문, do~while문  (0) 2023.07.31
14. For문 구구단  (0) 2023.07.27
12. For문(제어문)  (0) 2023.07.27
11. Switch~case  (0) 2023.07.27
10. IF문(제어문)  (0) 2023.07.27