How to print decreasing odd numbers starting from scanf input integer in C?

Viewed 356

If you input even numbers, only the odd numbers will be printed until it reaches 0. (0 will not be printed). For example, if you input 10, the output would be 9, 7, 5, 3, 1.

This is what I came up with. I'm wondering what should I decrement x by to get the desired output.

int x;
scanf("%d", &x);
while (x >= 0) {
  printf("%d", x);
  x = x - 2;
}
3 Answers

I'm wondering what should I decrement x by to get the desired output.

Subtracting 2 is fine, as long as you always start from an odd number. So you could change the loop into something like this:

for ( int i = x % 2 ? x : x - 1; // Is x odd? good. 
                                 // Otherwise, start from the previous one.
      i > 0;
      i -= 2 ) {
    printf("%d\n", i);
}
int x, n;


printf("Give N: ");
scanf("%d", &n);

printf("odd numbers from 1 to %d are: \n", n);
x=n;
while(x<=n && x>0)
{
    if(x%2!=0)
    {
        printf("%d\n", x);
    }
    x--;
}

return 0;

}

Your code was almost correct (indeed, it is a pity that you have selected as the correct question such a bad response) I will show you where is your error:

int x;
scanf("%d", &x);

if (x % 2 == 0) /* if the number is even */
    x = x - 1;  /* decrement it to convert it in an odd number */

while (x >= 0) {
  printf("%d", x);
  x = x - 2;
}

The thing is that you start your question with exactly that assert (if you input even numbers...)

Another problem is that you don't say what should happen when you introduce an odd number. Anyway, the code printed it, and all the odd numbers until we reach 0.

Why your code is better than the selected one? because your code only wastes time in the loop with the valid results, and doesn't get into the loop to decide that it has nothing to do. This saves a lot of loop executions (almost half of them) which, if your number is very large, can do your program a lot more efficient.

Related