- #1
The Sand Man
- 8
- 0
I haven't written C in a while, but I decided to brush up on it.
I'm trying to solve this problem:
User inputs values into an array, input terminates with a negative value. I then want to print out all the values in the order they were entered, then print them in ascending order.
I realize there are multiple ways to solve this problem, but this is the only one which is giving me trouble. The approach I have in this problem is to work through the array, find the lowest value, print it, then delete it.
I hope you can figure out my mistake. When I input values like:
1 3 1 5 1 5 1
I get:
1 1 3 5 5 5 5 :(
Thanks for any help. :)
Cheers,
Sand
I'm trying to solve this problem:
User inputs values into an array, input terminates with a negative value. I then want to print out all the values in the order they were entered, then print them in ascending order.
I realize there are multiple ways to solve this problem, but this is the only one which is giving me trouble. The approach I have in this problem is to work through the array, find the lowest value, print it, then delete it.
Code:
#include<stdio.h>
#include<math.h>
int main()
{
double x[100],v, min=0;
int i, n, j, count;
printf("Enter data (<0 to terminate): ");
n=0;
while(1)
{
scanf("%lf",&v); //Scan in values
if(v<0.0) break; //Terminate with negative value
x[n++]=v; //Store in array
}
printf("given data:\n");
for(i=0;i<n;i++)
{
printf("%5.1f",x[i]); //Print out array values
}
printf("\ndata in ascending order:\n");
count=n;
while(count>0)
{
min=x[0];
for(i=0;i<n;i++)
{
if(min>x[i]) min=x[i]; //Find lowest value
}
count--;
printf(" %.1lf", min); //Print lowest value
i=0;
while(i<(n-1)) //Delete lowest value
{
if(min==x[n-1]) //Check if it's the last one, reduce length of array
{
n--;
break;
}
if(x[i]==min) //If it's not at the end, delete it, and overwrite array from that position onwards
{
for(j=i;j<(n-1);j++)
{
x[j]=x[j+1];
}
n--;
}
i++;
}
}
printf("\n");
return 0;
}
I hope you can figure out my mistake. When I input values like:
1 3 1 5 1 5 1
I get:
1 1 3 5 5 5 5 :(
Thanks for any help. :)
Cheers,
Sand