In this Post, we’ll explore different ways to calculate the sum of digits in Dart Programming, with clear code examples and explanations.
Calculate Sum of Digits of a Number In Dart Programming
Getting Started
Working with numbers is a common task in programming, and one of the such task is calculating the sum of digits of a number. Dart, a modern object-oriented language developed by Google, makes this operation straightforward with its powerful standard library and easy-to-read syntax.
In programming, the sum of digits refers to the total obtained by adding each digit of a number. Here, we will see how to achieve this using the Dart programming language.
Example of Sum of Digits:- If a number is: 1234
- Then sum of digits is: 1 + 2 + 3 + 4 = 10
Various Method of Calculating Sum of Digits
There are various ways to calculate the sum of digits of a number. Here, I am going to discuss two very common and easy methods of the Dart programming language, and I will also explain how each one works.
Method 1: Calculating Sum of Digits Using String Conversion
String Conversion method is the most simplest and readable method. This method involves converting the number to a string, iterating through each character, converting each back to an integer, and summing them.
Code Example import 'dart:io';
void main() {
// Asking for favourite number
print("Enter your favourite number:");
// Scanning number
int number =int.parse(stdin.readLineSync()!);
print('Sum of digits of $number is: ${number.toString()
.split('')
.map(int.parse)
.reduce((a, b) => a + b)}');
}
Input
Enter your favourite number: 6789
Output
Sum of digits of 6789 is: 30
How it Works:
number.toString()
converts the integer to a string ("6789")..split('')
creates a list of characters (['6', '7', '8', '9'])..map(int.parse)
turns each character into an integer (['6', '7', '8', '9'])..reduce((a, b) => a + b)
sums the list.
Method 2: Calculating Sum of Digits Using a While Loop
This method uses arithmetic to extract digits, which avoids converting the number to a string.
Code Example import 'dart:io';
void main() {
// Asking for a favourite number
print("Enter your favourite number:");
// Scanning number
int number =int.parse(stdin.readLineSync()!);
//int number =7654;
int orgnumber=number;
int sum = 0;
while (number != 0) {
sum += number % 10;
number ~/= 10; // Integer division
}
print('Sum of digits of $orgnumber is: $sum');
}
Input
Enter your favourite number: 7654
Output
Sum of digits of 7654 is: 22
How it Works:
number % 10
gives the last digit.- Add it to sum.
number ~/= 10
removes the last digit.- Repeats until number is zero.
Summary
Calculating the sum of digits in Dart programming is a useful exercise in both string manipulation and basic arithmetic. Whether you're preparing for a coding interview or building an input validator, understanding this operation helps build stronger foundational skills in Dart.
Thanks