To create a set of numbers from 1 to N in Dart, you can use a for loop to add elements to a Set
In this example,
createSetOfNumbers
that takes an integer n
as a parameter. This parameter represents the upper limit of the set, inclusive.Set
named numberSet
to store the numbers.for
loop to iterate from 1 to n
, adding each number to the numberSet
.numberSet
containing the set of numbers from 1 to n
.Set<int> createSetOfNumbers(int n) {
Set<int> numberSet = {};
for (int i = 1; i <= n; i++) {
numberSet.add(i);
}
return numberSet;
}
void main() {
Set<int> mySet = createSetOfNumbers(5);
print("Set of numbers from 1 to 5: $mySet");
}
Set of numbers from 1 to 5: {1, 2, 3, 4, 5}
In this example,
createSetOfNumbers
that takes an integer n
as a parameter. This parameter represents the upper limit of the set, inclusive.Set
named numberSet
to store the numbers.for
loop to iterate from 1 to n
, adding each number to the numberSet
.numberSet
containing the set of numbers from 1 to n
.Set<int> createSetOfNumbers(int n) {
Set<int> numberSet = {};
for (int i = 1; i <= n; i++) {
numberSet.add(i);
}
return numberSet;
}
void main() {
Set<int> mySet = createSetOfNumbers(10);
print("Set of numbers from 1 to 10: $mySet");
}
Set of numbers from 1 to 10: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
In this tutorial, we learned How to create a Set of Numbers from 1 to N in Dart language with well detailed examples.