0
Develop a program to calculate the sum of digits in a given number by using while loop
Solve and explain
3 Respostas
+ 5
Open compiler and start coding.😊
Best of luck 🤞
If you face any issue in your code, you can share with us.
+ 4
Bannu Sivareddy to get the digits of a number you could convert the number to a string and loop through the characters, converting each digit character back to a numeric value to find the sum.
Another way is to do it mathematically. If the number is a positive integer then you can use modulo 10 to get the lowest digit. Then, using integer math, divide the number by 10 to shift its next digit down to the lowest digit to prepare for the next iteration. Loop while the number is non-zero.
If the number may be negative, then use its absolute value for the above loop.
If the number is a decimal value (floating point) the string approach might be best.
+ 1
hint: don't forget to increment the counter on the bottom of the while loop