0

I need to extract the odd number out and give the output, but when I execute the code, it gives me in reverse order (e.g. expected output is1234 = 13 but my code gave me 31).

int digit, num;
while (num > 0)
{
     digit = num % 10; 
    if(digit % 2 != 0)
    {
     printf("%d" , digit);
    }

    num /= 10;
}
Chris Tang
  • 567
  • 7
  • 18
k123
  • 13
  • 3

4 Answers4

4

That is because you are first printing the remainder from the division operation in the following statement:

digit = num % 10; 

You have to store it in an array and after all the divisions are complete only print it.

P.W
  • 26,289
  • 6
  • 39
  • 76
1

you're printing the units first. So you need either to store the data, or to use a recursive approach so last numbers are printed first:

#include <stdio.h>

void podd(int num)
{
   if (num > 0)
   {
      int digit = num % 10;
      if (digit % 2)
      {
        printf("%d" , digit);
      }
      podd(num / 10);
   }
}


int main() 
{
  podd(1234);
  printf("\n");
  return 0;
}

(variation of the classic int to string conversion problem described here: Convert integer to string without access to libraries)

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0

Obviously, It will output 31.

Coz,

1st iteration in while loop =>

num is 1234

digit = num % 10; digit = 1234 % 10 ( It's 4)

if(digit % 2 != 0)
    {
     printf("%d" , digit);
    }

4 will not print coz 4 % 2 != 0 will return false.

num /= 10; num = 1234 / 10 ( num is now 123)

2nd iteration in while loop =>

num is 123

digit = num % 10; digit = 123 % 10 ( It's 3)

if(digit % 2 != 0)
    {
     printf("%d" , digit);
    }

3 will be printed coz 4 % 2 != 0 will return true.

num /= 10; num = 123 / 10 ( num is now 12)

So ... we got our first number 3.

So, if you continue this process (it's called debugging ) for the next while loop iterations you will find the final output ... that's 31.

Rafaf Tahsin
  • 7,652
  • 4
  • 28
  • 45
0

The direct answer as follows:

int num = 1234, digit = 0;
do {
    digit = num % 10;           // Assigns the extracted digit to a variable named digit (ex: 4).
    if (digit % 2 != 0)         // Applies the formula to get the odd number.
        printf("%d\n", digit);  // Prints the odd number.
    num /= 10;                  // Extracts one digit each time (ex: 1234 / 10 = 123).
} while (num > 0);              // Has reached the end of the number 'num'.

The Result:

3
1

Lion King
  • 32,851
  • 25
  • 81
  • 143