• Tutorials
  • DSA
  • Data Science
  • Web Tech
  • Courses
July 16, 2024 |49.1K Views

C++ Program to Find the Sum of All Digits of a Number

  Share  2 Likes
Description
Discussion

In this video, we will see a how-to find Sum of the digits of a given number. Let's understand this concept with the help of examples:

Suppose an Input : n = 123
= 1+2+3
= Output: 6

Now take another example and Input n = 1990
= 1+9+9+0
= Output : 19

General Algorithm for the sum of digits in a given number:

Step 1: Get the number.
Step 2: Declare a variable to store the sum and set it to 0.
Step 3: Repeat the next two steps till the number is not 0.
Step 4: Get the rightmost digit of the number with help of the remainder ‘%’ operator by dividing it by 10 and add it to sum.
Step 5: Divide the number by 10 with help of ‘/’ operator to remove the rightmost digit.
Step 6: Print or return the sum.

Program for sum of the digits of a given number: https://www.geeksforgeeks.org/program-for-sum-of-the-digits-of-a-given-number/