본문 바로가기
c++ 기초

10) 반복문, 중첩 배열

by BitsrimAcrux 2024. 12. 28.

for문 c랑 같음

#include <iostream>

using namespace std;

int main() {
	for (int i = 0; i < 5; i++) {
		cout << i << " "; // -> 0 1...4
	}
    
    // c++에서만 가능
    char a[] ="apple";
    for (int i : a) { // 첫 번째 i는 a를 가리킴
		cout << i << " "; // -> a p p l e
	}

	return 0;
}

while문 c랑 같음

#include <iostream>

using namespace std;

int main() {
	int i = 0;
    while (i < 3) {
    	cout << i << " "; -> 0 1 2
        i++;
    }

	return 0;
}

do-while문 c랑 같음 : 무조건 1번 실행 후 조건에 따

#include <iostream>

using namespace std;

int main() {
    char a[] = "apple";
    int i = 0;
    do {
        cout << a[i] << " "; //-> a p p l e
        i++;
    } while (a[i] != '\0');

    return 0;
}

중첩 배열

#include <iostream>

using namespace std;

int main() {
    int temp[2][3] = { {1, 2, 3},
                       {4, 5, 6} };

    for (int row = 0; row < 2; row++) {
        for (int col = 0; col < 3; col++) {
            cout << temp[row][col] << " ";
        }
        cout << endl;
    }
    return 0;
}
728x90

'c++ 기초' 카테고리의 다른 글

12) 함수  (0) 2024.12.29
11) 조건문  (0) 2024.12.29
9) new 이용 동적 구조체  (0) 2024.12.28
8) 포인터, new와 delete 연산자, 포인터 배열  (0) 2024.12.28
7) 공용체, 열거체  (0) 2024.12.28