Split a number to individual digits in C | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Split a number to individual digits in C

I need a Program that will split a number entered by user into individual digits, but I got a problem with it. This is my code. https://code.sololearn.com/cLH3h9ZVNYdu/?ref=app Here: If user enters 124, it results; 4 2 1. But I need it to print. 1 2 4. How can I do it, please help me. Using for/ while loop is acceptable. Thank you.

5th Nov 2020, 2:35 AM
Bibek Oli
Bibek Oli - avatar
3 Answers
+ 7
//Replace the for statement with this for(; num != 0; num /= 10)
5th Nov 2020, 2:55 AM
ツSampriya😘ツ
ツSampriya😘ツ - avatar
+ 5
Bibek Oli the loop of I is for digits if it's 3 digit make it 100 and as digits increase add 0 to the limit. It's an dirty and quick fix it you only want to use one loop. https://code.sololearn.com/c4DOOAvnTkt9/?ref=app
5th Nov 2020, 3:39 AM
Preity
Preity - avatar
+ 3
Preity, good work on the quick fix! That inspired me to take it to the next level and demonstrate how to calculate the magnitude of a number in order to set the loop limit. Bibek Oli here I built on Preity's code to auto-adjust for the number of digits. Also it handles negative numbers. https://code.sololearn.com/cm8yvLCDo5yE/?ref=app
5th Nov 2020, 10:00 AM
Brian
Brian - avatar