Click here to Skip to main content
15,891,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Given an Int input , find the sum of the individual number in the input.
Eg.

Please input number : 12345 <-- user input
1+2+3+4+5=15 <---output

What I have tried:

Problem #2
Now, whenever I have an input that ends or starts with a 0 it doesn't print it out.
eg. Please input number: 100
output: 1=1

Problem #1(Solved)
So I was able to write out the equations I need to get the sum of the numbers.

C++
while (input != 0)
   { 
      remainder = input % 10; 
      input = input / 10;
      sum = sum + remainder; }


However I cant figure out the logic behind printing it out, so that it shows 1+2+3.
(Solved, able to produce 1+2+3=6 output Thanks!)

C++
while (input!= 0)
   { 
      remainder = input% 10; 
      input= input/ 10;
	  sum       = sum + remainder;
       
	if(digits !=0)
	 { printf("+");}
     printf("%d", remainder);
	 digits++;	 
 
   }
Posted
Updated 7-Oct-17 3:57am
v5

It's a little complicated, because of the need to print "+" characters between them.
So add a counter:
C++
int digitCount = 0;
Inside the loop, check the counter and print the "+" if you need it:
C++
if (digitCounter != 0)
   {
   printf("+");
   }
digitCounter++;
Then still inside the loop print each digit:
C++
printf("%d", remainder);
After the loop, print the "=" and the sum.
 
Share this answer
 
Quote:
However I cant figure out the logic behind printing it out , so that it shows 1+2+3.

You have a few options:
- Store digits in a list as you are doing the slicing and sum and print them later as they came in reverse order.
- Build a string as you are doing the slicing and sum. "" > "5" > "4+5" > "3+4+5"
- convert input to string, then print chars 1 by 1 and insert '+'s as you do so.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900