Vasile Ropot
Vasile Ropot

Reputation: 11

How to fix the output of the following C program?

I have a problem with output of the following C program. It does not get me the correct output.I transform this program from the sum of two big numbers. So I get the output with some "errors" like "232423-3-4-34--3424" instead of "23242334343424". How do i fix this?

 #include<stdio.h>
int main() {
  int num1[255], num2[255], dif[255];
  char s1[255], s2[255];
  int l1, l2;

  printf("Enter Number1:\n");
  scanf("%s", &s1);
  printf("Enter Number2:\n");
  scanf("%s", &s2);

  for (l1 = 0; s1[l1] != '\0'; l1++)
    num1[l1] = s1[l1] - '0';

  for (l2 = 0; s2[l2] != '\0'; l2++)
    num2[l2] = s2[l2] - '0';

  int carry = 0;
  int k = 0;
  int i = l1 - 1;
  int j = l2 - 1;
  for (; i >= 0 && j >= 0; i--, j--, k++) {
    dif[k] = (num1[i] - num2[j] - carry) % 10;
    carry = (num1[i] - num2[j] - carry) / 10;
  }
  if (l1 > l2) {

    while (i >= 0) {
      dif[k++] = (num1[i] - carry) % 10;
      carry = (num1[i--] - carry) / 10;
    }

  } else if (l1 < l2) {
    while (j >= 0) {
      dif[k++] = (num2[j] - carry) % 10;
      carry = (num2[j--] - carry) / 10;
   }
  } else {
    if (carry > 0)
      dif[k++] = carry;
  }


  printf("Result:");
  for (k--; k >= 0; k--)
    printf("%d", dif[k]);

  return 0;
}

Upvotes: 0

Views: 139

Answers (1)

user4815162342
user4815162342

Reputation: 154906

Your result includes negative numbers because the code doesn't correctly implement modulo-10 arithmetic. In lines like this:

dif[k] = (num1[i] - num2[j] - carry) % 10;

If subtraction num1[i] - num2[j] - carry is less than 0, you want to store the result of 10-subtraction. There are languages where the % operator works like that in, but in C it returns a negative number, so -1 % 10 yields -1 and not 9.

To fix the issue, the code needs to be more explicit, e.g.:

int sub = num1[i] - num2[j] - carry;
if (sub >= 0) {
    dif[k] = sub;
    carry = 0;
} else {
    dif[k] = 10 - sub;
    carry = 1;
}

Upvotes: 3

Related Questions