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++.


int main(){
   //statement
}

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

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

#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 << "Largest digit:" << ld;
   cout << "\nSmallest digit:" << sd;

   return 0;
}

Output:

Enter a number:4323 
Largest digit:4
Smallest digit:2