👁 Preview — Study, Practice and Revise are open; mock tests and the rest of the syllabus unlock on subscription. Unlock all · ₹4,999
← Back to Programming Fundamentals
Study mode

Functions and Procedures

Introduction to Functions and Procedures

When writing computer programs, especially large or complex ones, it is important to organize the code in a way that is easy to understand, maintain, and reuse. This approach is called modular programming. Modular programming breaks a program into smaller, manageable parts called modules. Two fundamental building blocks of modular programming are functions and procedures.

Both functions and procedures are named blocks of code designed to perform specific tasks. They help programmers divide a big problem into smaller pieces, making the program easier to write, test, and debug. By using functions and procedures, you avoid repeating the same code multiple times, which saves time and reduces errors.

In this chapter, we will explore what functions and procedures are, how they differ, and why they are essential in programming. We will also learn how to create and use them effectively with examples, flowcharts, and pseudocode.

Functions vs Procedures

Before diving deeper, it's important to understand the difference between a function and a procedure. Although both are blocks of code designed to perform tasks, their key difference lies in whether they return a value.

Comparison of Functions and Procedures
Aspect Function Procedure
Return Value Returns a value after execution Does not return a value
Purpose Computes and gives back a result Performs a task or action
Typical Use Case Calculations, data processing, value retrieval Displaying output, modifying data, performing operations
Example Function to calculate factorial of a number Procedure to print student details
Syntax (Generic)
function functionName(parameters) returns dataType   // code   return valueend function        
procedure procedureName(parameters)   // codeend procedure        

Why this difference matters: When you want your code block to produce a result that can be used elsewhere in the program, use a function. When you want to perform an action without needing a result, use a procedure.

Components of Functions and Procedures

Understanding the parts that make up functions and procedures helps in writing and using them correctly.

  • Parameters: These are placeholders or variables listed in the function or procedure definition. They specify what inputs the block expects.
  • Arguments: These are the actual values or variables passed to the function or procedure when it is called.
  • Return Type: For functions, this specifies the type of value the function will return (e.g., integer, float, string). Procedures do not have return types.
  • Local Variables: Variables declared inside a function or procedure. They exist only during the execution of that block and are not accessible outside.
  • Global Variables: Variables declared outside all functions and procedures. They can be accessed anywhere in the program but should be used carefully to avoid unexpected behavior.
graph TD    Call[Caller Program] -->|Pass Arguments| Func[Function/Procedure]    Func -->|Execute Code| Process[Process Inputs]    Process -->|Return Value (if Function)| Call    Process -->|End Execution| Call

This flowchart shows the general flow when a function or procedure is called:

  • The caller program passes arguments to the function/procedure.
  • The function/procedure processes the inputs.
  • If it is a function, it returns a value back to the caller.
  • Control returns to the caller program after execution.

Call by Value vs Call by Reference

When passing arguments to functions or procedures, there are two common methods:

Comparison of Call by Value and Call by Reference
Aspect Call by Value Call by Reference
How Data is Passed A copy of the actual value is passed A reference (address) of the actual variable is passed
Effect on Original Variable Original variable remains unchanged Original variable can be modified
Use Case When you do not want the original data to change When you want the function/procedure to modify the original data
Example Calculating a value without changing inputs Swapping two numbers by modifying their values

Advantages and Applications of Functions and Procedures

Using functions and procedures offers many benefits:

  • Code Reusability: Write once, use multiple times. This saves time and effort.
  • Modularity: Break complex problems into smaller, manageable parts.
  • Debugging and Maintenance: Easier to find and fix errors in small blocks than in a large program.
  • Improved Readability: Clear structure and meaningful names make code easier to understand.

Key Concept

Functions and procedures are essential tools in programming that help organize code into logical blocks, making programs easier to write, read, test, and maintain.

Formula Bank

Formula Bank

Simple Interest
\[ SI = \frac{P \times R \times T}{100} \]
where: P = Principal amount (INR), R = Rate of interest (% per annum), T = Time (years)

Worked Examples

Example 1: Calculating Factorial Using a Function Easy
Write a function to calculate the factorial of a given positive integer \( n \). Use this function to find the factorial of 5.

Step 1: Understand factorial: \( n! = n \times (n-1) \times (n-2) \times \ldots \times 1 \). For example, \( 5! = 5 \times 4 \times 3 \times 2 \times 1 = 120 \).

Step 2: Define a function named factorial that takes an integer parameter n and returns an integer.

Step 3: Use a loop or recursion inside the function to calculate factorial.

Step 4: Call the function with argument 5 and print the result.

Answer: The factorial of 5 is 120.

Example 2: Procedure to Print Student Details Easy
Create a procedure that takes a student's name, roll number, and marks as parameters and prints these details.

Step 1: Define a procedure named printStudentDetails with parameters: name (string), rollNo (integer), and marks (integer).

Step 2: Inside the procedure, print the values in a readable format.

Step 3: Call the procedure with sample data, for example, name = "Amit", rollNo = 23, marks = 85.

Answer: The procedure will display:
Name: Amit
Roll Number: 23
Marks: 85

Example 3: Swapping Two Numbers Using Call by Reference Medium
Write a procedure to swap the values of two variables using call by reference.

Step 1: Understand that call by reference passes the address of variables, so changes inside the procedure affect the original variables.

Step 2: Define a procedure swap that takes two parameters by reference.

Step 3: Inside the procedure, use a temporary variable to swap the values.

Step 4: Call the procedure with two variables, for example, a = 10 and b = 20.

Answer: After the procedure call, a = 20 and b = 10.

Example 4: Recursive Function to Find Fibonacci Number Medium
Write a recursive function to find the \( n^{th} \) Fibonacci number, where the sequence starts with 0 and 1.

Step 1: Recall Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, ... where each number is the sum of the two preceding ones.

Step 2: Define a function fibonacci(n) that returns 0 if \( n = 0 \), returns 1 if \( n = 1 \), else returns fibonacci(n-1) + fibonacci(n-2).

Step 3: Call the function with \( n = 6 \).

Answer: The 6th Fibonacci number is 8.

Example 5: Function with Multiple Parameters to Calculate Simple Interest Easy
Write a function that takes principal amount, rate of interest, and time period as parameters and returns the simple interest.

Step 1: Use the formula for simple interest: \( SI = \frac{P \times R \times T}{100} \).

Step 2: Define a function calculateSimpleInterest(P, R, T) that returns the calculated interest.

Step 3: Call the function with P = 10000 INR, R = 5%, T = 3 years.

Answer: Simple interest = \( \frac{10000 \times 5 \times 3}{100} = 1500 \) INR.

Tips & Tricks

Tip: Always define functions and procedures with clear parameter lists and specify return types where applicable.

When to use: To avoid confusion and errors when writing modular code.

Tip: Use call by reference when you need to modify the original variable values inside a procedure.

When to use: For tasks like swapping values or updating variables.

Tip: Start recursion problems by clearly identifying the base case to prevent infinite loops.

When to use: When solving problems using recursive functions.

Tip: Write pseudocode or draw flowcharts before coding functions to plan logic and understand flow.

When to use: Especially useful in exams and complex problems.

Tip: Reuse functions wherever possible to save time and reduce errors.

When to use: In larger programs or exam questions with repetitive tasks.

Common Mistakes to Avoid

❌ Confusing procedures with functions by expecting a procedure to return a value.
✓ Remember that procedures do not return values; use functions when a return value is needed.
Why: Students often mix terminology or syntax from different programming languages.
❌ Passing variables incorrectly leading to unexpected results.
✓ Understand the difference between call by value and call by reference and use appropriately.
Why: Lack of clarity on parameter passing mechanisms causes logic errors.
❌ Forgetting to define a base case in recursive functions causing infinite recursion.
✓ Always include a base case to stop recursion.
Why: Students overlook termination conditions under exam pressure.
❌ Using global variables inside functions without understanding scope.
✓ Use local variables inside functions to avoid side effects unless global variables are necessary.
Why: Leads to bugs and unpredictable behavior.
❌ Ignoring data types of parameters and return values.
✓ Always declare and use correct data types for parameters and return values.
Why: Type mismatches cause compilation or runtime errors.
Key Concept

Functions and Procedures

Functions return values and perform calculations; procedures perform actions without returning values. Both improve code modularity, readability, and reusability.

✨ AI exam tools — try them free (included in every plan)
Tip: select any text above to Explain / Example / Simplify it.
Curated videos per subtopic
Top YouTube explainers, AI-ranked for your exam and language. Unlocks with subscription.
Unlock

Try Practice next.

Progress tracking is paywalled — subscribe to mark subtopics as understood and save your streak.

Go to practice →
Ask a doubt
Functions and Procedures · 10 free messages
Ask me anything about this subtopic. You have 10 free messages this session — chat history isn't saved in preview.