- You are developing a simple application for a library. Declare a variable named
numberOfBooksof typeintand assign it the total number of books in the library, which is 1500. Print the number of books. - In a weather application, declare a variable
temperatureof typedoubleto represent the current temperature in Celsius. Assign it a value of 23.5 and print the temperature. - Write a Dart program that calculates the area of a rectangle. Add comments to explain each part of the code, including variable declarations and calculations.
- In a shopping cart application, declare two variables
itemPriceandquantity. Assign them values of 20.0 and 3, respectively. Calculate the total cost and print it. - Create a program that asks the user for their name and age. Print a greeting message that includes their name and the year they were born.
- In a social media application, declare a variable
usernameand assign it your chosen username. Print a message that includes the username and its length. - Write a program that declares a
boolvariable namedisMemberto indicate if a user is a member of a gym. Assign ittrueand print a message stating whether the user is a member or not. - Create a Dart program that declares a variable
priceof typenumto represent the price of an item. Assign it a value of 99.99 and print the price. - Write a Dart program that converts kilometers to miles. Include comments explaining the conversion formula and the output.
In a recipe application, declare a variable
sugarCupsand assign it a value of 2.5. Calculate the total amount of sugar needed for 4 servings and print the result.
1. Understanding Variables in Dart
Question: You are developing a simple application for a library. Declare a variable named numberOfBooks of type int and assign it the total number of books in the library, which is 1500. Print the number of books.
Solution:
void main() {
int numberOfBooks = 1500; // Declare and initialize the variable print('Number of books in the library: $numberOfBooks'); // Print the value }
Explanation:
int numberOfBooks = 1500;: This line declares an integer variable namednumberOfBooksand assigns it a value of 1500, representing the total number of books in the library.print('Number of books in the library: $numberOfBooks');: This line uses string interpolation to format the output string, which includes the variable value.
2. Exploring Data Types in Dart
Question: In a weather application, declare a variable temperature of type double to represent the current temperature in Celsius. Assign it a value of 23.5 and print the temperature.
Solution:
void main() {
double temperature = 23.5; // Declare and initialize the variable print('Current temperature: $temperature °C'); // Print the temperature }
Explanation:
double temperature = 23.5;: This line declares a variabletemperatureof typedoubleand assigns it the value 23.5, indicating the current temperature in Celsius.print('Current temperature: $temperature °C');: This line prints the current temperature, using string interpolation to include the variable value.
3. Adding Comments in Dart Code
Question: Write a Dart program that calculates the area of a rectangle. Add comments to explain each part of the code, including variable declarations and calculations.
Solution:
void main() {
// Declare the length and width of the rectangle double length = 5.0; // Length in units double width = 3.0; // Width in units
// Calculate the area of the rectangle double area = length * width; // Area = length * width
// Print the area print('Area of the rectangle: $area square units');
}
Explanation:
- The program starts by declaring variables
lengthandwidthto represent the dimensions of the rectangle. - The area is calculated by multiplying
lengthandwidth, and the result is stored in theareavariable. - Finally, the program prints the calculated area, with comments explaining each step.
4. Working with Operators in Dart
Question: In a shopping cart application, declare two variables itemPrice and quantity. Assign them values of 20.0 and 3, respectively. Calculate the total cost and print it.
Solution:
void main() {
double itemPrice = 20.0; // Price of a single item int quantity = 3; // Number of items
// Calculate total cost double totalCost = itemPrice * quantity;
// Print total cost print('Total cost: \$${totalCost}');
}
Explanation:
double itemPrice = 20.0;: This line declares a variableitemPriceto represent the price of a single item.int quantity = 3;: This line declares a variablequantityto represent how many items are being purchased.- The total cost is calculated by multiplying
itemPriceandquantity, and the result is stored intotalCost. - The program prints the total cost, formatting it as currency.
5. Getting User Input in Dart
Question: Create a program that asks the user for their name and age. Print a greeting message that includes their name and the year they were born.
Solution:
import 'dart:io'; // Import the dart:io library for input
void main() {
// Prompt for user input stdout.write('Enter your name: ');
String? name = stdin.readLineSync(); // Read the name from user input
stdout.write('Enter your age: ');
String? ageInput = stdin.readLineSync(); // Read the age from user input int age = int.parse(ageInput!); // Convert age to an integer
// Calculate the year of birth int yearBorn = DateTime.now().year - age;
// Print the greeting message print('Hello, $name! You were born in $yearBorn.');
}
Explanation:
- The program imports the
dart:iolibrary to read user input from the console. - It prompts the user for their name and age, reading these values using
stdin.readLineSync(). - The age string is converted to an integer using
int.parse(). - The year of birth is calculated by subtracting the age from the current year.
- Finally, the program prints a greeting message that includes the user's name and calculated year of birth.
6. Manipulating Strings in Dart
Question: In a social media application, declare a variable username and assign it your chosen username. Print a message that includes the username and its length.
Solution:
void main() {
String username = 'DartFan'; // Declare and initialize username int usernameLength = username.length; // Get the length of the username
// Print the username and its length print('Username: $username, Length: $usernameLength characters');
}
Explanation:
String username = 'DartFan';: This line declares a variableusernameand assigns it a string value.int usernameLength = username.length;: Thelengthproperty is used to get the number of characters in the username.- The program prints the username and its length using string interpolation.
7. Understanding Variables in Dart
Question: Write a program that declares a bool variable named isMember to indicate if a user is a member of a gym. Assign it true and print a message stating whether the user is a member or not.
Solution:
void main() {
bool isMember = true; // Declare a boolean variable
// Print membership status if (isMember) {
print('You are a gym member.');
} else {
print('You are not a gym member.');
}
}
Explanation:
bool isMember = true;: This line declares a boolean variableisMemberto indicate membership status.- The program uses an
ifstatement to check the value ofisMemberand prints an appropriate message based on whether the user is a member or not.
8. Exploring Data Types in Dart
Question: Create a Dart program that declares a variable price of type num to represent the price of an item. Assign it a value of 99.99 and print the price.
Solution:
void main() {
num price = 99.99; // Declare a variable of type num
// Print the price print('The price of the item is: \$${price}');
}
Explanation:
num price = 99.99;: This line declares a variablepriceof typenum, which can hold both integers and doubles.- The program prints the price using string interpolation to format it as currency.
9. Adding Comments in Dart Code
Question: Write a Dart program that converts kilometers to miles. Include comments explaining the conversion formula and the output.
Solution:
void main() {
// Declare the distance in kilometers double kilometers = 10.0;
// Conversion factor from kilometers to miles double conversionFactor = 0.621371;
// Calculate the distance in miles double miles = kilometers * conversionFactor;
// Print the result print('$kilometers kilometers is equal to $miles miles.');
}
Explanation:
- The program declares a variable
kilometersto hold the distance in kilometers. - A conversion factor is defined to convert kilometers to miles.
- The distance in miles is calculated by multiplying
kilometersbyconversionFactor. - Finally, the program prints the result, including both kilometers and miles.
10. Working with Operators in Dart
Question: In a recipe application, declare a variable sugarCups and assign it a value of 2.5. Calculate the total amount of sugar needed for 4 servings and print the result.
Solution:
void main() {
double sugarCups = 2.5; // Amount of sugar for one serving
// Calculate total sugar for 4 servings double totalSugar = sugarCups * 4;
// Print the total amount of sugar needed print('Total sugar needed for 4 servings: $totalSugar cups');
}
Explanation:
double sugarCups = 2.5;: This line declares a variablesugarCups, which represents the amount of sugar needed for one serving.- The total amount of sugar for 4 servings is calculated by multiplying
sugarCupsby 4. - Finally, the program prints the total amount of sugar needed, formatted for clarity.