What Are
Functions in Programming?



What Are Functions?

In programming, a function is a named block of code that performs a specific task. It can be defined once and called (or reused) multiple times, making code modular, clean, and easier to maintain.

Why Use Functions?

Function Structure

At a basic level, a function includes:

function greetUser(name):
    print "Hello, " + name + "!"

Here, greetUser is the function name. It takes one parameter name and prints a greeting message.

How to Call a Function

Once defined, a function can be called using its name followed by parentheses containing arguments:

greetUser("Alice")

Output:

Hello, Alice!

Example 1: Function Without Parameters

function showWelcomeMessage():
    print "Welcome to the Programming Course!"
showWelcomeMessage()

Output:

Welcome to the Programming Course!

This function doesn’t take any input but simply prints a message when called.

Example 2: Function With Return Value

function add(a, b):
    result = a + b
    return result
sum = add(5, 3)
print sum

Output:

8

The add function takes two inputs and returns their sum, which can be stored or printed.

Let’s Think:

Question: Can a function return nothing?

Answer: Yes. Some functions perform actions (like printing to screen or saving a file) and do not need to return a value.

Example 3: Function Returning Nothing

function logActivity(activity):
    print "Logging activity: " + activity
logActivity("User logged in")

Output:

Logging activity: User logged in

Function Reusability

Once you define a function, you can use it as many times as needed:

logActivity("File uploaded")
logActivity("Email sent")

Output:

Logging activity: File uploaded
Logging activity: Email sent

Intuition Builder:

Question: What if you want to repeat a calculation many times?

Answer: Wrap it in a function! That way, you don’t repeat logic — just call the function with different inputs.

Conclusion

Functions are fundamental building blocks in programming. They help you:

Mastering functions is essential to writing clean, scalable programs!



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