Q:

Writing Recursive code iteratively

I have the following recursive code which I want to change to iterative code.  I am unsure of where to begin as the function is very complex with recursive calls at two locations.  Any possible iterative implementations to the below function ? 
int ncip(int dim, double R){
    int n, r = (int)floor(R);

    if (dim == 1)
        return 1 + 2*r; 
    n = ncip(dim-1, R); // last coord 0

    for (int i=1; i<=r; ++i){
        n += 2*ncip(dim-1, sqrt(R*R - i*i) ); // last coord +- i
    }

    return n;
}

A:

One common approach is to use a stack for the function calls.  A simple implementation would be as follows and you can do some optimization on it
int ncip(int dim, double R){
    typedef pair<int, double> data; // ties parameters into one unit

    stack<data> s;
    s.push(make_pair(dim,R)); // push the first set of parameters
    int n = 0;

    while(false == s.empty()) { // do the loop until stack is depleted
        auto item = s.top(); // get the top item and pop it after
        s.pop();
        int r = static_cast<int>(floor(item.second));

        if (item.first == 1) {
            n += 1 + 2*r; 
        } else {
            s.push(make_pair(item.first-1,item.second));

            for (int i = 1; i <= r; ++i){
                // since you have a multiplier 2 we push the same parameters twice
                s.push(make_pair(item.first-1, sqrt(item.second*item.second - i*i) ));
                s.push(make_pair(item.first-1, sqrt(item.second*item.second - i*i) ));
            }
        }
    }
    return n;
}

