Page 280 - Computer_Science_F5
P. 280

condition is tested. For example, when  The  following C++ Program  Example
              you look for your favorite food at the  4.25 demonstrates the use of do…while
              restaurant. First, you will go, and if the  loop. The output is shown in Figure 4.49.
              food is attractive, you will continue to
              go. Otherwise, you will quit and go to         Program Example 4.25:                 Chapter Four: Object oriented programming with C++
          FOR ONLINE READING ONLY
              another restaurant. The syntax of the do-  The use of do-while loop
              while loop is given as:
                     do {
                                                           #include<iostream>
                     // The statement will be executed
                     once even if the condition is         using namespace std;
                     false.                                int main()
                     Statement(s);                         {

                     }                                            int sum = 0;
                                                                  int i = 0;
                     while(loop condition);
                                                           do
              Figure 4.48 shows  the execution             {
              flowchart of the do-while loop.                     sum+=i;
                                                                  cout<<”Enter an integer: “;
                                                                  cin>>i;
                                                           }
                                                           while(i!=0);
                                                           cout<<”The sum is “<<sum<<endl;
                                Statement (s)              return 0;
                                 (loop body)
                    True                                   }
                                                         Output:



                                    Loop
                                  condition

                                         False




               Figure 4.48: do-while loop flowchart      Figure 4.49: Output of the program











                                                    271
               Student’s Book  Form Five



     Computer Science Form 5.indd   271                                                     23/07/2024   12:34
   275   276   277   278   279   280   281   282   283   284   285