- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Sum of two large numbers in C++

In this problem, we are given two string that defines two large numbers. Our task is to create a program to find the sum of two large numbers.

## Let’s take an example to understand the problem,

Input: number1 = “341299123919” number2 = “52413424” Output: 341351537343

To solve this problem, we will traverse both the string. And add digit by digit and propagate the carry. And store the result digit by digit to sum string.

## Algorithm

Initialize sum = 0, carry = 0. Step 1: loop from n to 0. Step 1.1: intSum = number1[i] + number2[i] Step 1.2: carry = intSum/10. Sum += intSum Step 2: sum += carry. Step 3: return sum.

## Example

Program to illustrate the working of our solution,

#include<bits/stdc++.h> using namespace std; string addBigNumbers(string number1, string number2) { if (number1.length() > number2.length()) swap(number1, number2); string sum = ""; int len1 = number1.length(); int len2 = number2.length(); int digitDiff = len2 - len1; int carry = 0; int intSum; for (int i=len1-1; i>=0; i--) { intSum = ((number1[i]-'0') + (number2[i+digitDiff]- '0') + carry); sum.push_back(intSum%10 + '0'); carry = intSum/10; } for (int i=digitDiff-1; i>=0; i--) { intSum = ((number2[i]-'0')+carry); sum.push_back(intSum%10 + '0'); carry = intSum/10; } if (carry) sum.push_back(carry+'0'); reverse(sum.begin(), sum.end()); return sum; } int main() { string number1 = "235235823852"; string number2 = "45230820348"; cout<<"Sum of two large numbers is "<<addBigNumbers(number1,x number2); return 0; }

## Output

Sum of two large numbers is 280466644200

- Related Questions & Answers
- Sum of two numbers modulo M in C++
- Large Fibonacci Numbers in C#
- Handling large numbers in C++?
- Sum of the multiples of two numbers below N in C++
- Check if sum of divisors of two numbers are same in Python
- C program to find sum and difference of two numbers
- C++ Program to Find Factorial of Large Numbers
- Behavior of + operator in JavaScript to store large numbers?
- Minimum sum of two numbers formed from digits of an array in C++
- How to find the Sum of two Binary Numbers using C#?
- 8085 program to sum of two 8 bit numbers without carry
- How to stop default printing of large numbers in R?
- Print all integers that are sum of powers of two given numbers in C++
- Sum of sum of first n natural numbers in C++
- Find the Sum of two Binary Numbers without using a method in C#?

Advertisements