Skip to main content

5.7) Exercise 8


Write a program that uses a while loop to compute and display the square-roots of the whole numbers from 1 to 20 inclusive.

  • Write your while loop to generate the integers 1, 2, 3, ... 20 first, before adding further code.
  • You can use the sqrt function to compute a square-root; sqrt(n) will compute and return the square-root of the value represented by variable n, for example. To access this function you must add a #include <cmath> to the list of include directives at the top of your program.
  • Your program should display each value and its square-root as a neatly-formatted pair of right-justified columns, with square-roots displayed to 3 decimal places. Use stream manipulators to achieve this. A partial sample of expected output appears below.
 1   1.000
 2   1.414
 3   1.732
 4   2.000
 5   2.236
 6   2.449
 7   2.646
 8   2.828
 9   3.000
10   3.162