Header Ads Widget

C++ program to find the sum of digits of a number

 

 C++ program to find the sum of digits of a number 

Given a number , write a program to find the sum of digits of number in C++ . The logic behind to do this is first we will find the digits of the number by finding reminder by dividing number by 10 and each time add this reminder in a variable named as sum .

Sample input :

123

Sample output:

6

 C++ program to find the sum of digits of a number 

The objective of the code is to find the sum of the digits of a number . 

Code(C++):-

#include <iostream>
using namespace std;
int main()
{
int num,sum=0,r;
cout<<"Enter a number\n";
cin>>num;
while(num!=0)
{
r=num%10;
sum+=r;
num/=10;
}
cout<<"Sum of digits is "<<sum;
return 0;
}

Output:

Enter a number
123
Sum of digits is 6



Recommended Post :-

HCL Coding Questions:-

Capgemini Coding Questions:-

Companies interview:-

Full C course:-    

Key points:-

Cracking the coding interview:-

 Array and string:-

Tree and graph:-

Hackerearth Problems:-

Hackerrank Problems:-

Data structure:-

 MCQs:-

Post a Comment

0 Comments