简体   繁体   中英

How does % work on this C program? (sum of odd and even integers)

here's the code:

    #include <stdio.h>
#include <conio.h>
void main()
{
       int i, N, oddSum = 0, evenSum = 0;


printf("Enter the value of N\n");
    scanf ("%d", &N);
for (i=1; i <=N; i++)
      {
        if (i % 2 == 0)
            evenSum = evenSum + i;
        else
            oddSum = oddSum + i;
    }
printf ("Sum of all odd numbers  = %d\n", oddSum);
    printf ("Sum of all even numbers = %d\n", evenSum);

}

In this program it gets a number from user (N) and then prints sum of odd and even numbers in two different lines.

two questions:

1- how does % work here? 2- explain this line completely:

if (i % 2 == 0)
        evenSum = evenSum + i;

The % operator gives you the remainder of division.

An even number divided by 2 will always have a remainder of 0 regardless of sign. Odd numbers, if positive will have a remainder of 1 and if negative will have a remainder of -1 . You only need to test a single case to determine if it is even however, and that is what you see happening in your existing code.

It is more efficient to test the least significant bit to determine if a number is odd though:

if (i & 1)    // Example: 0101 (5) & 0001 (1) == 1
  // Odd

else          // Example: 0100 (4) & 0001 (1) == 0
  // Even

That approach does not involve division and only has two possible outcomes instead of three when dealing with signed integers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM