Print Sum of all digits in Numbers From 1 to N in C++

Modest programs can become severely difficult if the programmer itself does not understand the problem statement. So getting clarification of the problem statement is extremely necessary before you begin solving that problem. Now during competitions, interview rounds, etc, the problem statement itself is very confusing. One of the very simplest yet confusing problem statements we found is of performing addition. Well as simple as it sounds the complex it is. So today we’re going to find out how to Print Sum of all digits in Numbers From 1 to N in C++.

 

What’s The Approach?

 

  • One of the simplest approaches we can use is to traverse all the numbers from 1 to N. And for each number we can compute the sum of its digits.

 

  • We will perform modulo operation x % 10 for each number from 1 to N so that we get individual digits of each number eventually added up in the sum variable.

 

  • After the above instruction gets executed successfully, we will do x = x / 10. So that we know when to stop.

 

  • The above instructions will keep executing till x != 0  remains true.

 

Also Read: How To Check If Two Strings Are Anagram using C++?

 

C++ Program To Print Sum of All Digits in Numbers From 1 to N

 

Input:

n = 328

 

Output:

 

Sum of digits in numbers from 1 to 328 is 3241

 

// A Simple C++ program to compute sum of digits in numbers from 1 to n
#include<bits/stdc++.h>
using namespace std;

int sumOfDigits(int );

// Returns sum of all digits in numbers from 1 to n
int sumOfDigitsFrom1ToN(int n)
{
    int result = 0; // initialize result

    // One by one compute sum of digits in every number from
    // 1 to n
    for (int x = 1; x <= n; x++)
        result += sumOfDigits(x);

    return result;
}

// A utility function to compute sum of digits in a
// given number x
int sumOfDigits(int x)
{
    int sum = 0;
    while (x != 0)
    {
        sum += x %10;
        x = x /10;
    }
    return sum;
}

// Driver Program
int main()
{
    int n = 328;
    cout << "Sum of digits in numbers from 1 to " << n << " is "
        << sumOfDigitsFrom1ToN(n);
    return 0;
}

 

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

Your email address will not be published. Required fields are marked *