2-1. for문
for 문은 정해진 횟수만큼 반복할 때 사용하는 반복문이다.
기본구조
for ( 초기식 ; 조건식; 증감식 ){
반복할 문장;
}
for문 예제
public class FoorExample1 {
public static void main(String[] args) {
for (int i = 0; i <5; i++) {
System.out.println("i의 값은 : " + i);
}
}
}

1 부터 10까지 정수의 합을 구하는 프로그램
public class Sum {
public static void main(String[] args) {
int sum = 0;
for (int i = 0; i <= 10; i++)
sum += i;
System.out.println("Sum of integers from 1 to 10 : " + sum);
}
}

정숫값을 입력받아 팩토리얼 값구하는 프로그램
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
long fact =1;
int n;
System.out.print("Enter an integer : ");
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
for (int i = 1; i <= n; i++) // i = 1 부터 n보다 크거나 작지 않을 때 까지 +1
fact = fact * i; // fact에 i값을 곱한 값을 넣기
System.out.printf("%d! is %d.\n", n, fact);
}
}


양의 정수를 입력받아 그 정수의 모든 약수를 출력하는 프로그램
import java.util.Scanner;
public class Divisor {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a positive integer : ");
int n = sc.nextInt();
System.out.println("The divisor of " + n + " is");
for (int i = 1; i <= n ; i++) {
if (n % i == 0)
System.out.print(i + " " );
}
}
}

2-2. while문
while문 어떤 조건을 정하고 반복시키는 반복문이다.
기본구조
while (조건식){
}
Welcome을 반복하는 프로그램
public class WelcomeLoop {
public static void main(String[] args) {
int i = 0;
while (i < 5){
System.out.println("Welcome!!!");
i ++;
}
System.out.println("The Loop has ended");
}
}

사용자가 -1을 입력할 때까지 입력한 정수의 합출력하는 프로그램
import java.util.Scanner;
public class GetSum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int sum = 0, value = 0;
while (value != -1) {
sum = sum + value;
System.out.print("Enter an integer : ");
value = sc.nextInt();
}
System.out.println("The sum of integers is " + sum);
}
}

Share article