- 0-100까지의 합
int total = 0;
for (int i = 100; i <=0 ; i--) {
total += i;
}
System.out.println(total);
- 중첩 반복문
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
System.out.print(i+" "+j+" ");
}
System.out.println();
}
- 중첩 반복문
/*
* 1
* 12
* 123
* 1234
* 12345
*/
for (int i = 1; i < 6; i++) {
for (int j = 1; j < 6-i; j++) {
System.out.print(" ");
}
for (int j = 1; j < i+1; j++) {
System.out.print(j);
}
System.out.println();
}
- 중첩 반복문
/*
* 1 //i=0, 공백 4, 숫자 1
* 123 //i=1, 공백 3, 숫자 3
* 12345 //i=2, 공백 2, 숫자 5
* 1234567 //i=3, 공백 1, 숫자 7
* 123456789 //i=4, 공백 0, 숫자 9
*/
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 4-i; j++) {
System.out.print(" ");
}
for (int j = 0; j < (i*2)+1; j++) {
System.out.print(j+1);
}
System.out.println();
}
- 0-10 짝수만 while if 문
int i=0;
while (i<10) {
if (i%2==0) {
System.out.print(i+" ");
}
i++; // 위치가 중요함.
}
- 입력받은 값들의 합
int sum = 0;
int n=100; // 0이 아님을 인식하기 위해서 초기화해줌.
Scanner sc = new Scanner(System.in);
while (n != 0) { // n이 0이 아닐때까지 while문 반복
System.out.println("입력: ");
n = sc.nextInt(); //0을 입력하면 종료됨.
sum += n; //입력받은 값들의 합
}
System.out.println("입력받은 값들의 합= "+sum);
- 특정값 입력 시 반복문 종료
while (true) {
System.out.println("이름 입력: ");
String name = sc.next();
//문자열비교는 equals
if (name.equals("준수")) {
System.out.println("프로그램종료");
break;
}
System.out.println(name);
}
- 1~6까지 난수발생
while (true) {
n = (int)(Math.random()*6)+1;
if (n == 6) {
System.out.println("프로그램종료");
break;
} else {
System.out.println(n);
}
}
- 특정값 입력전까지의 값을 카운팅
Scanner sc = new Scanner(System.in);
int n=0;
while(true) {
if(sc.nextInt() == -1) {
System.out.println("프로그램종료");
break;
}
n++;
}
System.out.println(n);
- 1~99 중 2의 배수이면서 3의 배수 출력 (while)
int k = 1;
while(k <100) {
if (k%2==0 && k%3==0) {
System.out.print(k+ " ");
}
k++;
}
- 1에서 100까지의 홀수의 누적합
int sum = 0;
for (int j = 1; j <= 100; j++) {
if (j%2==0) {
continue; //짝수일때 반복문 반복
} else {
System.out.print(j+" ");
sum +=j;
}
}
System.out.println();
System.out.println("홀수의 누적합= "+sum);
- 1~100안의 정수를입력받아 3,6,9 중 하나가 있는 경우 “짝”, 두 개 있는 경우 “짝짝”, 하나도 없으면 “땡”을출력해라.
- (정수값이 39라고 할 때, n/10=3, n%10=9 이 나온다. (/, % 연산자 활용))
- 실행 결과) 입력:39
짝짝
public class Review0602A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt(); //정수를 입력받음
int chk1 = num/10; //체크용 변수
int chk2 = num%10; //체크용 변수
if(chk1==3 || chk1==6 || chk1==9) {
System.out.print("짝");
}
if(chk2==3 || chk2==6 || chk2==9) {
System.out.print("짝");
}
else {
System.out.println("땡");
}
}
}
728x90
728x90
'JAVA > Java 기초' 카테고리의 다른 글
배열 연습 1 (1) | 2022.05.13 |
---|---|
배열(Array) (0) | 2022.05.12 |
반복문 (break, continue) (1) | 2022.05.11 |
반복문 (while 문) (0) | 2022.05.10 |
반복문 (for 문) (0) | 2022.05.10 |