Entry Level C++ Problems: Sum of Digits

Write a program that sums all individual digits of a number given by the user. Make sure that the number has at least two digits. 
So the problem here can be divided into two smaller problems. We need user input and we need an algorithm that'll parse the number into its individual digits. 
First of all we need a variable which will store this number and ask the user to input a two digit number and not let the program proceed unless it receives it. We could achieve it by having an if statement in there such as the one shown below:
#include <iostream>

int main()
{
	int number = 0;

	std::cout << "Input a number < 10: ";
	std::cin >> number;

	if (number < 10)
	{
		std::cout << "Number " << number 
			<< "is not lesser than 10. Try again.";
	}

	return 0;
}
The problem here is that the conditional will only check the number and then run through the rest of the code because there is nothing stopping it from proceeding. In order to prevent that we need to use a loop that'll iterate until the condition is met. We can use while loop to achieve that. The if statement can stay there to let the users know why they're not getting the results though. 
#include <iostream>

int main()
{
	int number = 0;

	while (number < 10)
	{
		std::cout << "Input a number < 10: ";
		std::cin >> number;

		if (number < 10)
		{
			std::cout << "Number " << number 
				<< "is not lesser than 10. Try again.";
		}
	}

	return 0;
}
So this loop will carry on repeating for as long as the number typed in by the user is less than 10.

Moving onto the next part of the problem which is the actual algorithm. Once the user finally inputs the number, we'll need to parse it into its individual components and sum them. Here we could utilise a modulo to do so. If we divide a number by 10, its remainder will be its last digit. 
DividendDivisorQuotientRemainder
1234101234
12310123
121012
11001
We could then sum the remainders and we get what we want. We'll need a loop that will run until the remainder is greater than 0 (because the program has no way to look at the number before we type it in), and update the variable that stores the number with the new dividend. The final quotient will be 0 (as you can see in the table above) which will break the loop. We'll also need a variable that'll store the sum of all digits. This is the complete program:
#include <iostream>

int main()
{
	int number = 0;
	int sum=0;

	while (number < 10)
	{
		std::cout << "Input a number < 10: ";
		std::cin >> number;

		if (number < 10)
		{
			std::cout << "Number " << number 
				<< "is not lesser than 10. Try again.";
		}
	}


	while (number > 0)
	{

		sum = sum + (number % 10);
		number = number / 10;

	}

	std::cout << std::endl;
	std::cout << "Sum of the individual digits is equal to: " 
		<< sum << std::endl;

	return 0;
}
HYPER!locrian

Leave a Reply

Discover more from NMKN Studio

Subscribe now to keep reading and get access to the full archive.

Continue reading