for문을 작성하는 법
1.for를 적고 소괄호를 열고 닫고 중괄호를 열고 닫는다
2.소괄호 안을 구성해야 하는데
처음은 초기화 구간이다
중간은 조건 구간이다
마지막은 증감부 구간이다
초기화 구간은 for문 진입시 최초 한 번만 실행된다
초기화 하고 싶은 값을 초기화 구간에 작성한다
조건 구간은 while에서 작성하던 조건과 동일하다
증감부는 while에서 num++,num– 하던 부분이다
중괄호 내부에는 반복시킬 코드를 작성한다
문제로 풀어보며 구조를 파악해보자
3~20까지 출력
for (int i = 3; i <= 20; i++) {
System.out.print(i + " ");
cnt++;
}
1~10까지 2의 배수만 출력
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
System.out.print(i + " ");
}
}
0~-19까지 출력
//-19부터 출력
for (int i = -19; i <= 0; i++) {
System.out.print(i+" ");
}
System.out.println();
//0부터 출력
for (int i = 0; i >= -19; i--) {
System.out.print(i + " ");
}
피보나치 수열(양쪽의 값을 더해서 그다음 값을 더하는 방식)
int a = 0;//왼쪽값 저장
int b = 1;//오른쪽값 저장
int c;//둘이 더한값
for (int i = 0; i <= 20; i++) {
c = a + b;
System.out.print(c+" ");
a = b;//값을 오른쪽에서 왼쪽으로 이동시키는 로직
b = c;
}
1, 1, 3, 4, 5, 8, 12, 17, 25, 37, 54, …
위와 같은 숫자의 나열이 있다.
30번째 숫자는 무엇일지 프로그래밍
int first = 1, second = 1, third = 3;
int loop = 8;
int res = 0;
for(int i = 0; i < loop - 3; i++) {
res = first + third;
first = second;
second = third;
third = res;
}
System.out.printf("%d 번째 항은 = %d\n", loop, res);
(추후 보수예정)위에 문제를 순서대로 출력하기
/*
연습 문제 5.
1, 1, 3, 4, 5, 8, 12, 17, 25, 37, 54, ...
위와 같은 숫자의 나열이 있다.
30번째 숫자는 무엇일지 프로그래밍해보자!
*/
int first = 1;
int second = 1;
int third = 3;
int loop = 30;
int cnt = 0;
int total = 0;
for (int i = 0; i < 15; i++) {
total = first + third;
System.out.print(first + " " + second);
cnt += 2;
if (cnt == 30) {
break;
}
System.out.print(third + " " + total + " ");
first = second + total;
second = third + first;
third = total + second;
}
구구단 만들기
for문의 특징
1.초기화는 최초 진입시 한번만
2.조건을 검사하고 반복후 증감
3.조건만 만족된다면 2번 작업을 반복
int i, j;
// 초기 시작 i = 2
// 첫번째 내부 루프가 끝나고 i = 3
// i = 4 ... 9
for(i = 2; i < 10; i++) {
// 내부 루프 초기 시작 j = 1
// 내부 루프 j = 2
// 내부 루프 j = 3
// .......
// 내부 루프 j = 9
// 내부 루프 j = 10
for(j = 1; j < 10; j++) {
System.out.printf(
"%2d x %2d = %2d\n", i, j, i * j);
}
System.out.println("");
}
랜덤
Math.random()을 이용한 랜덤숫자 출력(실수)
System.out.printf(
"0.0 ~ 1.0 사이의 랜덤 = %f\n",
Math.random());
System.out.printf(
"0 ~ 10 사이의 랜덤 = %d\n",
(int)(Math.random() * 10));
System.out.printf(
"0 ~ 100 사이의 랜덤 = %d\n",
(int)(Math.random() * 100));
Random 클래스를 이용한 랜덤숫자 출력(정수)
Random rand = new Random();
for(int i = 0; i < 10; i++) {
// Random 클래스의 nextInt()는 0 부터 시작해서
// 소괄호 안에 있는 개수까지를 범위로 잡는다.
// 2 - 0, 1
// 10 - 0, 1, 2, ... , 9
// 6 - 0, 1, ... , 5
// 6 - 0 ~ 5
// - 1 ~ 6
System.out.printf(
"%d\n", rand.nextInt(6) + 1);
}
for문을 이용한 무한루프
//세미콜론만 포함시킨다
for(;;) {
System.out.println("끝나지 않아");
}
for문 무한루프를 이용하여 주사위게임
/*
연습 문제
이 주사위 놀이는 홀수가 나오면 주사위를 한번 더 굴릴수 있다
모든 주사위가 굴려졌을때
최종 합계
*/
Random ran = new Random();
int cnt = 0;
int t = 0;
for (; ; ) {
int n = ran.nextInt(6) + 1;
if (cnt == 0) {
try {//시간 조절
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
if (n % 2 == 0) {
System.out.println(n + "은 짝수이므로 종료");
cnt = 1;
} else if (n % 2 == 1) {
System.out.println(n + "은 홀수 이므로 다시 뽑는다");
t += n;
System.out.println("총합" + t);
}
} else if (cnt == 1) {
System.out.println("종료 하겠습니다");
break;
}
}
연습문제
/*
현재 은행의 이자율이 2.3%다
은행은 매년 이자율을 변동하고 있다
이자율의 변동폭은 -0.7~0.7정도 이다
현재 수중에 들고 있는 돈은 1000만원이다
이 금액을 3년동안 관리한다고 가정
최종 금액은 얼마가 되는지
*/
Random ran = new Random();
float scale, money = 10000000.0f, defScale = 2.5f;
for(int i = 0; i < 3; i++) {
scale = defScale + (ran.nextFloat() * 1.4f - 0.7f);
System.out.printf(
"scale = %f\n", scale);
// 원금 + 원금 * 스케일 / 100
money = money + money * scale / 100.0f;
}
System.out.printf("최종 금액은 %f", money);