# Calculating the sum of digits times the length of string

Last week i had a project from my teacher asking me to develop a program which takes in a string (stream of integers to be precise) and calculates the sum of the numbers in the string for each number in the string ie.

if input is 31456

• 1st loop does nothing (no number to left of 3 with result of sum as 0)
• 2nd loop ends on 3 (with result of sum as 3)
• 3rd loop ends on 1 (with result of 3+1 = 4)
• 4th loop ends on 4 (with result of 3+1+4 = 8)
• 5th loop ends on 5 (with result of 3+1+4+5 = 13)
• 6th loop ends on 6 (with result of 3+1+4+5+6 = 19)

I did submit a working project but it is full of spaghetti code (nested loops which ends if string length is less than the number of loops) which is not a clean approach. I wondered and studied a quite a lot over this situation in vain. I have not found any way of doing this without nested for loops in C (or maybe i gave up too fast ?)

Again, i am not asking you guys for an answer to my problem but wanted to know if there is a way of doing this without the nested loops (which will have problem if length of input > number of nested loops).

Here is my advice: stop thinking in "loops" and start thinking in "steps". If the input string has n characters, you have n+1 steps.

Now, ponder the following three questions:

1. Do you know the solution to the first step (no digits)?
2. Given the solution to step k, how can you compute the solution to step k+1?
3. How can you combine questions 1 and 2 to solve your entire problem with just a single loop?

Since this is homework, I'll let you take it from here.