for문은 조건식을 통해 일정 횟수를 중심으로 반복하지만 범위기반 for문의 반복횟수는 배열의 요소 개수에 맞추어 자동으로 결정된다.
따라서 코드를 잘못 입력해서 오류가 발생할 가능성이 줄어들게 된다.
기존의 for문
#include <iostream>
using namespace std;
int main(){
int arr[5] = {1, 2, 3, 4, 5};
for(int i = 0; i < 5; i++){
cout << arr[i] << ' ';
}
}
범위기반 for문
for(auto 요소 변수 : 배열이름){
반복구문;
}
#include <iostream>
using namespace std;
int main(){
int arr[5] = {1, 2, 3, 4, 5};
for(auto n : arr)
cout << n << ' ';
}