Here’s a short practice exercise to help you practice using Dart:
Instructions
Create a new Dart project called my_app
, and create a new file in the lib
folder called main.dart
.
Write a program that does the following:
- Defines a list of integers, containing the values
[1, 2, 3, 4, 5]
. - Uses a for loop to calculate the sum of the integers in the list.
- Prints the sum to the console.
Example Solution
dartCopy codevoid main() {
List<int> numbers = [1, 2, 3, 4, 5];
int sum = 0;
for (int number in numbers) {
sum += number;
}
print('The sum of the numbers is $sum.');
}
In this solution, we’re defining a list of integers called numbers
, and initializing it with the values [1, 2, 3, 4, 5]
.
We’re then using a for loop to iterate over the values in the list, and adding each value to a variable called sum
.
Finally, we’re printing the value of sum
to the console using string interpolation.
When you run this program, you should see the following output in your terminal:
pythonCopy codeThe sum of the numbers is 15.