Algorithms

Functions in programming: write once, use many times

Cover of the article Functions in programming: write once, use many times
Focused reading

Understand the context.
Put it into practice.

Leia este artigo em português

In this article
  1. How does a function work?
  2. How do you create a function?
  3. What’s the difference between a parameter and an argument?
  4. Does every function need to return a value?
  5. Why use functions?
  6. Now it’s your turn!

A function is a named block of code that receives input data, performs a task and can give back a result. You write it once and use it as many times as you need, just by calling it by its name.

In the previous article, about arrays and matrices, we calculated the average of four grades. Now imagine you need to calculate the average in ten different places in the program. Are you going to copy and paste the same code ten times? Don’t do that haha! That’s exactly the problem a function solves.

How does a function work?

Think of a blender. You put the fruit in (input), press the button (call the function), it does the work inside (processing) and gives you back the juice (output). You don’t need to know how the motor works to use it. A function is the Input, Processing and Output model in miniature!

Three-panel comic: a person puts fruit in the blender, presses the button and gets the juice, representing the input, processing and output of a function
The function as a blender: input, processing and output.

Every function has four parts:

PartWhat it isIn our example
NameHow you call the functioncalculateAverage
ParametersThe data it receivesThe grades
BodyThe code that does the workThe sum and the division
ReturnThe result it gives backThe average
The four parts of a function.
Diagram of a function: the list of grades goes into calculateAverage and the average 7.75 comes out
The function seen from the outside: it receives the grades, does the math and gives back the average.

How do you create a function?

Let’s go to the code. Once again, the same example in three languages. Focus on the concept, not the language! First in PHP:

<?php

function calculateAverage(array $grades): float
{
    return array_sum($grades) / count($grades);
}

echo calculateAverage([7.5, 8.0, 6.5, 9.0]), PHP_EOL; // 7.75
echo calculateAverage([10, 9]), PHP_EOL;              // 9.5

In Python, the word that creates the function is def:

def calculate_average(grades):
    return sum(grades) / len(grades)


print(calculate_average([7.5, 8.0, 6.5, 9.0]))  # 7.75
print(calculate_average([10, 9]))               # 9.5

And in C:

#include <stdio.h>

float calculate_average(float grades[], int count) {
    float total = 0;

    for (int i = 0; i < count; i++) {
        total += grades[i];
    }

    return total / (float)count;
}

int main(void) {
    float grades[4] = {7.5, 8.0, 6.5, 9.0};

    printf("%.2f\n", calculate_average(grades, 4)); // 7.75
    return 0;
}

Notice three things. The function was written only once and called more than once, with different grades. Whoever calls it doesn’t need to know how the math is done. And in C you have to state the type of what goes in and what comes out (float). In the PHP version I stated the types too, but in PHP and in Python they’re optional.

What’s the difference between a parameter and an argument?

This one confuses a lot of people. A parameter is the name that appears when the function is created, like $grades. An argument is the actual value you hand over when you call it, like [10, 9]. In the blender: the parameter is “fruit”, and the argument is the banana you put in today haha.

Does every function need to return a value?

No. Some functions only perform an action, like showing a message on the screen, and don’t give anything back. In C, this kind of function is marked with the word void.

IMPORTANT: the variables created inside the function only exist in there. This is called the variable’s scope, and understanding it is the basis for understanding functions.

Why use functions?

  • It avoids repetition. The code stays in one place.
  • It makes fixing easier. Found a mistake in the math? You fix it in the function, and the whole program is right.
  • It makes the code readable. The function’s name already tells you what it does.
  • It lets you test in parts. You can check each function separately from the rest.

A golden tip: give names that say what the function does. calculateAverage is much better than doStuff haha. And remember: a function should do only one thing.

Now it’s your turn!

Remember the challenge from the arrays article, finding the highest temperature of the week? Turn that code into a function that receives the array and returns the highest value. Then call the function with two different arrays.

Did you notice that you didn’t need to write the logic again? That’s the power of functions! And if you haven’t done the previous challenge yet, start with it. Try it on your own, without asking anyone for the ready-made answer, not even AI! Making mistakes and fixing them is part of learning.

In the next article, the story gets interesting: we’ll see a function that calls itself. It’s the famous recursion. See you there!

Stay confident!!!

Sources:

  • PHP, official manual. User-defined functions, with a function defined by the function keyword, a name, a list of parameters and a body in curly braces.
  • PHP, official manual. Type declarations, with types that can be added to function arguments and return values.
  • PHP, official manual. Variable scope, with a variable created inside a function limited to the scope of the function body.
  • Python, official documentation. Compound statements, with def, which starts a function definition.
  • Python, official documentation. Programming FAQ: What is the difference between arguments and parameters?, with parameters as the names in the function definition and arguments as the values passed when calling it.
  • Python, official documentation. typing: Support for type hints, with the note that the Python runtime does not enforce type annotations.
  • GNU, The GNU C Language Manual. Function Definitions, with void as the return type of a function that does not return a value.
  • UC Berkeley, Composing Programs (John DeNero). 1.4 Designing Functions, with each function having exactly one job, identifiable by a short name.
  • UC Berkeley, CS 61A. Lecture 4: Higher-Order Functions (slides), with the “don’t repeat yourself” rule: implement a process just once and execute it many times.
  • Stanford University, CS106A (Nick Parlante). Python Style Decomposition, with the black-box model, in which the input and output of each function are its contact point with the rest of the program.
  • The examples were run on PHP 8.3, Python 3.13 and GCC 13.

Share this article

About the author

Walmir Silva

Hi! I'm Walmir, a software engineer with an MBA in Software Engineering, the mind behind GrowthCode and the author of the book "Além do Código" (in Portuguese).

If you think programming is just about writing code, get ready to broaden your horizons. Here, we go beyond the code and explore the fascinating intersections between technology, business, the arts and philosophy.

Are you looking for career growth? Do you want to stand out in a competitive market? Are you after a life richer in knowledge and fulfillment? Then you've come to the right place. At GrowthCode, we offer deep insights, proven strategies and a touch of philosophical wisdom to fuel your personal and professional growth.

See all articles →

Continue the conversation

Share your perspective

Your email address will not be published. Required fields are marked *

We keep the IP address and browser of commenters for 6 months, to block spam and because Brazil’s Marco Civil da Internet requires access records to be kept for that period. See how we handle your data (in Portuguese).

Find your next answer

What do you want to learn?

Cookie preferences

Optional cookies start off. You can change your choice at any time on this screen.

NecessaryAlways on

They store your cookie choice and its record code, and keep the site working. They are not used for advertising.

They count visits and show how the site is used: Google Analytics and Microsoft Clarity, loaded by Google Tag Manager.

They show Google AdSense ads without personalization. The cookies in this category limit how often ads repeat and measure their results.

Uses your browsing to choose ads and build ad audiences: Google ads chosen by your interests and Google signals in Analytics. When off, ads are shown without personalization. Requires Advertising.

You can also block cookies in your browser settings. Details in the Privacy policy (in Portuguese).