I am just starting to learn C. I am trying to write a program where the user will input x and y coordinates. The x's and y's will go into separate arrays. The program is then supposed to sort the coordinates based on their distance from the origin, using the formula sqrt (x*x + y*y), and display them from least to greatest. I have been unable to find any information on this, either in my books, or on the net.
This is what I have so far.
#include <stdio.h>
#include <math.h>
#define MAX_LIST_SIZE 10
float calc_z (int x, int y);
void sort_xy (int x[], int y[]);
int i,j, choice, coordNumber;
int x[MAX_LIST_SIZE], y[MAX_LIST_SIZE];
void main () {
while (1) {
printf ("Enter (1) to run (2) to quit: ");
scanf ("%d", &choice);
if (choice == 2) return;
else {
printf("How many coordinates do you want to enter in: ");
scanf ("%d", &coordNumber);
for (i = 0; i < coordNumber; i++) {
printf ("enter x,y: ");
scanf ("%d,%d", &x[i], &y[i]);
}
void sort_xy (int x[], int y[]);
for (i = 0; i < coordNumber; i++) {
printf("%d %d\n", x[i], y[i]);}
}
}
}
void sort_xy (int x[], int y[], int j) {
int hold1, hold2;
for (j = 1; j < coordNumber; j++) {
for (i = 0; i< coordNumber-1; i++) {
if (sqrt((float)(x[i]*x[i]+y[i]*y[i])) > sqrt((float)(x[i+1]*x[i+1]+y[i+1]*y[i+1]))) {
hold1= x[i];
x[i]=x[i+1];
x[i+1] = hold1;
hold2= y[i];
y[i]=y[i+1];
y[i+1] = hold2;
}
}
}}
However it prints them in the same order they were typed. I tried writing a separate function to calculate distance from the origin, but I couldn't figure out how to make it work with the sorting function.If anyone can point me in the right direction it would be greatly appreciated.


Sign In
Create Account

Back to top









