Basic HTML Version

|  | Table of Contents |  | View Full Version

Page 159 - CoreGPT(Podar)_Flipbook_C8
P. 159

    The while loop can accept expressions, not just conditions. The following are all valid expressions:

                     while(x = x + 1)   // Assigns a new value to x and loops indefinitely
                     while(n--) // Decrements n and continues looping while n is non-zero
                     while(count += i) //  Adds i to count and loops while the result is non-zero
                     Program 4: To input any number and print it in reverse order using while loop. The input number

                     must be positive.
                     #include<iostream.h>

                     #include<conio.h>
                     void main()
                                                           Enter a positive number to be reversed: -987
                     {
                                                           The number must be positive. Please enter again:
                         clrscr();
                         long int n, digit;
                         cout<< "Enter a positive number to be reversed: ";
                         cin>> n;
                         while(n <= 0)                     Enter a positive number to be reversed: 12345
                                                           The reverse of the number 12345 is: 54321_
                         {
                             cout<< "The number must be positive. Please enter again: ";
                             cin>> n;
                         }
                         cout<< "The reverse of the number " << n << " is: ";
                         while(n > 0)

                         {
                             digit = n % 10;
                             cout<< digit;
                             n = n / 10;
                         }

                         getch();
                     }
                              Tech Funda

                           If you want to execute just one statement in the body of the while loop, you do not have
                           to enclose the statement in braces.

                     The do-while Loop

                     The do-while loop is similar to the while loop. The only difference is that, in a do-while loop,

                     the condition  is stated at the end of the loop. This ensures that the body of the loop executes
                     at least once.

                                                                                      Developing Programs in C++        157

| 154 155 156 157 158 159 160 161 162 163 164 |