https://www.youtube.com/watch?v=Bm5vp5XwzDU&list=PLgqG2uj21HgkcfVtlr5rPekQl5VWJEnIB&index=18
반복문을 활용할 수 있는 방법은 배열을 사용하는 방법이다. 기존 방식으로 배열을 출력하려면 아래의 코드처럼 작성을 해야한다. 하지만 배열의 값만큼 for문 안의 조건에 넣어주어야한다는 단점이 있다.
#include <iostream>
int main(){
using namespace std;
int a[5] = {1, 3, 5, 7, 9};
for (int i = 0; i<5; i++){
cout << a[i] << endl;
}
return 0;
}
c++에서는 아래의 코드처럼 작성을해도 배열을 출력할 수 있고, 이 반복문을 배열기반 반복문이라고 한다.
#include <iostream>
int main(){
using namespace std;
int a[5] = {1, 3, 5, 7, 9};
for(int i :a){
cout << i << endl;
}
return 0;
}
중첩 루프는 2차원 배열을 작성할 때 많이 사용된다.
#include <iostream>
int main(){
using namespace std;
int temp[4][5] =
{
{1,2,3,4,5},
{6,7,8,9,10},
{11,12,13,14,15},
{16,17,18,19,20},
};
for (int row = 0; row < 4; row++){
for(int col = 0; col <5; col++){
cout << temp[row][col]<<" ";
}
cout << "\\n";
}
}