형식
for (초기화식; 조건식; 증감식){
수행문...;
...
}
예를 들어, 1부터 10까지 합을 구하는 코드를 작성해보면
int sum = 0;
for (int i = 1; i <= 10; i++){ //i를 1부터 10까지 1씩 증가시킴.
sum += i; //sum = sum + i sum변수에 i를 계속 더해줌.
}
이렇게 작성할 수 있음.
이때 초기화식에서 int i를 괄호 밖에서 미리 선언하고 i = 1; 이렇게만 초기화식에 작성할 수 있음.
백준 코드 작성
* 백준 2739번 : 구구단.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
sc.close();
for (int i = 1; i < 10; i++) {
System.out.println(N + " * " + i + " = " + N * i);
}
}
}
i를 1부터 10까지 범위를 출력하고, 구구단식을 출력함.
* 백준 2438번 : 별 찍기.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
sc.close();
for(int i = 1; i <= T; i++) {
for(int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println(); // 줄 바꿈 코드를 구현하지 않으면 별이 모두 한 줄에 출력됨.
}
}
}
이중 for문을 사용하여 i가 1일 경우 j의 범위도 1까지 하는 조건을 작성하여 i의 증가만큼 별의 개수도 증가하게 코드를 작성함.
* 백준 2741번 : 1부터 N까지 하나씩 출력하기.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
sc.close();
for(int i = 1; i <= N; i++) {
System.out.println(i);
}
}
}
* 백준 11021번 : A와 B를 입력받아 합 구하기.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int i = 1; i <= T; i++) {
int A = sc.nextInt(); //A와 B를 입력받는 코드를 for문 안에 작성해야 반복문이 실행되는 동안 계속 값을 받을 수 있음.
int B = sc.nextInt();
System.out.println("Case #" + i + ": " + ((int)A+(int)B));
}
sc.close();
}
}
다음 글에서는 break, continue, switch에 대해 설명하겠습니다.
감사합니다!
2021.06.30
'JAVA' 카테고리의 다른 글
flag 변수 (0) | 2021.07.02 |
---|---|
break / continue / switch - case문 (0) | 2021.07.01 |
while /do - while 반복문 (0) | 2021.06.29 |
if - else 반복문 문제 풀이 (0) | 2021.06.29 |
if / if - else 조건문 (0) | 2021.06.28 |