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

Problem with affectation or issue in the for Loop

I created an Array with two elements, and tried a comparison of static arrays, but the incrementation of them is not working like was expected,

the expected output is 1 1 but the output gives me every time 0 1

here is the C code :

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>

int main() {

  int a[] = {1, 2, 3};
  int b[] = {3, 2, 1};

  int *res = malloc(2 * sizeof(int));

  int sumA = 0, sumB = 0;
  for (int k = 0; k < 2; k++) {
    if (a[k] > b[k]) {
      printf("yes a\n");
      sumA += 1;
    } else if (a[k] < b[k]) {
      printf("yes b\n");
      sumB += 1;
    }
  }

  res[0] = sumA;
  res[1] = sumB;

  printf("%d, %d", res[0], res[1]);

  return 0;
}

I tried debugging the code but no solution, I think the for loop is the issue, I just need hints or permanent solution …

Looking for you help guys.

>Solution :

You’re not iterating over all the 3 valid indexes.

for (int k = 0; k < 3; k++)

Note: you can use sizeof a / sizeof *a to calculate the number of elements in the array.

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