Hi! I'm new to programming and I've found your video very helpful . I wanted to ask you something. Let's say that I wanted to print not just the sum of the digits of a given number, but, if the result is greater that 9, like in your case it was 12, is there a way to print 3 (1 + 2) instead of a two digit number?
@PortfolioCourses3 жыл бұрын
I might be able to help, but I'm not sure I understand. So instead of "12" you would want to print "1 + 2"? Or instead of "12" you would want to print "2 + 3 + 7", the numbers used to add up to "12"?
@carmenniro80213 жыл бұрын
In your video, the program prints 12 but, I'd want to print only one digit number. So in this case, before printing 12, the program has to sum the result and print 3
@PortfolioCourses3 жыл бұрын
@@carmenniro8021 Here is a version of the program that should do this. This one will keep summing the digits of the resulting sum until it is less than 10 (i.e. a one digit number). So it may sum the digits more thna one time. #include int main() { int number = 0; int sum = 0; int digit = 0; printf("Enter number: "); scanf("%d", &number); int sums = 0; do { // reset variables if necessary if (sums > 0) { number = sum; sum = 0; } while (number != 0) { digit = number % 10; sum += digit; number = number / 10; } sums++; } while (sum >= 10); printf("sum: %d ", sum); return 0; }
@carmenniro80213 жыл бұрын
@@PortfolioCourses thank you! 😊
@ReginaldCGray Жыл бұрын
Great but what if they enter a negative number how do you handle that using this code
@PortfolioCourses Жыл бұрын
This code is not created to handle negative numbers. You could always apply abs() to the negative number before this algorithm to make the number positive: www.tutorialspoint.com/c_standard_library/c_function_abs.htm. :-)