-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.dart
98 lines (84 loc) · 2.53 KB
/
main.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import 'dart:math';
void main() {
// Bismillahir-Rahmanir-Rahim
// Allahumma Salli 'ala Muhammad
// Write a program that takes a list of numbers as input and prints the
// even numbers in the list using a for loop.
void even(List nums) {
List evenNums = List.empty(growable: true);
for (var i in nums) {
i % 2 == 0 ? evenNums.add(i) : 0;
}
print(evenNums);
}
even([2, 3, 4, 5, 6, 7, 8, 9, 10]); // > [2, 4, 6, 8, 10]
// Write a program that prints the Fibonacci sequence up to a given
// number using a for loop.
void fibonacci(int limit) {
List nums = [0, 1];
while (true) {
int num = nums[nums.length - 1] + nums[nums.length - 2];
if (num < limit) {
nums.add(num);
} else {
break;
}
}
print(nums);
}
fibonacci(20); // > [0, 1, 1, 2, 3, 5, 8, 13]
// Implement a code that checks whether a given number is prime or not.
void checkPrime(int n) {
bool isPrime = true;
for (int i = 2; i < sqrt(n); i++) {
if (n % i == 0) {
isPrime = false;
}
}
isPrime ? print("Number is prime") : print("Number not prime");
}
checkPrime(101); // > Number is prime
checkPrime(24); // > Number not prime
checkPrime(63); // > Number not prime
// Implement a code that finds the factorial of a number using a while
// or for loop
void factorial(int num) {
for (int i = num - 1; i > 0; i--) {
num *= i;
}
print(num);
}
factorial(5); // > 120
// Write a program that calculates the sum of all the digits in a given
// number using a while loop.
void sumOfDigits(int num) {
int sum = 0;
String numAsString = num.toString();
for (int i = 0; i < numAsString.length; i++) {
sum += int.parse(numAsString[i]);
}
print(sum);
}
sumOfDigits(123456); // > 21
// Write a function to find the largest number in a list
// To tackle this problem, we can sort the list
// Bubble sort algorithm:
// https://www.tutorialspoint.com/data_structures_algorithms/bubble_sort_algorithm.htm
void findLargestElement(List list) {
for (var i = 0; i < list.length - 1; i++) {
bool swapped = false;
for (var j = 0; j < list.length - 1; j++) {
var temp = list[j];
if (list[j] > list[j + 1]) {
swapped = true;
list[j] = list[j + 1];
list[j + 1] = temp;
} else {
swapped = false;
}
}
}
print("${list.last} is the largest element");
}
findLargestElement([2, 3, 7, 5, 1]); // > 7 is the largest element
}