Pages

Tuesday, March 29, 2011

Do While Loops (Iteration)

do/while loop

                Syntax:
                                do
                                                {
                                                //loop body
                                                //what instruction to be executed
                                                } while(expression);
               
                Execute first the statement under it prior to the checking of the condition. This assures you of an execution of block of statement at least once. Take note also that the while statement at the end of the loop has a semicolon (;).


Sample problems for do/while loop
               
                Sample 1
Write a program that will display 1 to 10 where each number is separated by a new line (\n or endl).

                #include<iostream>
                using namespace std;

                main ( )
                {
                                int a = 1;

                                do
                                                {
                                                cout<<a<<endl;
                                                a++;
                                                } while(a <=10);
                                return 0;
                }

                Sample 2
Write a program that will ask the user to display the message to the screen. The program will continue to ask until the user enters the key that will terminate the loop and exit the program.
               
                Assumptions:

Message              :               “The cat is biting the dog!”
Exit key                                :               ‘x’

                Sample Solution:
                                #include<iostream>
                                using namespace std;

                                main( )
                                {
                                      char input;
                                      do{
                                      cout<<“Message: The cat is biting the dog!”<<endl;
                                      cout<<”Press anykey to display the message, otherwise press x to exit”;
                                      cin>>input;
                                      }while(input!=’x’);
                                      return 0;
                                         }

No comments:

Post a Comment