How to split an Int number into digits in C++

In this tutorial, we will learn how to split an integer number into single digits in C++. So it will be an easy code in which we will take a number and split it into digits and show all the digits as output.

Split an integer number into digits in C++

Let’s see an example where we will split the 4 digit number.

#include<iostream>
using namespace std;
int main()
{
    //declare variables
    int number=4356;
    int digit[4];

    //defining a loop for splitting the number
    for(int i=0; i<4 ; i++)
    {
        digit[i]=number%10;
        number=number/10;
    }
    //for reading the digits stored in digits array
    cout <<"digits are"<<endl;
    for(int j=3 ; j>=0 ; j-- )
    {
        cout<<digit[j]<<", ";
    }


}

 

Explanation

  1. First, we have declared integer variable “number” in which we have stored the 4 digit number.
  2. We have defined an array “digit” whose size is the same as the integer number we have taken.
  3. Then we have defined a loop for splitting the input number into digits.
  4.  When we perform a mod operation between two numbers then we get the remainder as output after dividing the numbers. For example, 103%10 will give us 3 as a result because on dividing 103 by 10 we get 3 as the remainder.
  5. So inside the first loop, the mod operation is performed on the input number with 10 and the output is being saved in the array from the last index.
  6. If we take “103” as the input number then the value of n will be 3 (size of number) and after mod operation “3” will be taken from “103” and get stored in the “digit” array.
  7. After that, we are updating our input number value. As variable “number” is defined as an integer so after every iteration input number will be divided by 10 and the output in which the number after the decimal is removed will get stored in the variable “number”.
  8. So if we take”103″ after the first iteration its value will become “10” and will be stored in the variable “number”.
  9. At last, we are using a for loop for reading all the digits stored in an array.

Output

   digits are
4, 3, 5, 6,
Process returned 0 (0x0) execution time : 0.083 s
Press any key to continue.

Also read: Show two digits after decimal point in C++

Leave a Reply

Your email address will not be published.