C++

C++ for, while, do while 루프(Loop) 총정리

김구티2 2024. 3. 14. 20:15

1. 루프(Loop)의 개념

프로그래밍을 하다 보면, 어떤 연산을 n번 수행할 필요가 있다. 이처럼, 루프는 문장 블록을 반복적으로 실행해야 할 때 사용된다. 예를 들어, "Hello Guti"를 10번 프린트하고 싶다고 가정해 본다. 아래와 같이 두 가지 방법으로 프린트할 수 있다:

① 수동방식(반복방식)
수동으로 C++ 문장을 10번 쓰는 것이다. 그런데 10번이 아닌, 20번 써야 한다고 하면? 20개의 문장을 쓰기 위해 시간이 더 걸릴 것이다. 그렇다면 100번을 써야 한다면? 같은 문장을 몇 번이고 다시 쓰는 것은 정말 정신이 없고 귀찮은 일이 될 것이다.

 

예시:

// C++ program to Demonstrate the need of loops
#include <iostream>
using namespace std;

int main()
{
     cout << "Hello Guti\n";
     cout << "Hello Guti\n";

     cout << "Hello Guti\n";

     cout << "Hello Guti\n";

     cout << "Hello Guti\n";

     cout << "Hello Guti\n";

     cout << "Hello Guti\n";

     cout << "Hello Guti\n";

     cout << "Hello Guti\n";

     cout << "Hello Guti\n";
     return 0;
}

 

출력:

Hello Guti

Hello Guti

Hello Guti

Hello Guti

Hello Guti

Hello Guti

Hello Guti

Hello Guti

Hello Guti

Hello Guti

 

② 루프 사용

루프에서 문은 한 번만 작성하면 되고, 루프는 아래와 같이 10번 실행된다. 프로그래밍에서 루프는 특정 조건에 도달할 때까지 반복되는 일련의 명령어라고 할 수 있다.

 

예시:

// C++ program to Demonstrate for loop
#include <iostream>
using namespace std;

int main()
{
     for (int i = 1; i <= 5; i++) {
          cout << "Hello Guti\n";
     }

     return 0;
}

 

출력은 제일 예시와 동일하다.

2. 루프의 유형

루프에는 크게 2가지 유형이 존재한다.

① Entry Controlled loops: 이 유형의 루프에서는 루프 본체에 들어가기 전에 테스트 조건을 테스트한다. for 루프와 while 루프가 이에 속한다.

② Exit Controlled Loops: 이러한 유형의 루프에서는 테스트 조건이 루프 바디의 끝에서 테스트 또는 평가된다. 따라서 테스트 조건이 참인지 거짓인지에 관계없이 루프 바디는 적어도 한 번 실행되는 것이다. '적어도 한 번' 실행된다는 것에서 이미 눈치챘을 테지만, do while 루프가 여기에 속한다.

 

while 루프: 먼저 조건 확인, 이후 바디 실행

for 루프: 먼저 초기화, 다음으로 조건 확인, 이후에 바디 실행하고 업데이트

do while 루프: 먼저 바디 실행, 이후 조건 확인

3. For 루프

For 루프는 반복 제어 구조로 특정 횟수만큼 실행되는 루프를 작성할 수 있다. 이 루프를 사용하면 한 줄에서 n개의 단계를 함께 수행할 수 있다.

 

구문:

for (initialization expr; test expr; update expr)
{    
     // body of the loop
     // statements we want to execute
}

초기화 문: 이 문은 for 루프의 시작 부분에 한 번만 실행된다. int x=0, a=1, b=2와 같은 한 유형의 여러 변수의 선언을 입력할 수 있다. 이 변수들은 프로그래밍 전체가 아닌, 해당 루프의 범위에서만 유효하다. 같은 이름의 루프 앞에 정의된 변수는 루프를 실행하는 동안 숨겨진다.
조건: 이 문은 루프 본문의 각 실행 전에 평가되며, 주어진 조건이 거짓이 되면 실행을 중단한다.
반복 실행: 이 문은 for 루프가 바디에서 중단되지 않는 한, 평가된 다음 조건보다 앞서 루프 바디 이후에 실행된다.

 

예시1:

#include <iostream>
using namespace std;

int main() {

int arr[] {40, 50, 60, 70, 80, 90, 100}; 
     for (auto element: arr){ 
          cout << element << " ";
     }
return 0;

}

 

출력:

40 50 60 70 80 90 100

 

예시2:

#include <iostream>
using namespace std;

int main()
{
     for (int i = 0, j = 10, k = 20; (i + j + k) < 100;
             j++, k--, i += k) {
           cout << i << " " << j << " " << k << "\n";
     }
     return 0;
}

 

출력:

0 10 20
19 11 19
37 12 18
54 13 17

 

예시3:

#include <iostream>
using namespace std;

int main()
{
     int i = 99;
     for (int i = 0; i < 5; i++) {
          cout << i << "\t";
     }
     cout << "\n" << i;
     return 0;
}

 

출력:

0    1    2    3    4    
99

 

예시4:

#include <iostream>
using namespace std;

int main()
{
     int i = 99;
     for (i = 0; i < 5; i++) {
          cout << i << " ";
     }
     cout << "\n" << i;
     return 0;
}

 

출력

0 1 2 3 4

5

4. While 루프

앞에서 루프에 대해 학습하는 동안 우리는 반복 횟수, 즉 루프 바디가 실행되어야 하는 횟수가 미리 알려져 있다는 것을 알았게 됐다. while 루프는 루프의 정확한 반복 횟수를 미리 알 수 없는 상황에서 사용된다. 루프 실행은 테스트 조건에 기초하여 종료된다.

구문:

initialization expression;
while (test_expression)
{
   // statements
 
  update_expression;
}

 

예시:

// C++ program to Demonstrate while loop
#include <iostream>
using namespace std;

int main()
{
     // initialization expression
     int i = 1;

     // test expression
     while (i < 6) {
          cout << "Hello World\n";

          // update expression
          i++;
     }

     return 0;
}

 

출력:

Hello World
Hello World
Hello World
Hello World
Hello World

5. Do While 루프

Do while 루프에서는 테스트 조건을 기반으로 루프 실행이 종료된다. Do while 루프와 while 루프 사이의 주요 차이점은 루프 본체의 끝에서 테스트된다는 것이다. Do while 루프는 테스트 조건에 관계 없이 루프 바디가 적어도 한 번은 실행된다는 점만 잊지 않으면 된다.

구문:

initialization expression;
do
{
   // statements
   update_expression;
} while (test_expression);

 

예시:

// C++ program to Demonstrate do-while loop
#include <iostream>
using namespace std;

int main()
{
     int i = 2; // Initialization expression

     do {
          // loop body
          cout << "Hello World\n";

          // update expression
          i++;

    while (i < 1); // test expression

     return 0;
}

 

출력:

Hello World

 

위 프로그램에서 테스트 조건 (i<1)은 false로 평가된다. 그러나 여전히 do while 문이기 때문에 일단 do가 한 번은 수행되는 것이다.

6. 무한 루프

무한 루프(infinite loop)는 기능적인 출구가 없어서 무한히 반복되는 것이다. 무한 루프는 어떤 조건이 항상 참이라고 평가될 때 발생한다. 그리고 당연하게도, 보통 이것은 오류의 결과다.

 

for문 예시:

// C++ program to demonstrate infinite loops
// using for and while loop

// Uncomment the sections to see the output
#include <iostream>
using namespace std;
int main()
{
     int i;

     // This is an infinite for loop as the condition
     // expression is blank
     for (;;) {
          cout << "This loop will run forever.\n";
     }

     // This is an infinite for loop as the condition
     // given in while loop will keep repeating infinitely
     /*
     while (i != 0)
     {
          i-- ;
          cout << "This loop will run forever.\n";
     }
     */

     // This is an infinite for loop as the condition
     // given in while loop is "true"
     /*
     while (true)
     {
          cout << "This loop will run forever.\n";
     }
     */
}

 

출력:

This loop will run forever.
This loop will run forever.
................... 

 

while문 예시:

#include <iostream>
using namespace std;

int main()
{

     while (1)
          cout << "This loop will run forever.\n";
     return 0;
}

 

출력:

This loop will run forever.
This loop will run forever.
................... 

 

do while문 예시:

#include <iostream>
using namespace std;

int main()
{

     do {
          cout << "This loop will run forever.\n";
    while (1);

     return 0;
}

 

출력:

This loop will run forever.
This loop will run forever.
................... 

7. 감소하는 루프

이번에는 감소하는 루프에 대해 알아보도록 한다. 

 

for문 예시:

#include <iostream>
using namespace std;

int main() {

     for(int i=5;i>=0;i--){
          cout<<i<<" ";
     }
     return 0;
}

 

출력:

5 4 3 2 1 0

 

while문 예시:

#include <iostream>
using namespace std;

int main() {
     //first way is to decrement in the condition itself
     int i=5;
          while(i--){
          cout<<i<<" ";
     }
          cout<<endl;
          //second way is to decrement inside the loop till i is 0
          i=5;
          while(i){
          cout<<i<<" ";
          i--;
     }
     return 0;
}

 

출력:

4 3 2 1 0 
5 4 3 2 1 

 

for, while, do while 예시1:

#include <iostream>
using namespace std;

int main() {
     int i=5;
     do{
          cout<<i<<" ";
     }while(i--);
}

 

출력:

5 4 3 2 1 0

 

do while문 예시2:

#include <iostream>
#include <vector>
using namespace std;

int main() {
     // For loop
     for (int i = 1; i <= 5; i++) {
          cout << "For loop: The value of i is: " << i << endl;
     }

     // While loop
     int j = 1;
     while (j <= 5) {
          cout << "While loop: The value of j is: " << j << endl;
          j++;
     }

     // Do-while loop
     int k = 1;
     do {
          cout << "Do-while loop: The value of k is: " << k << endl;
          k++;
    while (k <= 5);

     // Range-based for loop
     vector<int> myVector = {1, 2, 3, 4, 5};
     for (int element : myVector) {
          cout << "Range-based for loop: The value of element is: " << element << endl;
     }

     return 0;
}

 

출력:

For loop: The value of i is: 1
For loop: The value of i is: 2
For loop: The value of i is: 3
For loop: The value of i is: 4
For loop: The value of i is: 5
While loop: The value of j is: 1
While loop: The value of j is: 2
While loop: The value of j is: 3
While loop: The value of j is: 4
While loop: The value of j is: 5
Do-while loop: The value of k is: 1
Do-while loop: The value of k is: 2
Do-while loop: The value of k is: 3
Do-while loop: The value of k is: 4
Do-while loop: The value of k is: 5
Range-based for loop: The value of element is: 1
Range-based for loop: The value of element is: 2
Range-based for loop: The value of element is: 3
Range-based for loop: The value of element is: 4
Range-based for loop: The value of element is: 5

 

for, while, do while 예시2:

#include <iostream>
using namespace std;

int main() {

     // for loop example
     cout << "For loop:" << endl;
     for(int i = 0; i < 5; i++) {
         cout << i << endl;
     }

     // while loop example
     cout << "While loop:" << endl;
     int j = 0;
     while(j < 5) {
          cout << j << endl;
          j++;
     }

     // do-while loop example
     cout << "Do-while loop:" << endl;
     int k = 0;
     do {
          cout << k << endl;
          k++;
    while(k < 5);

     return 0;
}

 

출력:

For loop:
0
1
2
3
4
While loop:
0
1
2
3
4
Do-while loop:
0
1
2
3
4

 

728x90

'C++' 카테고리의 다른 글

C++ 함수(functions) 총정리  (0) 2024.03.16
C++ 범위 기반 for문 총정리  (0) 2024.03.14
C++ 점프문 총정리  (1) 2024.03.14
C++ 스위치 문 총정리  (1) 2024.03.12
C++ Nested if문(중첩 if문) 총정리  (0) 2024.03.10