Search code examples
cmathradix

Write a program in C that outputs the smallest natural number greater or equal to n whose all digits are even


Write a program in C that will take a natural number n and output the smallest natural number greater or equal to n whose all digits are even in decimal. For example, if n = 16, it should output 20, and if n = 41, it should output 42. What I have tried:

#include <stdio.h>

int main(void) {
  int n, i, condition = 0;

  scanf("%d", &n);
  for (i = n; i >= n; i++) {
    if (i % 2 == 0) {
      i = i / 10;
      while (i > 0) {
        if (i % 2 == 0) {
          i = i / 10;
          condition = 1;
        } else {
          break;
        }
      }
    } else {
      condition = 0;
    }
    if (condition == 1) {
      printf("%d", i);
      break;
    }
  }
  return 0;
}

Why doesn't this work?


Solution

  • You're printing the i after making it 0 i.e dividing it by 10 until first digit comes. So, it'll print 0 in every case.

    Instead you should try assigning the value of i to another variable so you don't have to change i. Also after it becomes 0 by first iteration it won't make other iterations due to the requirement i>=n in the for loop.

    #include <stdio.h>
    
    int main(void) {
    int n;
    scanf("%d", &n);
    for (int i = n; i >= n; i++){
        int num = i;
        int cond = 0;
        while(num>0){
            int dig = num%10;
            if(dig%2 != 0){
            cond = 1;
            break;
            }
        num/=10;
        }
        if (cond ==0){
            printf("%d",i);
            break;
        }
     }
     return 0;
    }