Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Tham khảo tài liệu 'thinking in c plus plu (p4)', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | while while do-while and for control looping. A statement repeats until the controlling expression evaluates to false. The form of a while loop is while expression statement The expression is evaluated once at the beginning of the loop and again before each further iteration of the statement. This example stays in the body of the while loop until you type the secret number or press control-C. C03 Guess.cpp Guess a number demonstrates while include iostream using namespace std int main int secret 15 int guess 0 is the not-equal conditional while guess secret Compound statement cout guess the number cin guess cout You guessed it endl The whilef s conditional expression is not restricted to a simple test as in the example above it can be as complicated as you like as long as it produces a true or false result. You will even see code where the loop has no body just a bare semicolon while Do a lot here In these cases the programmer has written the conditional expression not only to perform the test but also to do the work. 130 Thinking in C www. BruceEckel .com do-while The form of do-while is do statement while expression The do-whileis different from the while because the statement always executes at least once even if the expression evaluates to false the first time. In a regular whiles if the conditional is false the first time the statement never executes. If a do-while is used in Guess.cpp the variable guess does not need an initial dummy value since it is initialized by the cin statement before it is tested C03 Guess2.cpp The guess program using do-while include iostream using namespace std int main int secret 15 int guess No initialization needed here do cout guess the number cin guess Initialization happens while guess secret cout You got it endl For some reason most programmers tend to avoid do-while and just work with while for A for loop performs initialization before the first iteration. Then it performs conditional testing and at the end of each iteration