Q:

How can I return a plot from for loop in R?

I am trying to write a program for bisection method and try to plot the points also at each iteration. 
Here is the code I have tried.
Bisec = function(f,a =1, b =2, max=1e10, tol = 1e-100){
  midVals = c()
  for (i in 1:max){
    c = (a+b)/2
    midVals = append(midVals,c)
    if(abs(f(c)) < tol){
      return(list(c,plot(f),points(midVals)))
    }else if(f(a)*f(c) > 0){
    a = c  
    }else{
      b =c 
    }
      }
  print("Maximum iterations reached")
}
x = var('x')
f = function(x){x*x-2}
Bisec(f,1, 3, max=1e5, tol = 1e-10)

But I am getting the graphs like this. 
What do I need?

the function f has to be plotted.
the midpoints found in each iteration should be plotted in x axis. 

How to achieve this?
Any hint may be helpful.  I dont know where am I goint wrong. 

A:

R notation can be a little different if you learned to program in a different language.  Part of R's power is it's integration between an interpreted interface and (fast) compiled functions.  Generally (although this may be an exception, I'm not focusing on that), for loops are avoided (many functions are vectorized, which means they do the looping within the compiled portion of the code).  We also avoid defining empty variables, because they have to be copied and pasted EVERY time you want to add something to them.
For your specific problem, plot is plotting f - it just doesn't know anything about the points command because it evaluates plot before it ever sees points.   You might find ggplot2 gives a more dynamic solution, but I'll start with a base R approach to your function:
Bisec = function(f,a =1, b =2, max_iter=1e10, tol = 1e-100){
  midVals = rep(NA, max_iter) # I avoid using `max` since that's a function to find the maximum

  for (i in 1:max_iter){
    x <- mean(c(a,b)) # I also avoid using `c` since that's a function to concatenate stuff
    midVals[i] <- x

    if(abs(f(x)) < tol){
      plot(f, xlim = range(midVals, na.rm = TRUE))
      points(midVals, rep(0,length(midVals))
      return(x)
    } else if(f(a)*f(x) > 0){
    a = x  
    }
    else{
      b = x 
    }
  }
  print("Maximum iterations reached")
}

