Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Code do not print values when are repeated

I am working in a C code for school, the program is supposed to extract an array N of float values and determinate the pairs with the shortest distance between them; when there is only one closest pair of numbers the code prints it properly, however, when there are more (2 or +), is simply doesn’t print anything in the result part (I mean, the other sentences like "Type file name" still there, but the "result" is missing).

How can I solve i?

The code is in Spanish, but I’ll add the translation

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int main() {
char file_name[100];
int n, i;


printf("\tEscriba el nombre del archivo:\n");  //Type file name 
scanf("%s", file_name);

FILE *archivo = fopen(file_name, "r");    //archivo means file
if (archivo == NULL) {
    printf("No se pudo abrir el archivo.\n"); //File error
    return 1;
}

//sacar el valor de n contandoi los elemntos 
float value;
n = 0;
while (fscanf(archivo, "%f\n", &value) != EOF) {
    n++;
}


rewind(archivo);  //inciio


float a[n];
for (int i = 0; i < n; i++) {
    fscanf(archivo, "%f\n", &a[i]);
}


fclose(archivo); //cerrar owo

//algoritmo de selección para el orden :3
for (int i = 0; i < n - 1; i++) {
    int maxIndex = i;
    for (int j = i + 1; j < n; j++) {
        if (a[j] > a[maxIndex]) {
            maxIndex = j;
        }
    }
   
    float temp = a[i];
    a[i] = a[maxIndex];
    a[maxIndex] = temp;
}

//valores ordenados
printf("\nValores ordenados de mayor a menor:\n");    //Values sorted from + to -
for (int i = 0; i < n; i++) {
    printf("%.2f, ", a[i]);
  
}

  printf("\n");

  int distanceSize = n - 1;

  float distancia[distanceSize];       //distancia means distance (between pair of numbers)

// distancia directa lineal pq si no revuelve todo 
printf("\nDistancia: \n");      //Distance
for (i = 0; i < distanceSize; i++) {
    distancia[i] = a[i] - a[i + 1];
    printf("%.2f, ", distancia[i]);
}

   
//ordenar distancia 
 for (i = 0; i < distanceSize; i++) {
    for (int j = 0; j < distanceSize - i - 1; j++) {
        if (distancia[j] > distancia[j + 1]) {
            float temp = distancia[j];
            distancia[j] = distancia[j + 1];
            distancia[j + 1] = temp;
        }
    }
}  //burbuja pq nu me salió el otro aquí



printf("\n\nValores ordenados de la distancia:\n");   //Sorted distance values 
for (i = 0; i < distanceSize; i++) {
    printf("%.2f, ", distancia[i]);
}


float min = distancia[0];

 // printf("\n%.2f\n", distancia[0]);
  printf("\n\nDistancia Min: %.2f\n", min);

printf("\nPARES CERCANOS\n");      //CLOSEST PAIRS (HERE IS WHERE IT PRINTS NOTHING WHEN THERE ARE MORE THAN 1 PAIR WITH THE SAME DISTANCE)

for (i = 0; i < n; i++) {
  if (a[i + 1] - a[i] == min) {
    printf("(%.2f, %.2f)", a[i], a[i + 1]);
  }
}
return 0;
}

>Solution :

This for loop

for (i = 0; i < n; i++) {
  if (a[i + 1] - a[i] == min) {
    printf("(%.2f, %.2f)", a[i], a[i + 1]);
  }
}

results in accessing memory outside the array a when i is equal to n - 1 due to expression a[i + 1].

The second problem with the loop is that as the array a is sorted in the descending order then the expressioin a[i + 1] - a[i] always has a non-positive value while min is always a non-negative value.

Rewrite the loop like

for ( i = 1; i < n; i++) {
  if (a[i - 1] - a[i] == min) {
    printf("(%.2f, %.2f)", a[i - 1], a[i]);
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading