Sum of Squares of First N Natural Numbers
To find the sum of squares 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 of squares. In this tutorial, we will write programs using each of the said approaches.
Dart Program
ADVERTISEMENT
Find the sum of squares using For Loop
In the following program, we read a number into n
, and find the sum of squares first n natural numbers using a For Loop.
main.dart
import 'dart:io'; void main(){ //read n from user print('Enter n'); var n = int.parse(stdin.readLineSync()!); //initialize sum to 0 var sum = 0; //accumulate the sum of squares for(var i = 1; i <= n; i++) { sum += i * i; } print('sum = $sum'); }
Output
Enter n 10 sum = 385
Output
Enter n 3 sum = 14
Find the sum of squares using mathematical formula
In the following program, we read a number into n
, and find the sum of squares of the first n
natural numbers using the below formula.
sum = n * (n + 1) * (2*n + 1) / 6
main.dart
import 'dart:io'; void main(){ //read n from user print('Enter n'); var n = int.parse(stdin.readLineSync()!); var sum = n * (n + 1) * (2 * n + 1) / 6; print('sum = $sum'); }
Output
Enter n 10 sum = 55.0
Output
Enter n 100 sum = 338350.0
Summary
In this Dart Tutorial, we learned how to find the sum of squares of the first n natural numbers.