Sum of First N Natural Numbers

To find the sum of first N natural numbers in Dart, we may use the direct mathematical formula, or use a For loop to iterate from 1 to N and accumulate the sum. In this tutorial, we will write programs using each of the said approaches.

Dart Program

ADVERTISEMENT

Find the sum using For Loop

In the following program, we read a number into n, and find the sum of first n natural numbers using a For Loop.

main.dart

import 'dart:io';

void main(){
    //read number from user
    print('Enter n');
    var n = int.parse(stdin.readLineSync()!);

    //initialize sum to 0
    var sum = 0;

    for(var i = 1; i <= n; i++) {
        sum += i;
    }

    print('sum = $sum');
}

Output

Enter n
10
sum = 55

Find the sum using mathematical formula

In the following program, we read a number into n, and find the sum of first n natural numbers using the below formula.

sum = n * (n + 1) / 2

main.dart

import 'dart:io';

void main(){
    //read number from user
    print('Enter n');
    var n = int.parse(stdin.readLineSync()!);

    var sum = n * (n + 1) / 2;
    print('sum = $sum');
}

Output

Enter n
10
sum = 55.0

Conclusion

In this Dart Tutorial, we learned how to find the sum of first n natural numbers.