Sum of Digits in a Number using Dart
In the following program, we read a number from user via console, and find the sum of digits in this number.
We use for loop to iterate over the digits of the number, and accumulate the sum of the digits in result.
Refer Dart For Loop tutorial.
main.dart
</>
Copy
import 'dart:io';
void main() {
print('Enter N');
int N = int.parse(stdin.readLineSync()!);
int result = 0;
for (int i = N; i > 0; i = (i / 10).floor()) {
result += (i % 10);
}
print('Sum of digits\n$result');
}
Output
Enter N
123456
Sum of digits
21
Summary
In this Dart Tutorial, we have written a Dart program to find the sum of digits in given number.