Largest even digit number not greater than N in C++

In this tutorial, we are going to write a program that finds the largest number whose digits are all even and not greater than the given n.

Let's see the steps to solve the problem.

  • Initialise the number n.
  • Write a loop from i = n .
    • Check whether the digits of current number are all even or not.
    • If the above condition satisfies, then print the number.
    • Else decrement the i.


Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int allDigitsEven(int n) {
   while (n) {
      if ((n % 10) % 2){
         return 0;
      n /= 10;
   return 1;
int findLargestEvenNumber(int n) {
   int i = n;
   while (true) {
      if (allDigitsEven(i)) {
         return i;
int main() {
   int N = 43;
   cout << findLargestEvenNumber(N) << endl;
   return 0;


If you run the above code, then you will get the following result.



If you have any queries in the tutorial, mention them in the comment section.

Updated on: 09-Apr-2021


Kickstart Your Career

Get certified by completing the course

Get Started