Problem Solving: Sum of Digits (revisited)

Learn to implement programs using functions in C++.

So let’s start with our first problem, which is the sum of digits!

Sum of digits

This program requires three main steps.

  1. To get a number from the user.

    i. If the number is invalid, i.e., not a 6-digit number

    ii. Input should be taken again.

  2. To calculate the sum of all its digits.

  3. To print the result on the screen.

We’ll perform the validity of the number (step 1 (ii) ) and the calculation of the sum of digits (step 2) through separate functions.

  1. The valid6Digit() method: This takes an integer as a parameter and returns true if the number is a 6-digit number and false otherwise.

  2. The digitsSum() method: This will take as a parameter an integer (of 6 digits) and return the sum of all its digits.

Look at the following implementation:

Get hands-on with 1200+ tech skills courses.