-
C++ 반복문 (2)C++ 2025. 3. 21. 15:52
이번엔 while 루프와 do while 루프에 대해 공부할 것이다.
int main() { int i =0; while (i < 3) { i++; } return 0; }
while문도 for문과 마찬가지로 true, false로 구분한다. 괄호 속의 조건문이 true일 경우 계속 반복하고, false가 됐을때 while문을 벗어나게 된다. 위 코드는 i는 0, 1, 2까지 실행된 후 탈출한다.
#include <iostream> using namespace std; int main() { string str = "Hong"; int i =0; while (str[i] != '\0') { cout << str[i] << endl; i++; } return 0; }
위 코드를 보면 "Hong"이란 문자열을 str 변수에 초기화했다. 이런 string 타입으로 선언할 경우 문자열의 마지막 자리엔 자동으로 '\0' 널문자가 들어간다. Hong은 배열로써도 사용할 수 있기 때문에 str[0]에는 H, str[1]은 o, str[2]는 n, str[3]에는 g가 들어가고, str[4]에 '\0' 문자가 들어간다. 따라서 다음과 같은 결과가 출력된다.
do while문의 특징은 반복을 실행하고 조건을 검사한다.
int main() { int j = 0; do { cout << "while문입니다.\n"; j++; } while (j < 3); return 0;
#include <iostream> using namespace std; int main() { int a[5] = {1,3,5,7,9}; for (int i=0; i <5; i++) { cout << a[i]; } cout << "\n"; for (int i : a) { cout << i; } return 0; }
배열 기반 반복문을 int i : a 라는 방식으로도 표현할 수 있다.
그러나 배열의 크기가 원소의 값보다 클 경우, 출력값에서 빈자리는 모두 0으로 출력된다는 사실이다.
중첩 루프는 2차원 배열을 사용해서 나타낼 수 있다.
#include <iostream> using namespace std; int main() { int temp[4][5]; for (int row = 0; row <4; row++) { for (int col = 0; col < 5;col++) { cout << temp[row][col] << endl; } } return 0; }
'C++' 카테고리의 다른 글
C++ 함수 (1) (0) 2025.03.21 C++ if구문과 if else 구문 , switch 구문과 break/continue (0) 2025.03.21 C++ 반복문 (1) (0) 2025.03.20 C++ 포인터 연산 (0) 2025.03.18 C++ 포인터와 메모리 해제 (2) (0) 2025.03.18