A09 Answer


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

/* Puzzle A09 -- add up even, odd and all integers from 0 to N 
|                except those integers divisible by 3 or 4.
*/ int main(int argc, char *argv[]) { int j; int sumAll = 0, sumOdd = 0, sumEven = 0; int n; printf("Enter n: "); scanf("%d", &n ); for (j=0; j<=n; j++ ) { if ( j%3 != 0 && j%4 != 0 ) { sumAll += j; if ( j%2 == 0 ) sumEven += j; else sumOdd += j; } } printf("Sum = %4d, Sum of Odd = %4d, Sum of Even = %4d\n", sumAll, sumOdd, sumEven); system("PAUSE"); return 0; }

Comments:

1. If an integer j can be divided by 3, then j%3 == 0. Also, if an integer j can be divided by 4, then j%4 == 0. So to exclude those integers that are divisible by 3 or by 4 use the following:

 if (j%3 != 0 && j%4 != 0)

This is an excellent opportunity to review the precidence of operators in C. You need to know that the precidence of % is higher than the precidence of != , and (out of %, !=, &&) the precidence of && is lowest of all. Look in your C book for a table. For example, Table 5.1 in Reek's text.

If you are unsure about the precidence, you might write the expression like this:

 if ( (j%3 != 0) && (j%4 != 0) )

This would be OK, and to my eyes looks better.

2. Yet another way to do the same thing is:

 if ( !( (j%3 == 0) || (j%4 == 0) ) )

To understand this, recall one of DeMorgan's Laws:

 !(A || B) == !A && !B

The other DeMorgan Law is:

 !(A && B) == !A || !B

These laws are essential for making sense of programming logic. If you really want to practice, try writing several more versions of the program using different, but equivalent expressions in the if statement.

3. In C, any value other than 0 counts as true. So the integers returned by the % operator can be used directly as true/false values. The if statment could be written:

 if (j%3 && j%4)

Although legal, and logically correct, I don't think this is wise. It does not say clearly what you want to express, and does not result in better code.