I'm using C. I expected this condition in the while loop to prevent any even value bigger than 4 million from being summed in my "sum" variable:
while ( (box1 < 4000000) || (box2 < 4000000) || (box3 < 4000000)) {
box3 = box1 + box2;
if (box3 % 2 == 0) /* checks if box is even */
sum += box3; /* if TRUE adds even value to the variable sum */
box1 = box3 + box2;/* exceeded 4 millions on 12th loop */
if (box1 % 2 == 0)
sum += box1;
box2 = box3 + box1;
if (box2 % 2 == 0)
sum += box2;/* then summed undesired value here */
printf("%d\n", sum);
}
It didn't come to my mind at all the possibility of the boxes exceeding 4 millions in the first or second statement within the loop. That happened and it took me a good while till I figure my program was summing one extra value before the while checks the condition again. I hope you to forgive me and have a little patience for making you spend your precious time here but I need to know if experienced programmers know how to avoid such simple, but annoying errors.
If that is true I would be very glad for having an opportunity to learn from better programmers. Thanks
To showcase a correct way to think about this, as noted in comments - the technique here is to recognise that you are repeating the same code snippet three times and that two out of those three are not checked properly. It is usually called the DRY principle ("Don't Repeat Yourself"). Having noticed this, you refactor your code so that "it is DRY". A DRY code has less points of failure than non-DRY one, which obviously reduces the possibility of an error.
int previous = 1, current = 1;
int next;
int sum = 0;
// single test for end
while (current < 4000000) {
// test for evenness
if (current % 2 == 0) {
sum += current;
}
// next value
next = previous + current;
// shuffle values around so you can reuse the same code
previous = current;
current = next;
}
Also note that if the variables are named box1
, box2
and box3
, no-one can read your code comfortably - and that includes your future self. Depending on the complexity, in one to six months you will have no idea what you wrote; having sensible names is pretty crucial for smooth maintenance.
However, note that these are only some of the principles of good code. Most of them come, as noted by many commenters, through experience. You start noticing "code smell", and when you do, you refactor it so it doesn't smell any more.
(Also, as noted in comments, general questions on the programming craft should go to https://softwareengineering.stackexchange.com/ ; Stack Overflow is more focused on specific problems. And if you do a search of that site, there are a number of threads that discuss good or maintainable code.)