본문 바로가기
개발일지/임시카테고리

dart(다트) - loop(루프) (for, do, while)

by 다니엘의 개발 이야기 2025. 3. 21.
320x100

#1 for loop의 기본형태

 

가장 중요한 것은 for 옆에 기술되는

어떤 조건; 언제까지 실행?; 1회 루프 실행시 어디까지 할거야? {

   과정;

}

이라고 판단 된다.

 

void main() {
  // for loop
  
  // 어떤 조건; 언제까지 실행?; 1회 루프 실행시, 어떻게 할거야?
  for (int i = 0; i < 10; i++) {
    print(i);
  }
  
  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);
  // 21
  
  // 초기화
  print('init');
  total = 0;
  
  for (int number in numbers) {
    print(number);
    total += number;
  };
  
  print(total);
  // 21
}

#2 while loop의 기본 형태

 

while loop의 포인트는

while(어떤 조건) {실행되는 내용}이다.

void main() {
  // while loop
  
  int total = 0;
  
  // (어떤조건) {실행되는 내용}
  while(total < 10) {
    total += 1;
  }
  
  print(total);
  // 10
  
  // 초기화
  total = 0;
  print('init $total');
  // init 0
}
void main() {
  for (int i = 0; i < 10; i++){
    if(i == 5){
      continue;
    }
    print(i);
    // 0부터 9까지 출력 되지만, 위의 if (i == 5)에 대한 실행문이 continue라
    // 5는 출력 안됨
  }
}
300x250