C++ Program to find the smallest digit in a given number

C++Server Side ProgrammingProgramming

Given a non-negative number, the task is to find its smallest digit.

For example


N = 154870



Explanation: In the given number '154870', the smallest digit is '0'.

Approach to Solve this Problem

The simplest approach to solve this problem is to extract the last digit in the given number using the remainder theorem. While traversing the number, we will check if the extracted digit is less than the last digit, then return the output.

  • Take a number as the input.
  • An integer function smallest_digit(int n) takes 'n' as the input and returns the smallest digit in the given number.
  • Now initialize min as the last digit of the given number.
  • Iterate through the number and check if the number extracted is less than the minimum number. If true, then update the minimum number and return the output.
  • Remove the last digit by n/10 and check if there is another digit which is lesser than the current digit.
  • Return the output.


Live Demo

#include <iostream>
using namespace std;
int smallest_digit(int n) {
   int min = n % 10; //assume that last digit is the smallest
   n /= 10; //to start from the second last digit
   while (n != 0) {
      if (min > n % 10)
         min = n % 10;
      n /= 10;
   return min;
int main() {
   int n = 154870;
   cout << smallest_digit(n);
   return 0;

Running the above code will generate the output as,



Explanation: In the given number '154870', the smallest digit is '0'.

Published on 23-Feb-2021 04:57:15