for(변수선언 및 초기화 가능 , 조건 , 변수증가값){
}
for안에서 선언 및 초기화 한것은
for문을 나왔을때 사라진다
예를들어 for(int a=0; a<10; a++){}
이라하면 for문 안에서는 a가 작동하지만
나오면 없는사람됨
public class Example {
public static void main(String[] args) {
// 반복실행문(=반복수행문) : 특정 조건이 만족하는동안 반복실행하는 문장
// for~, while~, do ~while (자바,자바스크립트,C동일)
// 반복실행문 부터는 로직이라함
// 알고리즘은 로직을 갖고 뭔가를 설계(해결하기위해)
//for(i=0; i<=10; i++){} == for(초기값, 조건식, 증감식)
int i=0;
int sum=0;
boolean b=true;
while(b){
if(i<=10){
sum+=i;
System.out.println(i);
i++;//카운트변수
}else{
System.out.println(sum+"\n");
b=false;
}
}
sum=0;
for(int n=0; n<=100; n+=2){//i :지역변수 여기 안에서만 유효
sum+=n;
} System.out.println(sum); //0~100까지 짝수의합계
//==위아래는 같은식이나 위에는 50번만 더하면돼서 위에값이 더 빠름
sum=0;
for(int n=0; n<=100; n++){
if (n % 2 == 0 ) sum+=n;
}System.out.println(sum);
sum=0;
for(int n=1; n<=100; n+=2){
sum+=n;
}System.out.println(sum);//홀수의합계
sum=0;
for(int n=0; n<=100; n++){
if (n % 2 != 0 ) sum+=n;
}System.out.println(sum);//홀수의합계
}
}
public class Example {
public static void main(String[] args) {
//바깥 for문은 안의for문이 모두 실행되면 그때 다시 실행된다
//(카운트가 증가되고) 안의 for문은 초기화돼서 다시 시작
//ex ) (0,0) (0,1) (0,2) (1,0) (1,1) (1,2)
//해당 데이터마다 끄집어내서 반복수행하는것을 배열
for(int a=0; a<9; a++){ //배열예제 //줄
//배열은 이중for문으로 반복실행문써야함
for(int b=0; b<5; b++){ //칸
System.out.print(a+", "+b+"\t");
}
System.out.println();
}
/*
*
**
***
****
위 모양이 출력되도록 중첩 for문을 활용하여 프로그램하시오.
*/
for(int q=0; q<5; q++){
for(int p=q; p<4; p++){
System.out.print("*");
}
System.out.println();
}
//정답
for(int q=1; q<=4; q++){
for(int p=1; p<=5-q; p++){
System.out.print("*");
}
System.out.println();
}
System.out.println();
//또다른답안
for(int q=4; q>=1; q--){
for(int p=1; p<=q; p++){
System.out.print("*");
}
System.out.println();
}
System.out.println();
//반대로
for(int q=4; q>=1; q--){
for(int p=1; p<=5-q; p++){
System.out.print("*");
}
System.out.println();
}
//또 다른답안
for(int q=0; q<5; q++){
for(int p=1; p<=q; p++){
System.out.print("*");
}
System.out.println();
}
}
}
public class Example3 {
public static void main(String[] args) {
//99단(2~9단까지)
for(int x=2 ; x<10; x++){
for(int y=1; y<10; y++){
System.out.printf("%d*%d=%d\n",x,y,x*y);
}
}
//가로배열로
for(int x=2 ; x<10; x++){
for(int y=1; y<10; y++){
System.out.printf("%d*%d=%d\t",x,y,x*y);
}System.out.println();
}
System.out.println();
//다른방식 가로배열로
for(int x=1 ; x<10; x++){
for(int y=2; y<10; y++){
System.out.printf("%d*%d=%d\t",y,x,y*x);
}System.out.println();
}
}