# Thread: Simple C Problem

1. ## Simple C Problem

Hi, I just started working with C and was working on an exercise where I needed to simulate a random 'walk' on a Cartesian grid. It is supposed to start on the origin, add a number between -5 - 5 one thousand times, and then calculate distance from the origin to the new value. I've been able to do everything, but I can't see how I'm supposed to get it to repeat the addition. If someone could point me in the right direction I would be very grateful.

Here's my current code for reference:
Code:
```#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main () {
float x, p, y, yn, xn, product, distance;
x= 0;
y= 0;
p= 5 - rand()%10;
xn= x+p;
yn= y+p;
product= (xn*xn) + (yn*yn);
distance= sqrt(product);
printf("Change in x: %f\n",xn);
printf("Change in y: %f\n",yn);
printf("Distance from origin:%f\n",distance);
return 0;
}```
Also just in case it is important, I'm using xcode. Thank you in advance and thanks for having this kind of community; I wouldn't have got this far with this program without being able to use this board as a reference.

2. It depends on how you want to repeat the computation, what conditions are necessary when you start and what conditions cause it to stop... Basically you should read up on "loops" in your C books... for(), while(), do -- while() are the most common forms.

3. It is very easy to add it for thousand times. Your current code is perfect for a single interation. What you will have to do is just to enclose it within a loop that runs for 1000 times.

You must refer to 'Looping in C'.

For an example: you can use 'for' loop for this.

Code:
```#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main () {
float x, p, y, yn, xn, product, distance;
int i;
x= 0;
y= 0;
distance = 0.0f;

for ( i = 1; i <= 1000; i++ ) {
p= 5 - rand()%10;
xn= x+p;
yn= y+p;
product= ((xn - x)*(xn - x)) + ((yn - y)*(yn - y));
distance += sqrt(product);

printf("Change in x: %f\n",xn);
printf("Change in y: %f\n",yn);

printf("Distance from origin:%f\n",distance);

x = xn;
y = yn;
}

return 0;
}```

Popular pages Recent additions