[Solved] Why dοes this code output 1?

Introduction

This question is about understanding the output of a particular code snippet. The code in question is a simple one-liner that outputs the number 1. It is important to understand why this code outputs 1 in order to understand the fundamentals of programming. In this article, we will discuss the reasons why this code outputs 1 and how it works.

Solution

The code outputs 1 because it is using the modulo operator (%) to divide the number 5 by 2 and return the remainder. Since 5 divided by 2 is 2 with a remainder of 1, the code outputs 1.


The code can be roughly translated to the English:

Start with a sum of zero then, for every number from 0 to 9 inclusive, add it to the sum if and only if the current sum is even.

So, you’ll add zero to the sum (because the sum is currently even) after which the sum will still be zero (hence even).

Then you’ll add one to the sum (because the sum is currently even) after which the sum will be one (hence odd).

Then you’ll never add anything to the sum again (because it’s odd and will remain so because you’re not adding anything to it).

That’s why it outputs one.


You may find it more instructive to simply modify your program to output what it’s “thinking”. The following changes will hopefully make it easier to understand:

#include <iostream>
using namespace std;

int main(void) {
    int sum = 0;
    for (int i = 0; i < 10; i++) {
        cout << "Processing " << i
             << ", sum is " << sum
             << ((sum % 2 == 0) ? " (even):" : " (odd): ");
        if (sum % 2 == 0) {
            sum += i;
            cout << "adding " << i << " to get " << sum;
        } else {
            cout << "leaving at " << sum;
        }
        cout << '\n';
    }
    cout << "Final value is " << sum << '\n';
}

Running that code will show you the steps along the way:

Processing 0, sum is 0 (even): adding 0 to get 0
Processing 1, sum is 0 (even): adding 1 to get 1
Processing 2, sum is 1 (odd):  leaving at 1
Processing 3, sum is 1 (odd):  leaving at 1
Processing 4, sum is 1 (odd):  leaving at 1
Processing 5, sum is 1 (odd):  leaving at 1
Processing 6, sum is 1 (odd):  leaving at 1
Processing 7, sum is 1 (odd):  leaving at 1
Processing 8, sum is 1 (odd):  leaving at 1
Processing 9, sum is 1 (odd):  leaving at 1
Final value is 1

0

solved Why dοes this code output 1?