Program to find largest and smallest digit in a Number

Description

To find largest and smallest digit in a number, extract digit from number
and compare this with maximum and minimum. Follow the below code.
Example: Number - 543682
			Smallest Number - 2
			Largest Number - 8

C/C++

/* C Program to find largest and smallest digit in a number */
//Save it as LargestSmallestDigitInNumber.c

#include<stdio.h>
#include<limits.h>
int main(){

    int max=INT_MIN;
    int min=INT_MAX;

    int rem, num;

    printf("Enter a number : ");
    scanf("%d",&num);

    while(num > 0) {

        //Extracting digits from number
        rem = num % 10;

        //checking minimum digit in number
        if(rem < min) {
            min = rem;
        }

        //checking maximum digit in number
        if(rem > max) {
            max = rem;
        }

        num /= 10;
    }

    printf("Max : %d Min : %d", max, min);

    return 0;
}
Input:
Enter a number : 18265

Output:
Max : 8 Min : 1

Java

/* Java Program to find largest and smallest digit in a number */
//Save it as LargestSmallestDigitInNumber.java

import java.io.*;
import java.util.Scanner;

public class LargestSmallestDigitInNumber {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        
        System.out.println("Enter a number : ");
        int num = scanner.nextInt();
        
        int max=Integer.MIN_VALUE;
        int min=Integer.MAX_VALUE;
        int rem;
        
        while(num > 0) {
            
            //Extracting digits from number
            rem = num % 10;
            
            //checking minimum digit in number
            if(rem < min) {
                min = rem;
            }
            
            //checking maximum digit in number
            if(rem > max) {
                max = rem;
            }
            
            num /= 10;
        }
        
        System.out.println("Max : "+max+" Min : "+min);
    }
}
Input:
Enter a number : 
18265

Output:
Max : 8 Min : 1

Related programs

1) Program to find largest and smallest character in a String
2) Find Smallest element and it’s position of an Array
3) Program for finding Second Largest Element Of Array
4) Program to form a number using entered digits
5) Program to Find the smallest missing number
6) Program to Find missing odd number in first n odd number
7) Program to generate Random number in a given Range
8) Program to reverse a number
9) Program to Check Leap Year
10) Program to find maximum and second maximum if elements of array is space separated input
Share Me

Leave a Reply