PRINTING THE
INDIVIDUAL DIGITS OF A NUMBER
AIM: To write a program to print the individual
digits of a 3-digit number.
ALGORITHM:
- Declare
variables n and r of type int with in method main()
- Obtain
the input for n through the command line argument args[], a string array.
- Convert
the value of args[0] – the input, into integer and store it in n.
- Apply
/ (division operator) and find n/100
to separate the left most digit of n
and print it
- Apply
both / and % operators to separate the middle digit like this: (n/10)%10
and print it
- 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