Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

while-loop

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;
}
like image 557
Gen Avatar asked Nov 16 '25 09:11

Gen


2 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);
}
like image 52
Bob__ Avatar answered Nov 19 '25 00:11

Bob__


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;

}

like image 35
Yazid Med Avatar answered Nov 19 '25 00:11

Yazid Med



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!