comp.lang.c
[Top] [All Lists]

Re: even or odd

Subject: Re: even or odd
From: pete
Date: Fri, 28 Mar 2008 07:43:18 -0500
Newsgroups: comp.lang.c

pete wrote:
> 
> melsayid wrote:
> >
> > The program always shows that the input is odd.
> 
> >      scanf ("%d", &n);
> >      d=1;
> 
> That's because (d=1) is always odd.

But that's not it. I read it wrong.

It's because this part of the code always prints
"The number is odd\n"
regardless of what happens in the loop.

     else if (d < n)
     {
          for (; d<n; d+=2);
          printf ("The number is odd\n");
     }

This is my version of the repaired algorithm:

/* BEGIN new.c */

#include <stdio.h>

int main(void)
{
    int n, d;
    
    printf ("Enter a Number: ");
    scanf ("%d", &n);
    d = 1;

    if (n > d) {
        do {
            d += 2;
        } while (n > d);
    } else {
        while (d > n) {
            n += 2;
        }
    }     
    if (d == n) {
        puts("The number is odd.");
    } else {
        puts("The number is even.");
    }
    return 0;
}

/* END new.c */


-- 
pete

<Prev in Thread] Current Thread [Next in Thread>
Privacy Policy