0

Develop a program to calculate the sum of digits in a given number by using while loop

Solve and explain

16th Oct 2024, 4:56 PM
Bannu Sivareddy
Bannu Sivareddy - avatar
3 Antworten
+ 5
Open compiler and start coding.😊 Best of luck 🤞 If you face any issue in your code, you can share with us.
16th Oct 2024, 4:58 PM
Gulshan Mahawar
Gulshan Mahawar - avatar
+ 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.
17th Oct 2024, 3:32 PM
Brian
Brian - avatar
+ 1
hint: don't forget to increment the counter on the bottom of the while loop
16th Oct 2024, 6:05 PM
Mihaly Nyilas
Mihaly Nyilas - avatar