# ------------------------------------------------------------------
# File name: while_loops.R
#
# while loop iterates a block of statements as long as a condition (boolean) remains true.
# Syntax of while loop is:
# while (boolean){
# statements
# }
# break exits the loop
#
# Version: 2.1
# Authors: H. Kocak, University of Miami and B. Koc, Stetson University
# References:
# https://www.r-project.org
# ------------------------------------------------------------------
# To generate a table of numbers and their squares
counter = 1
while (counter <= 10){
square = counter * counter
cat("counter = ", counter, "\t", "square = ", square, "\n" )
counter = counter + 1
}
# Newton-Raphson iteration for finding sqrt(2) with a specified tolerance
# x = starting value
# delta = absolute value of the difference between two consecutive iterates
# while performs Newton-Raphson iterates as long as delta remains greater than
# a desired tolerance
cat("Newton-Raphson iteration for computing sqrt(2) with a specified tolerance \n")
options(digits = 15)
x = 3.1
tolerance = 1e-8
cat("x =", x, "\t", "tolerance =", tolerance, "\n")
x_next = 0.5 * (x + 2/x)
delta = abs(x_next - x)
cat("x =", x_next, "\t", "delta =", delta, "\n")
x = x_next
while (delta > tolerance){
x_next = 0.5 * (x + 2/x)
delta = abs(x_next - x)
cat("x =", x_next, "\t", "delta =", delta, "\n")
x = x_next
}