Problem Solving: Sum of Digits (revisited)
Learn to implement programs using functions in C++.
We'll cover the following
So let’s start with our first problem, which is the sum of digits!
Sum of digits
This program requires three main steps.
-
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.
-
To calculate the sum of all its digits.
-
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.
-
The
valid6Digit()
method: This takes an integer as a parameter and returnstrue
if the number is a 6-digit number andfalse
otherwise. -
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.