Sum of an array of large numbers | C ++ program for the above approach ; Function to print the result of the summation of numbers having K - digit ; Reverse the array to obtain the result ; Print every digit of the answer ; Function to calculate the total sum ; Stores the array of large numbers in integer format ; Convert each element from character to integer ; Stores the carry ; Stores the result of summation ; Initialize the sum ; Calculate sum ; Update the sum by adding existing carry ; Store the number of digits ; Increase count of digits ; If the number exceeds 9 , Store the unit digit in carry ; Store the rest of the sum ; Append digit by digit into result array ; Append result until carry is 0 ; Print the result ; Driver Code ; Given N array of large numbers
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printResult ( vector < int > result ) { reverse ( result . begin ( ) , result . end ( ) ) ; int i = 0 ; while ( i < result . size ( ) ) { cout << result [ i ] ; i ++ ; } } void sumOfLargeNumbers ( string v [ ] , int k , int N ) { vector < vector < int > > x ( 1000 ) ; for ( int i = 0 ; i < k ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { x [ i ] . push_back ( v [ i ] [ j ] - '0' ) ; } } int carry = 0 ; vector < int > result ; for ( int i = N - 1 ; i >= 0 ; i -- ) { int sum = 0 ; for ( int j = 0 ; j < k ; j ++ ) sum += x [ j ] [ i ] ; sum += carry ; int temp = sum ; int count = 0 ; while ( temp > 9 ) { temp = temp % 10 ; count ++ ; } long long int l = pow ( 10 , count ) ; if ( l != 1 ) carry = ( double ) sum / l ; sum = sum % 10 ; result . push_back ( sum ) ; } while ( carry != 0 ) { int a = carry % 10 ; result . push_back ( a ) ; carry = carry / 10 ; } printResult ( result ) ; } int main ( ) { int K = 10 ; int N = 5 ; string arr [ ] = { "1111111111" , "1111111111" , "1111111111" , "1111111111" , "1111111111" } ; sumOfLargeNumbers ( arr , N , K ) ; return 0 ; }