Dremendo Tag Line

Input a number and find the largest digit in it using a function in Java

Function - Question 3

In this question, we will see how to input a number and find the largest digit in it in Java programming using a function. To know more about function click on the function lesson.

Q3) Write a program in Java to input a number and find the largest digit in it using a function.

Program

import java.util.Scanner;

public class Q3
{
    public static int largestdigit(int num)
    {
        int ld=0,d;
        while(num>0)
        {
            d=num%10;
            if(d>ld)
            {
                ld=d;
            }
            num=num/10;
        }
        return ld;
    }

    public static void main(String args[])
    {
        int n;
        Scanner sc=new Scanner(System.in);
        System.out.print("Enter a number ");
        n=sc.nextInt();
        System.out.print("Largest Digit = " + largestdigit(n));
    }
}

Output

Enter a number 78261
Largest Digit = 8
video-poster