You are here

C program to compare large numbers (integers)

We can use inbuilt data types to compare two integers that fit in the range of the respective data type. As you know there is a limit of maximum integer which can be stored in a data type. We will use strings to store integers and then create a function to compare the integers. An integer can be positive, zero or negative, we will take care of it in our program.

Algorithm of comparing:

If both numbers are positive: If the length of one of them is greater than the other, the greater number is bigger. If the length of both is the same then we compare individual digits of both the numbers, if any digit of first is greater then the second then the first is bigger and vice versa. If both the digits are equal then we move to the next digits. If the string ends then both the numbers are equal.

If anyone of the number is negative then the positive number is the bigger one.

If both the numbers are negative then the logic is the same as that of the comparing positive numbers except for one thing: the number which is smaller in magnitude is the larger one.

C program to compare numbers using string

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

int compare(char [], char []);

int main()
{
  char a[1000], b[1000];
  int n;

  printf("Enter two integers\n");

  scanf("%s%s", a, b);

  n = compare(a, b);

  if (n == 1)
    printf("First.\n");
  else if (n == 0)
    printf("Equal.\n");
  else
    printf("Second.\n");

  return 0;
}

int compare(char a[], char b[]) {
  int l1, l2, p1, p2, n;

  // Checking if any of the numbers is negative

  if (a[0] == '-')
    p1 = 0;
  else
    p1 = 1;

  if (b[0] == '-')
    p2 = 0;
  else
    p2 = 1;

  // Calculating length of strings

  l1 = strlen(a);
  l2 = strlen(b);

  // Both numbers positive

  if (p1 == 1 && p2 == 1) {
    if (l1 > l2)
      return 1;
    else if (l2 > l1)
      return 2;
    else {
      for (n = 0; n < l1; n++) {
        if (a[n] > b[n])
          return 1;
        if (b[n] > a[n])
          return 2;
      }
      if (n == l1)  // Can be removed (optional)
        return 0;
    }
  }

  // If one number is positive and other is negative

  if (p1 == 1 && p2 == 0) // 1st no positive
    return 1;
  if (p1 == 0 && p2 == 1) // 2nd no positive
    return 2;

  // If both numbers negative

  if (l1 < l2)
    return 1;
  if (l2 < l1)
    return 2;

  for (n = 1; n < l1; n++) {
    if (a[n] < b[n])
      return 1;
    if (b[n] < a[n])
      return 2;
  }

  return 0; // Both numbers (-ve) are same.
}

Share this