[Solved] How to split each digit in a given number with respect to their digit places?


It would be better to use a while loop so you wouldn’t have to hard code the number of digits. Your code is correct, although I’m assuming you need to print out the output in the correct order. You could do this by keeping it in an array. Instead of specifying each of the places by multiplying each digit by 10, 100, 1000, etc. , you could see that the powers of 10 correspond to each index when you are calculating the digits.

int number;
int digits[100];
int numDigits=0;
cin>>number;
while(number>0){
    digits[numDigits]=number%10; //Modulo ten to get the current digit
    for(int i=0; i<numDigits; i++){  //Loop through whatever digit you are on to retain the place 
        digits[numDigits]*=10;
    }
    number/=10;  //Divide by ten to get the next digit at the front
    numDigits++;  //Increment the number of digits by one
}
for(int i=numDigits-1; i>=0; i--){  //Print out the digits of the number backwards for desired output
    cout<<digits[i]<<endl; 
}

0

solved How to split each digit in a given number with respect to their digit places?