Unlocking Dart's Potential: Control Flow and Functions for Absolute Beginners
Introduction
In the previous blog, we introduced the basics of Dart, including features, configuration, data types, and use cases. In this blog, we will discuss control flow and functions, which are two of the most important concepts in programming.
Control flow refers to the order in which statements in a program are executed. Functions are reusable blocks of code that can be called from other parts of a program.
We will start by discussing the different types of control flow statements in Dart. Then, we will discuss how to define and use functions. Finally, we will provide some examples of how to use control flow and functions in Dart.
We recommend that you read the previous blog before reading this blog, as it will give you a good foundation in the basics of Dart.
Here are some of the topics we will cover in this blog:
Types of control flow statements
Defining and using functions
Examples of control flow and functions in Dart
We hope you enjoy this blog!
Types of control flow statements
- if-else statement: The
if-else
statement allows you to execute different statements depending on the value of a condition. For example, the following code checks if a number is even or odd, and then executes different statements depending on the result of the check:
int number = 10;
if (number % 2 == 0) {
print('The number is even.');
} else {
print('The number is odd.');
}
- for loop: The
for
loop allows you to execute a block of statements repeatedly until a condition is met. For example, the following code prints the numbers from 1 to 10:
for (int i = 1; i <= 10; i++) {
print(i);
}
- while loop: The
while
loop allows you to execute a block of statements repeatedly as long as a condition is met. For example, the following code prints the numbers from 1 to 10, but it stops if the user pressesEnter
.
int i = 1;
while (true) {
print(i);
if (stdin.readLineSync() == '') {
break;
}
i++;
}
- do-while loop: The
do-while
loop is similar to thewhile
loop, but the block of statements is executed at least once, even if the condition is not met. For example, the following code prints the numbers from 1 to 10, even if the user pressesEnter
before the loop reaches 10.
int i = 1;
do {
print(i);
i++;
} while (i <= 10);
These are just a few of the many types of control flow statements in Dart. By understanding these statements, you can write programs that are more efficient and well-structured.
Defining and using functions
Dart is a true object-oriented language, so even functions are objects and have a type, function. Just like a chef's recipes, functions encapsulate a set of instructions, allowing you to call and reuse them whenever needed, reducing redundant code and promoting cleaner, more readable scripts.
Function Syntax: The syntax of a Dart function is simple yet powerful. To define a function, use the void
keyword followed by the function's name, parentheses, and curly braces to enclose the function's body. For instance:
void greetUser() {
print("Hello, user! Welcome to Dart.");
}
Function Parameters: Functions can accept parameters to make them more versatile. Parameters act as placeholders for values that will be passed to the function when it's called. You can specify the type of the parameters, making Dart a statically typed language.
void greetUser(String name) {
print("Hello, $name! Welcome to Dart.");
}
Return Values: Functions can also return values using the return
keyword. If your function calculates a result, you can use return
to send the result back to the caller.
int addNumbers(int a, int b) {
return a + b;
}
Function Invocation: To execute a function, simply call it by its name followed by parentheses. If the function accepts parameters, provide the values when calling it.
greetUser("John");
int result = addNumbers(10, 20);
print("The sum is: $result");
Default and Named Parameters: Dart allows you to set default values for parameters, making them optional when calling the function. Additionally, you can use named parameters to pass arguments in any order, improving code readability.
void greetUser({String name = "Guest"}) {
print("Hello, $name! Welcome to Dart.");
}
print(greetUser()); // Output: Hello, Guest! Welcome to Dart.
print(greetUser(name: 'Kishan')); // Output: Hello, Kishan! Welcome to Dart.
Arrow Syntax (Fat Arrow): For short functions with a single expression, Dart provides an alternative syntax using the fat arrow (=>
). This syntax is concise and ideal for one-liner functions.
int multiplyNumbers(int a, int b) => a * b;
Higher-Order Functions: Dart supports higher-order functions, which means you can pass functions as arguments to other functions or return functions from functions. This feature opens up exciting possibilities for functional programming.
Lambda Functions (Anonymous Functions): Dart allows the use of anonymous functions, also known as lambda functions, using the (parameters) => expression
syntax. These functions are handy for concise, one-time operations.
List<int> numbers = [1, 2, 3, 4, 5];
numbers.forEach((number) => print(number * 2));
Examples of control flow and functions in Dart
Let's explore some examples of control flow and functions in Dart:
1. Control Flow (Conditional Statements):
void checkNumber(int number) {
if (number > 0) {
print("Positive number.");
} else if (number < 0) {
print("Negative number.");
} else {
print("Zero.");
}
}
void main() {
int num1 = 10;
int num2 = -5;
int num3 = 0;
checkNumber(num1); // Output: Positive number.
checkNumber(num2); // Output: Negative number.
checkNumber(num3); // Output: Zero.
}
2. Control Flow (Loops):
void printNumbers(int n) {
for (int i = 1; i <= n; i++) {
print(i);
}
}
void main() {
int count = 5;
printNumbers(count);
// Output:
// 1
// 2
// 3
// 4
// 5
}
3. Functions:
int addNumbers(int a, int b) {
return a + b;
}
void greetUser(String name) {
print("Hello, $name! Welcome to Dart.");
}
double calculateAverage(List<double> numbers) {
double sum = 0;
for (double num in numbers) {
sum += num;
}
return sum / numbers.length;
}
void main() {
int result = addNumbers(10, 20);
print("The sum is: $result"); // Output: The sum is: 30
greetUser("John"); // Output: Hello, John! Welcome to Dart.
List<double> grades = [85.5, 90.0, 78.5, 95.0, 88.0];
double average = calculateAverage(grades);
print("Average grade: $average"); // Output: Average grade: 87.0
}
4. Named Parameters and Default Values:
void greetUser({String name = "Guest", int age = 0}) {
print("Hello, $name! You are $age years old.");
}
void greetAgain([String name = 'Guest']){
print("Hello, $name!");
}
void main() {
greetUser(); // Output: Hello, Guest! You are 0 years old.
greetAgain(); // Output: Hello, Guest!
greetUser(name: "Alice"); // Output: Hello, Alice! You are 0 years old.
greetAgain('Kishan'); // Output: Hello, Kishan!
greetUser(name: "Bob", age: 30); // Output: Hello, Bob! You are 30 years old.
}
5. Higher-Order Function (Function as a Parameter):
void performOperation(int a, int b, Function operation) {
print("Result: ${operation(a, b)}");
}
void main() {
performOperation(5, 3, (a, b) => a + b); // Output: Result: 8
performOperation(5, 3, (a, b) => a * b); // Output: Result: 15
}
These examples demonstrate some common use cases of control flow (conditional statements and loops) and functions in Dart.
Conclusion
In this blog, we have discussed the different types of control flow statements in Dart, how to define and use functions, and some examples of how to use control flow and functions in Dart.
Control flow statements allow you to execute different statements depending on the value of a condition. Functions are reusable blocks of code that can be called from other parts of a program.
By understanding these concepts, you can write programs that are more efficient and well-structured.
We hope you enjoyed this blog!