Tuesday, June 22, 2021
Home coding Write a program to print sum of digits.

Write a program to print sum of digits.

Given a number we have to find the sum of digit of number .

so what is sum of digits?

for example- number like 25 the sum of digit is 2+5=7

Example:

input:19
output:10

input:98
output:17

Logic:

main logic behind this question is to just find all the digit of a number and add them all .

#include<iostream>
using namespace std;
int main()
{
 int num;
 cout<<"Enter a number : "<<endl;
 cin>>num;
 int sum=0;
 while(num>0)
 {
     int rem=num%10;
    sum+=rem;
     num=num/10;
 }
cout<<"sum of digit is "<<sum<<endl;
 

}

Output:

Enter a number : 14
sum of digit is 5

Time Complexity:O(N)

Space Complexity:O(1)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments