Find Factorial of a Number

In the following Dart programs, we read a number from user via console, and find the factorial of this number.

Factorial using For Loop

We use for loop to iterate from 1 to N, and then find the factorial of N.

Refer Dart For Loop tutorial.

main.dart

import 'dart:io';

void main() {
  print('Enter N');
  int N = int.parse(stdin.readLineSync()!);

  int result = 1;
  for (int i = 1; i <= N; i++) {
    result *= i;
  }

  print('Factorial of $N');
  print(result);
}

Output

Enter N
5
Factorial of 5
120
ADVERTISEMENT

Factorial using Recursion

We use for loop to iterate from 1 to N, and then find the factorial of N.

main.dart

import 'dart:io';

int factorial(int n) {
  return n == 1 ? 1 : n * factorial(n - 1);
}

void main() {
  print('Enter N');
  int N = int.parse(stdin.readLineSync()!);

  int result = factorial(N);

  print('Factorial of $N');
  print(result);
}

Output

Enter N
4
Factorial of 4
24

Summary

In this Dart Tutorial, we have written a Dart program to find the factorial of a given number, using Dart Loops or Recursion technique.