⬅ Previous Topic
What Are Functions?Next Topic ⮕
Variable Scope: Local, Global, and Nonlocal⬅ Previous Topic
What Are Functions?Next Topic ⮕
Variable Scope: Local, Global, and NonlocalIn programming, functions are used to group reusable logic. To make functions dynamic and reusable, we use parameters. These are inputs we give to a function to perform its task. After performing its logic, a function can optionally send a value back to the caller using a return statement.
Parameters are placeholders defined in a function. They accept values when the function is called. These actual values passed are known as arguments.
FUNCTION greetUser(name)
PRINT "Hello, " + name
END FUNCTION
CALL greetUser("Alice")
Output:
Hello, Alice
A function can return a value using the RETURN
statement. This value can then be used elsewhere in your code.
FUNCTION addNumbers(a, b)
sum ← a + b
RETURN sum
END FUNCTION
result ← addNumbers(3, 5)
PRINT result
Output:
8
Return values allow us to take the result of a function and use it in computations, logic, or assignments. Without return values, a function would simply perform an action without providing feedback.
FUNCTION calculateArea(length, width)
area ← length * width
RETURN area
END FUNCTION
areaOfRoom ← calculateArea(10, 5)
PRINT "Area of the room: " + areaOfRoom
Output:
Area of the room: 50
Can a function return multiple values?
Yes, in many programming environments, a function can return multiple values using structured data like tuples, arrays, or dictionaries. In pseudocode, we can simulate this using an array or list.
FUNCTION getMinMax(a, b)
IF a > b THEN
RETURN [b, a]
ELSE
RETURN [a, b]
END IF
END FUNCTION
values ← getMinMax(7, 3)
PRINT "Min: " + values[0]
PRINT "Max: " + values[1]
Output:
Min: 3 Max: 7
Sometimes you may want a function to have a default value for a parameter. This means if the caller doesn’t provide a value, the default will be used.
FUNCTION greet(name = "Guest")
PRINT "Welcome, " + name
END FUNCTION
CALL greet("John")
CALL greet()
Output:
Welcome, John Welcome, Guest
Understanding how to use parameters and return values is fundamental in writing reusable and flexible functions. Parameters help customize function behavior, while return values help pass back results for further use.
⬅ Previous Topic
What Are Functions?Next Topic ⮕
Variable Scope: Local, Global, and NonlocalYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.