C++ while và do … while Loop

Trong hướng dẫn này, chúng ta sẽ học cách sử dụng vòng lặp while và do … while trong lập trình C ++ với sự trợ giúp của một số ví dụ.

Trong lập trình máy tính, các vòng lặp được sử dụng để lặp lại một khối mã.

Ví dụ: giả sử chúng ta muốn hiển thị một tin nhắn 100 lần. Sau đó, thay vì viết câu lệnh in 100 lần, chúng ta có thể sử dụng một vòng lặp.

Đó chỉ là một ví dụ đơn giản; chúng tôi có thể đạt được nhiều hiệu quả và tinh vi hơn trong các chương trình của mình bằng cách sử dụng hiệu quả các vòng lặp.

Có 3 loại vòng lặp trong C ++.

  1. for vòng
  2. while vòng
  3. do...while vòng

Trong hướng dẫn trước, chúng ta đã tìm hiểu về vòng lặp for trong C++ . Ở đây, chúng ta sẽ tìm hiểu về whilevà do...whilelặp lại.

C ++ trong khi Vòng lặp

Cú pháp của whilevòng lặp là:

while (condition) {
    // body of the loop
}

Đây,

  • while loop evaluates the condition
  • If the condition evaluates to true, the code inside the while loop is executed.
  • The condition is evaluated again.
  • This process continues until the condition is false.
  • When the condition evaluates to false, the loop terminates.

Để tìm hiểu thêm về conditions, hãy truy cập Các toán tử quan hệ và logic trong C ++ .

Lưu đồ về Vòng lặp trong khi

Lưu đồ của vòng lặp while trong C ++

Ví dụ 1: Hiển thị các số từ 1 đến 5

// C++ Program to print numbers from 1 to 5

#include <iostream>

using namespace std;

int main() {
    int i = 1; 

    // while loop from 1 to 5
    while (i <= 5) {
        cout << i << " ";
        ++i;
    }
    
    return 0;
}

Đầu ra

1 2 3 4 5

Đây là cách chương trình hoạt động.

IterationVariablei <= 5Action
1sti = 1true1 is printed and i is increased to 2.
2ndi = 2true2 is printed and i is increased to 3.
3rdi = 3true3 is printed and i is increased to 4
4thi = 4true4 is printed and i is increased to 5.
5thi = 5true5 is printed and i is increased to 6.
6thi = 6falseThe loop is terminated

Ví dụ 2: Chỉ tổng các số dương

// program to find the sum of positive numbers
// if the user enters a negative number, the loop ends
// the negative number entered is not added to the sum

#include <iostream>
using namespace std;

int main() {
    int number;
    int sum = 0;

    // take input from the user
    cout << "Enter a number: ";
    cin >> number;

    while (number >= 0) {
        // add all positive numbers
        sum += number;

        // take input again if the number is positive
        cout << "Enter a number: ";
        cin >> number;
    }

    // display the sum
    cout << "\nThe sum is " << sum << endl;
    
    return 0;
}

Đầu ra

Enter a number: 6
Enter a number: 12
Enter a number: 7
Enter a number: 0
Enter a number: -2

The sum is 25

Trong chương trình này, người dùng sẽ được nhắc nhở để nhập một con số, được lưu trữ trong các biến số .

Để lưu trữ tổng các số, chúng ta khai báo một biến tổng và khởi tạo nó với giá trị là 0.

Các whilevòng lặp tiếp tục cho đến khi người dùng nhập vào một số âm. Trong mỗi lần lặp, số do người dùng nhập được thêm vào biến tổng .

Khi người dùng nhập một số âm, vòng lặp kết thúc. Cuối cùng, tổng tổng được hiển thị.

C ++ do … while Loop

Các do...whilevòng lặp là một biến thể của whilevòng lặp với một sự khác biệt quan trọng: cơ thể của do...whilevòng lặp được thực hiện một lần trước khi conditionđược kiểm tra.

Cú pháp của nó là:

do {
   // body of loop;
}
while (condition);

Đây,

  • The body of the loop is executed at first. Then the condition is evaluated.
  • If the condition evaluates to true, the body of the loop inside the do statement is executed again.
  • The condition is evaluated once again.
  • If the condition evaluates to true, the body of the loop inside the do statement is executed again.
  • This process continues until the condition evaluates to false. Then the loop stops.

Lưu đồ vòng lặp do … while

Lưu đồ của C ++ vòng lặp do … while

Ví dụ 3: Hiển thị các số từ 1 đến 5

// C++ Program to print numbers from 1 to 5

#include <iostream>

using namespace std;

int main() {
    int i = 1; 

    // do...while loop from 1 to 5
    do {
        cout << i << " ";
        ++i;
    }
    while (i <= 5);
    
    return 0;
}

Đầu ra

1 2 3 4 5

Đây là cách chương trình hoạt động.

IterationVariablei <= 5Action
i = 1not checked1 is printed and i is increased to 2
1sti = 2true2 is printed and i is increased to 3
2ndi = 3true3 is printed and i is increased to 4
3rdi = 4true4 is printed and i is increased to 5
4thi = 5true5 is printed and i is increased to 6
5thi = 6falseThe loop is terminated

Ví dụ 4: Chỉ tổng các số dương

// program to find the sum of positive numbers
// If the user enters a negative number, the loop ends
// the negative number entered is not added to the sum

#include <iostream>
using namespace std;

int main() {
    int number = 0;
    int sum = 0;

    do {
        sum += number;

        // take input from the user
        cout << "Enter a number: ";
        cin >> number;
    }
    while (number >= 0);
    
    // display the sum
    cout << "\nThe sum is " << sum << endl;
    
    return 0;
}

Đầu ra 1

Enter a number: 6
Enter a number: 12
Enter a number: 7
Enter a number: 0
Enter a number: -2

The sum is 25

Ở đây, do...whilevòng lặp tiếp tục cho đến khi người dùng nhập một số âm. Khi số âm, vòng lặp kết thúc; số âm không được thêm vào sumbiến.

Đầu ra 2

Enter a number: -6
The sum is 0.

Phần nội dung của do...whilevòng lặp chỉ chạy một lần nếu người dùng nhập một số âm.

Vòng lặp while vô hạn

Nếu conditionluôn luôn là vòng lặp true, vòng lặp sẽ chạy trong khoảng thời gian vô hạn (cho đến khi bộ nhớ đầy). Ví dụ,

// infinite while loop
while(true) {
    // body of the loop
}

Đây là một ví dụ về do...whilevòng lặp vô hạn .

// infinite do...while loop

int count = 1;

do {
   // body of loop
} 
while(count == 1);

Trong các chương trình trên, conditionluôn luôn là true. Do đó, phần thân của vòng lặp sẽ chạy trong thời gian vô hạn.

vòng lặp for vs while

Một forvòng lặp thường được sử dụng khi số lần lặp được biết đến. Ví dụ,

// This loop is iterated 5 times
for (int i = 1; i <=5; ++i) {
   // body of the loop
}

Ở đây, chúng ta biết rằng vòng lặp for sẽ được thực thi 5 lần.

Tuy nhiên, whilevà do...whilevòng lặp thường được sử dụng khi số lần lặp không xác định. Ví dụ,

while (condition) {
    // body of the loop
}








Gõ tìm kiếm nhanh...