Click here to Skip to main content
15,885,890 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i have a homework from an input of "2 3 5 -2 20 0 " till we meet 0 to find all even numbers. I wrote :

#include <stdio.h>

int main()
{
    int i, n;
  
    scanf("%d", &n);

    printf("I found %d even numbers \n", n);

    for(i=1; i<=n; i++)
    {
        
        if(i%2 == 0)
        {
            printf("%d\n", i);
        }
    }

    return 0;
}


when i print it finds there are 2 even numbers . i think i dont recognize the negative number . how can i correct that?

What I have tried:

.........................................
Posted
Updated 20-Nov-22 11:02am
v2
Comments
Richard MacCutchan 20-Nov-22 8:27am    
Because you are printing the message before you test any of the numbers.

When doing the test, use the abs function to make sure the value tested is a positive value. Here is more information on it: C library function - abs()[^]
 
Share this answer
 
Comments
Bogdan Alexandru Oct2022 20-Nov-22 7:10am    
can u tell me how to write it pls?
0x01AA 20-Nov-22 7:16am    
Modulo is defined also for negative numbers, I'm sure you know that. The 'for' is more the problem I think.
Graeme_Grant 20-Nov-22 7:17am    
Yes, am aware.
To add to what Graeme has said, the simplest solution is to ignore all the odd ones.
Instead of starting your loop at 1 and increasing it by 1, start it at 2 and increase it by 2:
C
for (int i = 2; i <= n; i += 2)
   ...
Since all the even number are multiples of two, why look at the intervening numbers at all?
 
Share this answer
 
Quote:
when i print it finds there are 2 even numbers
because your program just prints the first integer of the input sequence.

As matter of fact, if you feed it with the input sequence
3 19 27 42
it then prints
I found 3 even numbers

As it stands, your program is completely broken. You're given an input sequence that you must entirely process (well, you must process it until you find 0).

Try the following approach:
  1. define a counter of even numbers, say even_count and initialise it with 0.
  2. read an integer, say n from the input sequence (use scanf).
  3. if n==0 the print the value of the even_counter and exit the program
  4. here n is non-zero, check for its parity: if n is even the increment the even_count
  5. goto point 2
 
Share this answer
 
v2
Quote:
input of "2 3 5 -2 20 0 " till we meet 0

1. the result is output without searching an array
2. where is the array and why is n read in?
3. why is the index searched instead of the elements of an array?
Note: Even without abs() the result is 2,-2,20 - "I found 3 even numbers".
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900