Input number and print largest and smallest digit in it using for loop in Java
for Loop - Question 13
In this question, we will see how to input a number and print the largest and the smallest digit in Java programming using for loop. To know more about for loop click on the for loop lesson.
Q13) Write a program in Java to input a number and print the largest and the smallest digit present in it using for loop.
Program
import java.util.Scanner;
public class Q13
{
public static void main(String args[])
{
int i,ld=-1,sd=10,n,d;
Scanner sc=new Scanner(System.in);
System.out.print("Enter a number ");
n=sc.nextInt();
for(i=n; i>0; i=i/10)
{
d=i%10;
if(d>ld) // storing the largest digit
{
ld=d;
}
if(d<sd) // storing the smallest digit
{
sd=d;
}
}
System.out.println("Largest Digit = " + ld);
System.out.print("Smallest Digit = " + sd);
}
}
Output
Enter a number 521964 Largest Digit = 9 Smallest Digit = 1