Why the conditional statement is not giving the correct answer?

After scanning all array elements how can i printf even and odd seperately.

#include <stdio.h>  
void  main()  
{  
    int arr[100]; 
    int n,i;
    printf("Number of Elements:-");
    scanf("%d",&n);
    for (i=0;i<=n;i=i+1)
    {
        printf("Elem %d:-",i);
        scanf("%d",&arr[i]);
    }
        for(i=0;i<=n;i=i+1)
        {
            if(arr[i]/2==0)
            {
                printf("Even%d\n",arr[i]);
            }
            else
            {
                printf("odd%d\n",arr[i]);
            }
        }

}

Output:

Number of Elements:-4
Elem 0:-1
Elem 1:-2
Elem 2:-3
Elem 3:-4
Elem 4:-5
Even1
odd2
odd3
odd4
odd5

>Solution :

The conventional way to write your loop is:

for( i=0; i<n; ++i )
{
    printf("%s %d\n", (arr[i]%2)? "Odd" : "Even", arr[i]);
}

In C, most loops have an initial condition of var=0, run while var<target, and increment with ++var (some people prefer var++)

The conventional way to test if a number is even or odd is using the Modulo (%) operator, not using division (/).

Why do you think a an expression like 10/2 would ever equal 0??

10 is clearly even, dividing by 2 gives 5, not zero!!?


Putting it all together, I got:

#include <stdio.h> 
#include <stdlib.h>

int main(void)  
{  
    int arr[100]; 
    int n = 20;
    
    for ( int i=0; i<n; ++i )
    {
        arr[i] = rand() % 100;
        // Replaced user-input with pseudo-random numbers, for ease and simplicity. 
        // You can stick with scanf if you want.
    }
    
    for( int i=0; i<n; ++i )
    {
        printf("%-4s %d\n", (arr[i]%2)? "Odd" : "Even", arr[i]);
    }
    
    return 0;
}

Output:

Success #stdin #stdout 0.01s 5404KB
Odd  83
Even 86
Odd  77
Odd  15
Odd  93
Odd  35
Even 86
Even 92
Odd  49
Odd  21
Even 62
Odd  27
Even 90
Odd  59
Odd  63
Even 26
Even 40
Even 26
Even 72
Even 36

Leave a Reply