# Intro to C programming help

This is a discussion on Intro to C programming help within the C Programming forums, part of the General Programming Boards category; I am trying to figure out how to convert this recursive Scheme definition into a non-recursive loop function in C. ...

1. ## Intro to C programming help

I am trying to figure out how to convert this recursive Scheme definition into a non-recursive loop function in C. I've just started learning C after Scheme and loops are still confusing to me.

This is the recursive version in scheme:
Code:
```#lang racket
(define (powmod2 x e m)
(define xsqrm (remainder (* x x) m))
(cond
[(= e 0) 1]
[(even? e) (powmod2 xsqrm (/ e 2) m)]
[(odd? e) (remainder (* x (powmod2 xsqrm (/ (sub1 e) 2) m)) m)]))```
This is my non-working code in C:
Code:
```int powmod2(int x, int e, int m) {
int ans = 1;
while (e != 0) {
x=x*x%m;
if(e%2 == 0) {
e=e/2;
}
else {
e=(e-1)/2;
ans=(ans*x)%m;
}
}
return ans;
}```
Any guidance would really be appreciated!

2. Try getting a recursive version working first.

3. This looks wrong:
Code:
`x=x*x%m;`
I am not much of a schemer, but I believe that your Scheme code does not do that computation at that point. Rather, it just defines a function to do that, and then calls the function with arguments depending on the subsequent condition. As such, an appropriate translation is to define a xsqrm function in C, and call that from your powmod2 function.

4. Now that I think about it, forget about a recursive version. In fact, forget about the scheme (lisp) program completely and think about how you would do it iteratively. You want to multiply 1 by x e times, modulus m.