The program is written to add the digits of the given number. A number is taken as input and then the digits of the number are added and the sum of the digits is printed.
For example, let the input be: 1234
Then the sum of the digits is: 1+2+3+4=10
INPUT: A number
OUTPUT: Sum of the digits
PROCESS:
Step 1: [Taking the input]
Read n
Step 2: [Finding the sum of the digits]
Set sum<-0
While n>0 repeat
Set sum<-sum+(n mod 10)
Set n<-n/10
[End of ‘while’ loop]
Step 3: Stop.
while(n>0)--------------------------------O(log10n)
{
sum=sum+(n%10);
n=n/10;
}
The time complexity of this program is O(log10n) where ‘n’ is the number whose sum of the digits is to be calculated.
The space complexity of this program is O(1) as it requires a constant number of memory spaces for any given input.