Click here to Skip to main content
15,891,902 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i have an array of float datatype. arr=[-0.05,0.03,0.09,0.1]; now i have written code such that it will display the closest value to zero and their location.
but now i need to do in such a way that all the array values should be in an order closer to zero.
if array index starting from zero.
the output should be like
1. 0.03 location=1
2. -0.05 location=0
3. 0.09 location=2
4. 0.1 location=3

What I have tried:

#include<stdio.h>
int main() 
{
    float array[100], minimum;
    int size, c, location = 1;
 
    printf("Enter the number of elements in array\n");
    scanf("%d",&size);
 
    printf("Enter %d integers\n", size);
 
    for ( c = 0 ; c < size ; c++ )
        scanf("%f", &array[c]);
 
    minimum = array[0];
 
    for ( c = 0 ; c < size ; c++ ) 
    {
	   if(array[c]<0 && minimum<0)
		{
	if ( (-array[c]) < (-minimum ) )
        {
           minimum = array[c];
           location = c+1;
        }	
		}
else if(array[c]<0 && minimum>0)
{
if ( (-array[c]) < (minimum ) )
        {
           minimum = array[c];
           location = c+1;
        }	
}
else if(array[c]>0 && minimum<0)
{
if ( (array[c]) < (-minimum ) )
        {
           minimum = array[c];
           location = c+1;
        }	
}
else{
        if ( array[c] < minimum ) 
        {
           minimum = array[c];
           location = c+1;
        }}
    } 
 
    printf("Minimum element is present at location %d and it's value is %f.\n", location, minimum);
    return 0;
}
Posted
Updated 10-Apr-17 1:56am

Use the qsort[^] function for the purpose.
 
Share this answer
 
You have to sort the array. Because you need to print out the initial position after sorting you have to store that too. The solution is to use a structure:
C++
typedef struct
{
    int position;
    float value;
} val_struct;

int main()
{
    val_struct array[100];
    /* ... */
    for ( c = 0 ; c < size ; c++ )
    {
        array[c].position = c;
        scanf("%f", &array[c].value);
    }
    /* ... */
}

Now sort the array and print all items as required. Because it seems this is some kind of homework, it will not post a final solution. You can search online for sorting algorithms or use qsort - C++ Reference[^].
 
Share this answer
 
Comments
R!sh! 11-Apr-17 0:46am    
This in not my homework. if i get the proper code my project will be done. this is the part left.
Jochen Arndt 11-Apr-17 2:31am    
Where is the problem?
All you have to do is implementing the sort compare function, call qsort, and print the result.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900