반복문

shin·2022년 8월 26일
0

Dart

목록 보기
14/20

for

void main() {
  //for loop
  for(int i = 0; i < 10; i++){
    print(i);
  }
}

()안에 3가지 조건을 설정한다.

  • 먼저 변수를 정해준다. => int i = 0
  • 언제까지 이 반복문을 실행할 건지를 설정 해준다. => i < 10
  • 한 번 반복문이 실행될때 어떤 변화를 줄지 정한다. => i++

활용

void main() {
  //for loop
  int total  = 0;
  
  List<int> numbers = [1, 2, 3, 4, 5, 6];
  
  for(int i = 0; i < numbers.length; i++){
    total += numbers[i];
  }
  
  print(total);
  
  리스트에 있는 값들을 하나씩 꺼내 총합을 구하는 for 문이다.
  
  for in 을 사용해서 다른 방식으로 작성할 수 있다.
  
  total = 0;
  
  for(int number in numbers){
    total += number;
  }
  
  print(total);
}

while

void main(){
  
  int total = 0;
  
  while(total < 10){
    total += 1;
  }
  
  print(total);
}
  • while문 작성 시 주의해야 할 점은 ()안에 들어갈 조건이 실행 가능해야 한다.
    만약 total < 10 말고 total < -1 로 설정하면 무한 loop에 빠지게 된다.

break

void main(){
  
  int total = 0;
  
  while( total < 10){
    total += 1;
    
    if(total == 5 ){
      break;
    }     
  }
  
  print(total);
  
}

=> 5
  • break를 사용하면 그 조건을 만족하면 반복문이 끝나게 된다.

continue

void main(){
    
  for(int i = 0; i < 10; i++){
    if(i == 5){
      continue;
    }
    print(i);
  }
}

0
1
2
3
4
6
7
8
9
  • continue는 현재 loop만 건너뛰고 실행할 때 사용한다.

enum

enum Status{
  approved, //승인
  pending, //대기
  rejected, //거절
}

void main(){
  Status status = Status.approved;
  
  if(status == Status.approved){
    print('승인');
  }else if(status == Status.pending){
    print('대기');
  }else{
    print('거절');
  }
}
  • enum은 특정 상황에서 사용되는 것끼리 묶어 놓은 것이다.

0개의 댓글