Home  >  Article  >  Backend Development  >  In C program, add two numbers represented by two arrays

In C program, add two numbers represented by two arrays

WBOY
WBOYforward
2023-09-13 21:49:021054browse

In C program, add two numbers represented by two arrays

A number represented by an array is stored in such a way that each digit of the number is represented by an element of the array. For example,

Number 234 in array is {2,3,4}.

To add these numbers, we first add the numbers at the lowest digit and pass a carry if the sum is greater than 10. After this we will continue the same process for the next consecutive number of the array and sum it.

Let us take an example and add two numbers -

a = {2,9, 6}
b = {6, 3, 8}
Output: 934

Explanation − We will add the least significant digit of the number i.e. 6 8 = 14 which will Propagate a carry and then for the same 9 3 1 = 13 this will again propagate the carry to the next number. The sum of the next numbers will be 2 6 1 = 9. This would make the sum 934.

Algorithm

To find the sum of numbers stored in array form. We first check if any number has more digits. If it is, then we find the sum of the digits of the smaller number and then add the digits of the larger number.

Additionally, we will check for a carry number which will keep track of carries that may occur in the sum and need to be forwarded, initially to zero and before each iteration of the sum It is set to zero. We will find the sum of the numbers one by one and store it into an array and then print it.

Example

Live Demo

#include <iostream>
using namespace std;
int Sum(int a[], int b[], int n, int m){
   int sum[n];
   int i = n - 1, j = m - 1, k = n - 1;
   int c = 0, s = 0;
   while (j >= 0) {
      s = a[i] + b[j] + c;
      sum[k] = (s % 10);
      c = s / 10;
      k--;
      i--;
      j--;
   }
   while (i >= 0) {
      s = a[i] + c;
      sum[k] = (s % 10);
      c = s / 10;
      i--;
      k--;
   }
   for (int i = 0; i <= n-1; i++) {
      cout<<sum[i];
   }
}
int main(){
   int a[] = { 5, 6, 9 };
   int b[] = { 3, 8 };
   int n = sizeof(a) / sizeof(a[0]);
   int m = sizeof(b) / sizeof(b[0]);
   cout<<"The sum is ";
   if (n >= m)
      Sum(a, b, n, m);
   else
      Sum(b, a, m, n);
   return 0;
}

Output

The sum is 607

The above is the detailed content of In C program, add two numbers represented by two arrays. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete