Menu
Coddy logo textTech

Functions Returning Values

Part of the Fundamentals section of Coddy's Dart journey — lesson 68 of 94.

Functions returning values allow your code to calculate a result and send it back to where the function was called. Unlike void functions, these functions specify a return type.

Create a function that returns an integer:

int add(int a, int b) {
  return a + b;
}

void main() {
  int sum = add(5, 3);
  print('Sum: $sum');
}

After executing the above code, the output will be:

Sum: 8

The function calculates the sum and returns it with the return keyword. The returned value is stored in the sum variable.

challenge icon

Challenge

Beginner

In this challenge, you'll practice creating a function that returns a value. Functions can calculate a result and return it to be used elsewhere in your code.

Complete the calculateSquare function below. It should:

  1. Take an integer parameter number
  2. Calculate the square of that number (multiply it by itself)
  3. Return the result

The expected output is:

The square of 5 is: 25

Cheat sheet

Functions can return values by specifying a return type and using the return keyword:

int add(int a, int b) {
  return a + b;
}

void main() {
  int sum = add(5, 3);
  print('Sum: $sum'); // Output: Sum: 8
}

The returned value can be stored in a variable and used elsewhere in your code.

Try it yourself

void main() {
  // This number is already defined for you
  int number = 5;
  
  // Call the calculateSquare function and store the result
  int result = calculateSquare(number);
  
  // This will display the result
  print('The square of $number is: $result');
}

// TODO: Complete this function to return the square of the number
int calculateSquare(int number) {
  // Your code here - calculate the square and return it
  
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals