C++ While ループ
C++ の While ループ ループの正確な反復回数が事前にわからない状況で使用されます。テスト条件に基づいてループの実行が終了します。 C++ のループ ステートメントのブロックを繰り返し実行する必要がある場合に使用されます。の研究中に、 C++ の「for」ループ 、反復回数が事前にわかっていること、つまりループ本体を実行する必要がある回数がわかっていることがわかりました。
構文:
while (test_expression) { // statements update_expression; } さまざまな While ループの一部 は:
- テスト式: この式では、条件をテストする必要があります。条件が true と評価された場合、ループの本体が実行され、式の更新に進みます。それ以外の場合は、while ループから抜けます。 Update Expression : ループ本体の実行後、この式はループ変数をある値ずつ増減します。本文: これは、変数、関数などが含まれるステートメントのグループです。 while ループを使用すると、コードや単純な名前を出力したり、複雑なアルゴリズムを実行したり、関数操作を実行したりできます。
While ループはどのように実行されるのでしょうか?
- 制御は while ループに入ります。
- フローは条件にジャンプします
- 状態はテスト済みです。
- Condition が true の場合、フローは Body に入ります。
- 条件が false を返した場合、フローはループの外に出ます。
- ループ本体内のステートメントが実行されます。
- 更新が行われます。
- 制御はステップ 2 に戻ります。
- while ループが終了し、フローが外側に出ました。
while ループのフロー図
例 1: このプログラムは、いくつかの条件に応じて Hello World を 5 回出力しようとします。
C++
// C++ program to illustrate while loop> > #include> using> namespace> std;> > int> main()> {> > // initialization expression> > int> i = 1;> > > // test expression> > while> (i <6) {> > cout < <> 'Hello World
'> ;> > > // update expression> > i++;> > }> > > return> 0;> }> |
出力:
Hello World Hello World Hello World Hello World Hello World
例 1 のドライラン:
1. Program starts. 2. i is initialized with value 1. 3. Condition is checked. 1 <6 yields true. 3.a) 'Hello World' gets printed 1st time. 3.b) Updation is done. Now i = 2. 4. Condition is checked. 2 < 6 yields true. 4.a) 'Hello World' gets printed 2nd time. 4.b) Updation is done. Now i = 3. 5. Condition is checked. 3 < 6 yields true. 5.a) 'Hello World' gets printed 3rd time 5.b) Updation is done. Now i = 4. 6. Condition is checked. 4 < 6 yields true. 6.a) 'Hello World' gets printed 4th time 6.b) Updation is done. Now i = 5. 7. Condition is checked. 5 < 6 yields true. 7.a) 'Hello World' gets printed 5th time 7.b) Updation is done. Now i = 6. 8. Condition is checked. 6 < 6 yields false. 9. Flow goes outside the loop to return 0.
例 2:
C++
// C++ program to illustrate while loop> > #include> using> namespace> std;> > int> main()> {> > // initialization expression> > int> i = 1;> > > // test expression> > while> (i>-5) {>> > cout < < i < <> '
'> ;> > > // update expression> > i--;> > }> > > return> 0;> }> |
出力:
1 0 -1 -2 -3 -4