Function Parameters
and Return Values



Introduction to Parameters and Return Values

In 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.

What Are Parameters?

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

How Do Return Values Work?

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

Why Do We Need Return Values?

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.

Example: Area of a Rectangle

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

Question:

Can a function return multiple values?

Answer:

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

Default Parameter Values

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

Conclusion

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.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

Mention your name, and programguru.org in the message. Your name shall be displayed in the sponsers list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M