Learn what functions are in programming and understand with simple real-world examples.
A function is a block of code designed to perform a specific task. Functions help organize code into reusable pieces that can be called whenever needed. They can take inputs, called parameters, and often return a result.
Imagine a coffee machine. You press a button, and it makes coffee for you. The coffee machine is like a function — it performs a specific task when you "call" it (press the button). You might tell it what kind of coffee you want (input), and it gives you a cup of coffee (output).
void sayHello() {
print("Hello!");
}
This function sayHello prints the word "Hello!" when called.
void main() {
sayHello(); // Calling the function to execute its code
}
void sayHello() {
print("Hello!");
}
When sayHello() is called inside main(), it runs and prints "Hello!" to the screen.
Functions can take inputs (parameters) to work with different data.
void greet(String name) {
print("Hello, $name!");
}
void main() {
greet("Alex");
greet("Samantha");
}
Here, the function greet takes a String called name and prints a personalized greeting.
Functions can also return a value after doing some work.
int add(int a, int b) {
return a + b;
}
void main() {
int sum = add(5, 3);
print("Sum is $sum");
}
The add function adds two numbers and returns the result.
Think of a calculator: you give it two numbers and the operation (add, subtract), and it returns the result.
double calculate(double num1, double num2, String operation) {
if (operation == "add") {
return num1 + num2;
} else if (operation == "subtract") {
return num1 - num2;
} else {
return 0;
}
}
void main() {
print(calculate(10, 5, "add")); // Output: 15
print(calculate(10, 5, "subtract")); // Output: 5
}