C++ Program to find largest and smallest digit of a number


In this program, You will learn How to find largest and smallest digit of a number in C++.


Number is : 1234

Largest digit is : 4

Smallest digit is : 1


Example: How to find largest and smallest digit of a number in C++

Run it Now
#include<iostream>
using namespace std;

int main() {

   int n, r, sd = 9, ld = 0;

   cout << "Enter a Number :";
   cin>>n;

   while (n > 0) {
       r = n % 10;
       if (sd > r) {
           sd = r;
       }
       if (ld < r) {
           ld = r;
       }
       n = n / 10;
   }
   cout << "\nThe Largest Digit :" << ld;
   cout << "\nThe Smallest Digit :" << sd;

   return 0;
}
 

Output:

Enter a Number :8459
The Largest Digit :9
The Smallest Digit :4