Triangle

Triangle

The nth term in the series is obtained by adding n to the previous term. Thus, the second term is found by adding 2 to the first term (which is 1), giving 3. The third term is 3 added to the second term (which is 3) giving 6, and so on. The numbers in this series are called triangular numbers because they can be visualized as a triangular arrangement of objects.

$ dart 05_recursion/triangle.dart
import 'dart:io';

int triangle(int number) {
  if (number == 1) {
    return 1;
  } else {
    return (number + triangle(number - 1));
  }
}

void main(List<String> args) {
  stdout.writeln('Enter a number:');
  int number = int.parse(stdin.readLineSync());
  int answer = triangle(number);

  stdout.writeln(answer);
}