Challenge: Move a Point
Completed
Define typedef struct { int x; int y; } Point; and a function void move(Point *p, char dir) that moves the point one step: U is y+1, D is y−1, R is x+1, L is x−1. Start at (0, 0), read a word of moves like UURDL, apply them all and print the final position.
Input
One word made of U, D, L, R.
Output
(x, y)
Example
Input
UURDL
Output
(0, 1)
Editor
C
Hints
Pass &pos so move can change the real point.
Inside move, use p->x and p->y.
Solution explanation
Because move gets a pointer, every step changes the same pos variable in main.
Show solution
#include <stdio.h>
typedef struct {
int x;
int y;
} Point;
void move(Point *p, char dir) {
if (dir == 'U') {
p->y++;
} else if (dir == 'D') {
p->y--;
} else if (dir == 'R') {
p->x++;
} else if (dir == 'L') {
p->x--;
}
}
int main() {
char moves[101];
scanf("%s", moves);
Point pos;
pos.x = 0;
pos.y = 0;
for (int i = 0; moves[i] != '\0'; i++) {
move(&pos, moves[i]);
}
printf("(%d, %d)\n", pos.x, pos.y);
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module