Summing Even Digits in an Integer with C++ Loops

Introduction

Welcome to another exciting session! In today's lesson, we face a unique coding challenge. We will traverse the digits of a number using a while loop under a specific condition. You will hone your skills in working with C++ loops and conditional statements, both of which are fundamental building blocks of programming. Shall we begin?

Task Statement

Solution Building: Step 1

We begin by setting the basic structure for our function. In this step, we define a variable, digit_sum, that will accumulate the sum of the even digits.

Here's the initial framework of our function:

int solution(int n) {
    int digit_sum = 0;
    // The function expands from here.
}

Step 2: Setting up the Loop

The most effective tool for iterating through the digits of n is a while loop. The loop will run as long as n is greater than zero. Integrating this into our function produces:

int solution(int n) {
    int digit_sum = 0;
    while (n > 0) {
        // Further development of the function will proceed here.
    }
}

Step 3: Extracting and Processing Each Digit

Within our loop, we'll extract the last digit of n using the modulo operation (n % 10). If this digit is even, we add it to the digit_sum.

After we process a digit, we'll truncate the last digit of n using integer division (n / 10). This step readies the while loop for the next digit.

This is what the code looks like now:

int solution(int n) {
    int digit_sum = 0;
    while (n > 0) {
        int digit = n % 10;
        if (digit % 2 == 0) {  // Check if the digit is even.
            digit_sum += digit;
        }
        n = n / 10;  // Remove the last digit.
    }
}
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal