This is an exercise from a textbook
Problem:
Write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits. For example, it should output the individual digits of 3456 as 3 4 5 6, output the individual digits of 8030 as 8 0 3 0, output the individual digits of 2345526 as 2 3 4 5 5 2 6, output the individual digits of 4000 as 4 0 0 0, and output the individual digits of -2345 as 2 3 4 5.
This problem was found in Chapter 5 of a C++ Textbook, which means, this problem was meant to be solved with the concepts covered by the first 5 chapters only.
Here are the Chapters and what each chapter covered
1. Chapter 2: Declare Variables, Variable Types, <iostream>
2. Chapter 3: Input / Output, <iomanip> <cmath> <fstream>
3. Chapter 4: Control Structure (Selection), if, else if, else, switch
4. Chapter 5: Control Structure (Repetition), while, do-while, for loop, nested loops
To solve this problem, this is the algorithm I used
1. Find the number of digits in a given integer
2. Find nth power of 10 with the # of digits so individual digits can be taken off from the left (Ex: 4321, take off 4 by dividing by 10^3)
3. Print each individual digit while calculating sum
4. Print sum
It took me some time, but eventually, I came up with a solution. I can usually solve a problem, but I find that the solution is sometimes more complicated than it needs to be and I can't seem to really optimize it.
If you can show me an example of a simpler and more efficient solution, I'd appreciate it.
To me, the goal is to improve my problem-solving skills with limited tools before I dive into more advanced C++ concepts.
Thank You.
This is my solution to the problem using only the concepts listed above.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
#include <iostream>
#include <cmath>
int main ()
{
int integer;
int numberOfDigits = 0;
int digit = 0;
int sum = 0;
std::cout << "Enter an integer: ";
std::cin >> integer;
std::cout << std::endl;
integer = std::abs ( integer ); // Convert neg value to abs
int copyInteger = integer; // Create a working copy of integer
// Find the number of digits
do
{
numberOfDigits ++;
copyInteger /= 10;
}
while ( copyInteger != 0 );
int divisor = std::pow ( 10 , numberOfDigits - 1 );
// Take out each digit from the left, calculate sum and print the digit
do
{
digit = integer / divisor; // Take out a digit
integer = integer - ( digit * divisor ); // Update integer
std::cout << digit << ' ';
sum += digit;
divisor /= 10; // Take a zero off the divisor
}
while ( divisor > 0 );
std::cout << "\nSum = " << sum << std::endl;
return 0;
}
|