You are currently viewing Best Code for Large Number Addition in 2023

Best Code for Large Number Addition in 2023

Code for Large Number Addition

For learning c code in more advanced form, students are advised to practice few codes related to pointer, dynamic memory allocation. For learning pointer, dynamic memory allocation you should go through this code. This is Code for Large Number Addition.

In C code practice, this Code for Large Number Addition logic plays a very important role. So I have designed this code as easy as possible for the students. They will be able to understand each and every step very easily. 

Before going for this type of program a student should go through basics of pointer, dynamic memory allocation etc. So that they can easily go through each step with self explanation mode. 

For more code click here. For video tutorial on several topics click here

				
					#include<stdio.h>

#include<stdlib.h>

typedef struct linked {
  int val;
  struct linked * next;
}
lnk;

lnk * create();
lnk * add(lnk * , lnk * );
void disp(lnk * );

int main() {
  lnk * h1, * h2, * h3;
  printf("\n\nEnter the first large number : ");
  h1 = create();
  printf("\n\nEnter the second large number : ");
  h2 = create();
  h3 = add(h1, h2);
  printf("\n\nResultant number : ");
  disp(h3);
  return 0;
}

lnk * create() {
  int a, m;
  lnk * temp, * h = NULL;
  char ch;
  while ((ch = getchar()) != '\n') {
    temp = (lnk * ) malloc(sizeof(lnk));
    temp -> val = ch - '0';
    temp -> next = h;
    h = temp;
  }
  return h;
}

lnk * add(lnk * h1, lnk * h2) {
  lnk * h3 = NULL, * temp, * ptr;
  int cr, t = 0;
  while (h1 != NULL && h2 != NULL) {
    t = h1 -> val + h2 -> val + t;
    cr = t % 10;
    temp = (lnk * ) malloc(sizeof(lnk));
    temp -> val = cr;
    temp -> next = h3;
    h3 = temp;
    t = t / 10;
    h1 = h1 -> next;
    h2 = h2 -> next;
  }
  if (h1 != NULL && h2 == NULL) {
    while (h1 != NULL) {
      t = h1 -> val + t;
      cr = t % 10;
      temp = (lnk * ) malloc(sizeof(lnk));
      temp -> val = cr;
      temp -> next = h3;
      h3 = temp;
      t = t / 10;
      h1 = h1 -> next;
    }
  } else if (h2 != NULL && h1 == NULL) {
    while (h2 != NULL) {
      t = h2 -> val + t;
      cr = t % 10;
      temp = (lnk * ) malloc(sizeof(lnk));
      temp -> val = cr;
      temp -> next = h3;
      h3 = temp;
      t = t / 10;
      h2 = h2 -> next;
    }
  } else {
    temp = (lnk * ) malloc(sizeof(lnk));
    temp -> val = t;
    temp -> next = h3;
    h3 = temp;
  }
  return h3;
}

void disp(lnk * h) {
  if (h == NULL)
    return;
  else {
    printf("%d", h -> val);
    disp(h -> next);
  }
}
				
			

Leave a Reply