home *** CD-ROM | disk | FTP | other *** search
/ C Programming Starter Kit 2.0 / SamsPublishing-CProgrammingStarterKit-v2.0-Win31.iso / tybc4 / dowhile1.cpp < prev    next >
C/C++ Source or Header  |  1993-03-22  |  807b  |  46 lines

  1. // Program demonstrates the do-while loop
  2.  
  3. #include <iostream.h>
  4.  
  5. const double TOLERANCE = 1.0e-7;
  6.                
  7. double abs(double x)
  8. {
  9.   return (x >= 0) ? x : -x;
  10. }               
  11.                
  12. double sqroot(double x)
  13. {
  14.   double guess = x / 2;
  15.   do {    
  16.     guess = (guess + x / guess) / 2;  
  17.   } while (abs(guess * guess - x) > TOLERANCE);
  18.   return guess;
  19.  
  20. double getNumber()
  21. {
  22.   double x;
  23.   do {
  24.     cout << "Enter a number: ";
  25.     cin >> x;
  26.   } while (x < 0);
  27.   return x;  
  28. }
  29.  
  30. main()
  31. {
  32.    char c;
  33.    double x, y;
  34.  
  35.    do {
  36.       x = getNumber();
  37.       y = sqroot(x);
  38.       cout << "Sqrt(" << x << ") = " << y << "\n"
  39.            << "Enter another number? (Y/N) ";
  40.       cin >> c;
  41.       cout << "\n";
  42.    } while (c == 'Y' || c == 'y');
  43.    return 0;
  44. }
  45.