Sum Of Digits

We have to find the sum of the sum of digits of a very long integer.

umm…
in order to get the last digit of a number you do
last_digit = num % 10;

and in order to iterate through number until the last digit.

while( num > 0 )
{
    currLastDigit = num % 10;
	num = num / 10;
	cout << currLastDigit;
}

//example if num is 2912, the output would be 2192

also, << is turned into ( operand )lt

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int fir, sec, thi;
cin>>fir<<endl;
cin>>sec<<endl;
thi=fir+sec;
cout<<“The total no. of digits”<<thi<<endl;
getch();
}

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int fir, sec, thi;
cin>>fir<<endl;
cin>>sec<<endl;
thi=fir+sec;
cout<<“The total no. of digits”<<thi<<endl;
getch();
}

Since you haven’t specified how long the integer is, let’s assume it has around 10^7 digits.
Take the input as an array of characters.
Iterate through this array and add each character to the sum.
While doing this, remember the the array has characters and not digits.
To convert each digit character into digit, simply subtract 48 from it (as ASCII of 0 is 48).

The question that is been put up is a considerably simple problem. The only trick lies there is the size of input.

In the very initial days of coding ; we do the mistake of taking every numeric input in the form of int.

I mean it was something that we picked from our schooling days, strings meant “abcd” and int meant 1234.

Since it is mentioned that it is a very long integer ; the absolute beginner goes ahead and takes a bigger data type as long long ; long double or something like that.

But the long long data type cant handle even let say a number with 100 digits.

So it becomes imperative to take input as a string. Which can have a considerable high length and capability to store biggggggggerrrr numbers.

Then you may iterate over the string once in complexity of O(no. of digits); pick one character at a time.

find ascii value of each character (digit) ; subtract 48 from the obtained ascii value ( which would be the numeric value of the character type digit ) and add those values ( addition now will give sum of digits )…

Finally print the sum of digits…!!!

Hope this helps… Happy coding… :slight_smile:

#include

using namespace std;

int main()
{
int a, b, c;

cout << “Enter two integers to add\n”;
cin >> a >> b;

c = a + b;
cout <<"Sum of the numbers: " << c << endl;

return 0;
}

//