Boost Your Coding Skills with Dart Practice Problems | Flutter
1. Dart program that generates a Fibonacci series based on user input.
import 'dart:io';
void main() {
print("Enter the number of terms for the Fibonacci series: ");
String input = stdin.readLineSync()!;
int n = int.parse(input);
if (n <= 0) {
print("Please enter a positive integer.");
} else {
print("Fibonacci Series with $n terms:");
for (int i = 0; i < n; i++) {
print(fibonacci(i));
}
}
}
int fibonacci(int n) {
if (n <= 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
2. Find the minimum value in a list in Dart by first taking input from the user.
import 'dart:io';
void main() {
// Take input from the user
print("Enter a list of numbers separated by spaces:");
String input = stdin.readLineSync() ?? "";
List<String> inputList = input.split(' ');
List<int> numbers = [];
for (String item in inputList) {
try {
int number = int.parse(item);
numbers.add(number);
} catch (e) {
print("Invalid input: $item is not a valid number.");
}
}
if (numbers.isEmpty) {
print("No valid numbers entered. Cannot find the minimum value.");
} else {
int minValue = findMinimumValue(numbers);
print("The minimum value in the list is: $minValue");
}
}
int findMinimumValue(List<int> numbers) {
int minValue = numbers[0];
for (int number in numbers) {
if (number < minValue) {
minValue = number;
}
}
return minValue;
}
3. A Dart program that takes user input and checks if the number is an Armstrong number or not.
import 'dart:io';
void main() {
print("Enter a number: ");
int num = int.parse(stdin.readLineSync()!);
int sum = 0;
int temp = num;
while (temp > 0) {
int digit = temp % 10;
sum = sum + (digit * digit * digit);
temp ~/= 10;
}
if (num == sum) {
print("$num is an Armstrong number.");
} else {
print("$num is not an Armstrong number.");
}
}
4. How you can create a Factorial function in Dart that takes input from the user?
import 'dart:io';
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
void main() {
stdout.write("Enter a number to find its factorial: ");
String input = stdin.readLineSync() ?? '';
int number = int.tryParse(input) ?? 0;
if (number < 0) {
print("Factorial is not defined for negative numbers.");
} else {
int result = factorial(number);
print("The factorial of $number is $result");
}
}
5. Print pattern 1 in Dart.
import 'dart:io';
void printPattern() {
int size = 11;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size - i; j++) {
stdout.write(' ');
}
for (int k = 0; k <= i; k++) {
int num = (k + i) % 10;
stdout.write('$num ');
}
for (int l = i - 1; l >= 0; l--) {
int num = (l + i) % 10;
stdout.write('$num ');
}
stdout.write('\n');
}
for (int i = size -2; i >= 0; i--) {
for (int j = 0; j < size - i; j++) {
stdout.write(' ');
}
for (int k = 0; k <= i; k++) {
int num = (k + i) % 10;
stdout.write('$num ');
}
for (int l = i - 1; l >= 0; l--) {
int num = (l + i) % 10;
stdout.write('$num ');
}
stdout.write('\n');
}
}
void main() {
printPattern();
}
6. Write a Dart program which accepts a sequence of comma-separated numbers from the user and generates a list and a tuple with those numbers.
Sample data : 3, 5, 7, 23
Output : List : [‘3’, ‘ 5’, ‘ 7’, ‘ 23’] Set : (‘3’, ‘ 5’, ‘ 7’, ‘ 23’)
import 'dart:io';
void main() {
print("Enter a sequence of comma-separated numbers:");
String input = stdin.readLineSync() ?? '';
List<String> numbersList = input.split(',').map((number) => number.trim()).toList();
var numbersTuple = Tuple.fromList(numbersList);
print("List : $numbersList");
print("Tuple : $numbersTuple");
}
class Tuple {
final List<String> items;
Tuple(this.items);
factory Tuple.fromList(List<String> list) {
return Tuple(List<String>.from(list));
}
@override
String toString() {
return '(${items.join(', ')})';
}
}
7. Write a Dart program to print the calendar of a given month and year.
import 'dart:io';
void main() {
print("Enter the year (e.g., 2023): ");
int year = int.tryParse(stdin.readLineSync()!) ?? DateTime.now().year;
print("Enter the month (1-12): ");
int month = int.tryParse(stdin.readLineSync()!) ?? DateTime.now().month;
final date = DateTime(year, month, 1);
final lastDay = DateTime(year, month + 1, 0);
final firstWeekday = date.weekday;
printCalendar(month, year, firstWeekday, lastDay.day);
}
void printCalendar(int month, int year, int firstWeekday, int lastDay) {
final monthNames = [
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
];
print('${monthNames[month - 1]} $year');
print('Su Mo Tu We Th Fr Sa');
// Print leading spaces for the first week
for (int i = 0; i < firstWeekday; i++) {
stdout.write(' ');
}
for (int day = 1; day <= lastDay; day++) {
if (day < 10) {
stdout.write(' ');
}
stdout.write('$day ');
if ((day + firstWeekday) % 7 == 0 || day == lastDay) {
print('');
}
}
}
8. Write a Dart program to calculate number of days between two dates.
Sample dates : (2014, 7, 2), (2014, 7, 11)
Expected output : 9 days
import 'dart:io';
void main() {
print("Enter the first date (YYYY-MM-DD): ");
String dateStr1 = stdin.readLineSync() ?? "";
print("Enter the second date (YYYY-MM-DD): ");
String dateStr2 = stdin.readLineSync() ?? "";
try {
DateTime date1 = DateTime.parse(dateStr1);
DateTime date2 = DateTime.parse(dateStr2);
// Calculate the difference in days
int differenceInDays = date2.difference(date1).inDays;
print("Number of days between the two dates: $differenceInDays");
} catch (e) {
print("Invalid date format. Please enter dates in the format 'YYYY-MM-DD'.");
}
}
9. Write a Dart program to count the number 4 in a given list (Take input from the user).
import 'dart:io';
void main() {
print("Enter a list of numbers separated by spaces:");
String input = stdin.readLineSync() ?? '';
List<String> numbers = input.split(' ');
int countOfFour = countNumberFour(numbers);
print("The number 4 occurs $countOfFour time(s) in the list.");
}
int countNumberFour(List<String> numbers) {
int count = 0;
for (var number in numbers) {
if (number.contains('4')) {
for (var digit in number.runes) {
if (String.fromCharCode(digit) == '4') {
count++;
}
}
}
}
return count;
}
10. Dart program that performs all the basic arithmetic operations (+ addition, — subtraction, * multiplication, / division) on two numbers provided by the user.
import 'dart:io';
void main() {
print("Enter two numbers:");
double? num1 = double.tryParse(stdin.readLineSync()!);
double? num2 = double.tryParse(stdin.readLineSync()!);
if (num1 != null && num2 != null) {
print("Addition: ${num1 + num2}");
print("Subtraction: ${num1 - num2}");
print("Multiplication: ${num1 * num2}");
if (num2 != 0) {
print("Division: ${num1 / num2}");
} else {
print("Division by zero is not possible.");
}
} else {
print("Invalid input. Please enter valid numbers.");
}
}
11. Dart program that converts feet to meters.
import 'dart:io';
void main() {
print("Enter the length in feet:");
double? feet = double.tryParse(stdin.readLineSync()!);
if (feet != null) {
double meters = feet * 0.3048; // 1 foot is equal to 0.3048 meters
print("$feet feet is equal to $meters meters.");
} else {
print("Invalid input. Please enter a valid number for feet.");
}
}
12. Dart program that converts Celsius to Fahrenheit.
import 'dart:io';
void main() {
print("Enter the temperature in Celsius:");
double? celsius = double.tryParse(stdin.readLineSync()!);
if (celsius != null) {
double fahrenheit = (celsius * 9 / 5) + 32; // Formula to convert Celsius to Fahrenheit
print("$celsius°C is equal to $fahrenheit°F.");
} else {
print("Invalid input. Please enter a valid temperature in Celsius.");
}
}
13. Dart program that converts Fahrenheit to Celsius.
import 'dart:io';
void main() {
print("Enter the temperature in Fahrenheit:");
double? fahrenheit = double.tryParse(stdin.readLineSync()!);
if (fahrenheit != null) {
double celsius = (fahrenheit - 32) * (5 / 9); // Formula to convert Fahrenheit to Celsius
print("$fahrenheit°F is equal to $celsius°C.");
} else {
print("Invalid input. Please enter a valid temperature in Fahrenheit.");
}
}
14. Dart program that reverses a string entered by the user.
import 'dart:io';
void main() {
print("Enter a string:");
String? input = stdin.readLineSync();
if (input != null) {
String reversedString = reverseString(input);
print("Reversed string: $reversedString");
} else {
print("No input provided. Please enter a string.");
}
}
String reverseString(String input) {
String reversed = input.split('').reversed.join();
return reversed;
}
>>> You can now buy me a coffee! <<<
15. Dart program that counts the number of alphabets, digits, and special characters in a string entered by the user.
import 'dart:io';
void main() {
print("Enter a string:");
String? input = stdin.readLineSync();
if (input != null) {
Map<String, int> characterCount = countCharacters(input);
print("Number of alphabets: ${characterCount['alphabets']}");
print("Number of digits: ${characterCount['digits']}");
print("Number of special characters: ${characterCount['special']}");
} else {
print("No input provided. Please enter a string.");
}
}
Map<String, int> countCharacters(String input) {
int alphabets = RegExp(r'[a-zA-Z]').allMatches(input).length;
int digits = RegExp(r'\d').allMatches(input).length;
int special = input.length - alphabets - digits;
return {'alphabets': alphabets, 'digits': digits, 'special': special};
}
16. Dart program that swaps the first and last digit of a number provided by the user.
import 'dart:io';
void main() {
print("Enter a number:");
String input = stdin.readLineSync() ?? '';
if (input.isNotEmpty) {
int number = int.parse(input);
int swappedNumber = swapFirstLastDigit(number);
print("Number after swapping first and last digit: $swappedNumber");
} else {
print("Invalid input. Please enter a number.");
}
}
int swapFirstLastDigit(int number) {
if (number < 10) {
return number;
} else {
int lastDigit = number % 10;
int firstDigit = int.parse(number.toString()[0]);
int power = 1;
int temp = number;
while (temp >= 10) {
temp ~/= 10;
power *= 10;
}
c
// Formula to swap first and last digits
int newNumber = lastDigit * power;
newNumber += number % power;
newNumber -= lastDigit;
newNumber += firstDigit;
return newNumber;
}
}
17. How to measure the execution time for a Dart method?
void main() {
// Call the method and measure its execution time
measureExecutionTime(myMethod);
}
void myMethod() {
// Example method that you want to measure the execution time
for (int i = 0; i < 100000000; i++) {
// Some computation or task
}
}
void measureExecutionTime(Function method) {
var stopwatch = Stopwatch()..start();
method(); // Call the method
stopwatch.stop();
print('Execution time: ${stopwatch.elapsed}');
}
18. Write a Dart program to get OS name, platform and release information.
import 'dart:io';
void main() {
print("OS Name: ${Platform.operatingSystem}");
print("OS Version: ${Platform.operatingSystemVersion}");
print("OS Platform: ${Platform.operatingSystem}");
print("OS Architecture: ${Platform.operatingSystem}");
print("Dart VM: ${Platform.version}");
}
19. Write a Dart program to get the number of processors.
import 'dart:io';
void main() {
int processors = Platform.numberOfProcessors;
print('Number of Processors: $processors');
}
20. Dart program that checks whether a number is a palindrome or not.
import 'dart:io';
void main() {
print("Enter a number to check if it's a palindrome: ");
int number = int.parse(stdin.readLineSync() ?? '0');
bool isPalindrome = checkPalindrome(number);
if (isPalindrome) {
print("$number is a palindrome number.");
} else {
print("$number is not a palindrome number.");
}
}
bool checkPalindrome(int number) {
int reversedNumber = 0;
int originalNumber = number;
while (number > 0) {
int remainder = number % 10;
reversedNumber = reversedNumber * 10 + remainder;
number = number ~/ 10;
}
return originalNumber == reversedNumber;
}
21. Dart program that converts a decimal number entered by the user into its equivalent binary number.
import 'dart:io';
void main() {
print("Enter a decimal number to convert to binary: ");
int decimalNumber = int.parse(stdin.readLineSync() ?? '0');
String binaryNumber = convertToBinary(decimalNumber);
print("Binary representation: $binaryNumber");
}
String convertToBinary(int decimalNumber) {
return decimalNumber.toRadixString(2);
}
22. Dart program that converts a binary number entered by the user into its decimal number.
import 'dart:io';
void main() {
print("Enter a binary number: ");
String binary = stdin.readLineSync() ?? '0';
int decimal = binaryToDecimal(binary);
print("Decimal equivalent: $decimal");
}
int binaryToDecimal(String binary) {
int decimal = 0;
int power = 0;
for (int i = binary.length - 1; i >= 0; i--) {
int digit = int.parse(binary[i]);
decimal += digit * (1 << power);
power++;
}
return decimal;
}
23. Dart program that calculates the Least Common Multiple (LCM) of two numbers provided by the user.
import 'dart:io';
void main() {
print("Enter first number: ");
int num1 = int.parse(stdin.readLineSync() ?? '0');
print("Enter second number: ");
int num2 = int.parse(stdin.readLineSync() ?? '0');
int lcm = calculateLCM(num1, num2);
print("The LCM of $num1 and $num2 is: $lcm");
}
int calculateLCM(int a, int b) {
int max = (a > b) ? a : b;
int step = max;
while (true) {
if (max % a == 0 && max % b == 0) {
return max;
}
max += step;
}
}
24. Dart program that calculates the Highest Common Factor (HCF) of two numbers provided by the user.
import 'dart:io';
void main() {
print("Enter first number: ");
int num1 = int.parse(stdin.readLineSync() ?? '0');
print("Enter second number: ");
int num2 = int.parse(stdin.readLineSync() ?? '0');
int hcf = calculateHCF(num1, num2);
print("The HCF of $num1 and $num2 is: $hcf");
}
int calculateHCF(int a, int b) {
while (b != 0) {
int remainder = a % b;
a = b;
b = remainder;
}
return a;
}
25. Dart program that converts a number (up to 999) to its corresponding words.
import 'dart:io';
void main() {
print("Enter a number (up to 999): ");
int number = int.parse(stdin.readLineSync() ?? '0');
String words = numberToWords(number);
print("Number in words: $words");
}
String numberToWords(int number) {
List<String> units = [
'', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'
];
List<String> teens = [
'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'
];
List<String> tens = [
'', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'
];
if (number == 0) {
return 'zero';
}
String words = '';
if (number >= 100) {
words += units[number ~/ 100] + ' hundred ';
number %= 100;
}
if (number >= 10 && number < 20) {
words += teens[number - 10];
} else {
words += tens[number ~/ 10] + ' ' + units[number % 10];
}
return words.trim();
}
26. Dart program to determine whether a number entered by the user is a prime number.
import 'dart:io';
void main() {
print("Enter a number: ");
int number = int.parse(stdin.readLineSync() ?? '0');
if (isPrime(number)) {
print("$number is a prime number.");
} else {
print("$number is not a prime number.");
}
}
bool isPrime(int number) {
if (number <= 1) {
return false;
}
for (int i = 2; i <= number / 2; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}