Again we will get the remainder of this number with the use of modulus operator, dividing the number by 10 (i.e. 123 % 10). Now we will get 3 and display it on the screen. To get the new number with two digits, divide the number by 10. Once again, we get the next digit of the number (i.e. 12) by using the modulus operator with 10, get the digit 2 and display it on the screen. Again get the new number by dividing it by 10 (i.e. 1). We can show it directly, as it is the last digit, or take remainder by using modulus operator with 10. In this way, we get all the digits of the number.

Now let’s write the program in C by following the analysis we have made. The complete C program for the above problem is given below. It is easy to understand as we are already familiar with the statements used in it.

 

#include <iostream.h>

 

main()

{

            //declare variables

            int number, digit;

 

            //prompt the user for input

           cout << "Please enter 4-digit number:";

           cin >> number;

          

           // get the first digit and display it on screen

            digit = number % 10;

           cout << "The digits are: ";

           cout << digit << ", ";

          

           // get the remaining three digits number

           number = number / 10;

          

            // get the next digit and display it

           digit = number % 10;

           cout << digit << ", ";

          

           // get the remaining two digits number

           number = number / 10;

          

            // get the next digit and display it

            digit = number % 10;

           cout << digit << ", ";

          

           // get the remaining one digit number

           number = number / 10;

          

           // get the next digit and display it

           digit = number % 10;

           cout << digit;    

}

 

 

 

Previous

 

 

TOC

 

 

Next