Search This Blog

Tuesday, 11 November 2014

Java Program to Separate the Individual Digit of a 3-Digit Number!

0 comments

PRINTING THE INDIVIDUAL DIGITS OF A NUMBER


AIM:  To write a program to print the individual digits of a 3-digit number.

ALGORITHM:
  1. Declare variables n and r of type int with in method main()
  2. Obtain the input for n through the command line argument args[], a string array.
  3. Convert the value of args[0] – the input, into integer and store it in n.
  4. Apply / (division operator) and find n/100 to separate the left most digit of n and print it
  5. Apply both / and % operators to separate the middle digit like this: (n/10)%10 and print it
  6. Apply only % (modulus operator) on n (n%10) to get the least significant and print it.

PROGRAM:
public class SeparatingDigits
{
    public static void main(String[] args) {
        int n,r;

        n = Integer.parseInt(args[0]);
        System.out.println("The Given Number is : " + n);
       
        System.out.println("The Individual Digits are : ");
        r = n / 100;     /*Find the First digit - which is in Hundre's place*/
        System.out.println(r);

        r = (n/10)%10;       /*Find the Second digit - which is in the Hundred's place)*/
        System.out.println(r);

        r = n%10;       /*Find the Right Most digit - which is in the One's place)*/
        System.out.println(r);
    }
}

Sample Run:
C:\DOCUME~1\ADMINI~1>cd\
C:\>cd java
C:\JAVA>cd bin
C:\JAVA\BIN>javac SeparatingDigits.java

C:\JAVA\BIN>java SeparatingDigits 764
The Given Number is : 764
The Individual Digits are :
7
6
4

Leave a Reply