In this example, we will learn to find or calculate the sum of digits of the number entered by the user in the C++ program. For Example if user enter 123, then sum of digits is 1 + 2 + 3 = 6.
C++ program to find the sum of Digit by using
Now let's see Sum of the digit program
#include<iostream>
using namespace std;
int main()
{
int n, rem, sum = 0;
cout<<"Enter the number: ";
cin>>n;
while(n != 0)
{
rem = n % 10;
sum = sum + rem;
n = n / 10;
}
cout<<"\nSum of Digits of a number = "<<sum;
cout<<endl;
return 0;
}
Enter the number: 12 Sum of Digits of a number = 3
In the above program, you will take a number from the user and store it in a variable n
.
Now iterate the loop until the user value i.e n becomes zero
. inside loop finds the remainder of variable n and stores it in rem
.
Add the remainder i.e rem
into the sum
variable. when the loop end print the sum of the digit.
Time complexity: O(n)
In this example, we will find the sum of digits by using for loop. the output and time complexity of this program is the same as above.
#include<iostream>
using namespace std;
int main()
{
int n, rem, sum;
cout<<"Enter the number: ";
cin>>n;
for(sum=0; n != 0; n/=10)
{
rem = n % 10;
sum = sum + rem;
}
cout<<"\nSum of Digits of a number = "<<sum;
cout<<endl;
return 0;
}
This program is the same as above only here we have uses a do-while loop for calculating sum of the digit.
#include<iostream>
using namespace std;
int main()
{
int n, rem, sum = 0;
cout<<"Enter the number: ";
cin>>n;
do
{
rem = n % 10;
sum = sum + rem;
n = n / 10;
} while(n != 0);
cout<<"\nSum of Digits of a number = "<<sum;
cout<<endl;
return 0;
}
In this program, we use the user defines a function for finding the Sum of digits of a number. The output will same as the above program.
#include<iostream>
using namespace std;
int SumOfDigits(int n)
{
int sum=0, rem;
while(n != 0)
{
rem = n % 10;
sum = sum + rem;
n = n / 10;
}
return sum;
}
int main()
{
int n;
cout<<"Enter the number: ";
cin>>n;
cout<<"\nSum of Digits of a number = "<<SumOfDigits(n);
cout<<endl;
return 0;
}
you will pass user input i.e n
as an argument in the function SumOfDigits( ). It will calculate and return the sum of all digits.
In this C++ program, we will write the sum of digits program by using Class.
#include<iostream>
using namespace std;
class studyfame
{
private:
int n, sum, rem;
public:
void getData();
int SumOfDigits();
};
void studyfame::getData()
{
cout<<"Enter the Number: ";
cin>>n;
}
int studyfame::SumOfDigits()
{
sum=0;
while(n != 0)
{
rem = n % 10;
sum = sum + rem;
n = n / 10;
}
return sum;
}
int main()
{
studyfame s;
int sum;
s.getData();
sum = s.SumOfDigits();
cout<<"\nSum of Digits of a number = "<<sum;
cout<<endl;
return 0;
}
Enter the Number: 123 Sum of Digits of a number = 6
Time complexity of all above program: O(n)