I have to write a function of the following method :
Rejection method (uniform envelope):
Suppose that fx is non-zero only on [a, b], and fx ≤ k.
Inside while loop, if we have return statement with true or false.. it will work accordingly..
Example: To Check a list is circular or not..
here the loop is infinite, because while (true) is true always, but we can break sometimes by using the return statement,.
while(true)
{
if(!faster || !faster->next)
return false;
else
if(faster==slower || faster->next=slower)
{
printf("the List is Circular\n");
break;
}
else
{
slower = slower->next;
faster = faster->next->next;
}
It's an infinite loop. The expression is executed as long as the condition evaluates to TRUE
, which it will always do. However, in the expression there is a return
, which when called (e.g., if y < fx(x)
), breaks out of the function and thus stops the loop.
Here is a simpler example:
fun <- function(n) {
i <- 1
while (TRUE) {
if (i>n) return("stopped") else print(i)
i <- i+1
}
}
fun(3)
#[1] 1
#[1] 2
#[1] 3
#[1] "stopped"
What happens when this function is called?
i
is set to 1.while
loop is tested. Because it is TRUE
, it's expression is evaluated. if
construct is tested. Since it is FALSE
the else
expression is evaluated and i
is printed.i
is increased by 1.i
reaches the value of 4, the condition of the if
construct is TRUE
and return("stopped")
is evaluated. This stops the whole function and returns the value "stopped".