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;
%
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.
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.