2074 7

CSC115 ยท 2074 ยท 5 marks

What is function? Discuss the benefits of using function. [1.5+3.5]

What is function? Discuss the benefits of using function. [1.5+3.5]

C ProgrammingChapter 7: FunctionsUser defined functions

Quick answer

A function is a self-contained, named block of code that performs a specific task. It is written once and can be called (invoked) multiple times from anywhere in the program.

Function in C Programming

What is a Function? [1.5 marks]

General Syntax:

return_type function_name(parameter_list)
{
    // body of the function
    return value;
}

Example:

int add(int a, int b)
{
    return a + b;
}

A C program must have at least one function: int main(), which is the starting point of every C program.


Benefits of Using Functions [3.5 marks]

1. Reusability

A function is written once and can be called multiple times from different parts of the program. This avoids writing the same code repeatedly.

int square(int n) { return n * n; }
// Can be called as: square(3), square(5), square(10) ...

2. Modularity / Divide and Conquer

A large, complex program can be broken down into smaller, manageable, and independent modules (functions). Each function handles one specific task, making the overall program easier to design and understand.

3. Readability and Clarity

Programs written using functions are easier to read and understand. The main() function becomes shorter and cleaner because the detailed logic is moved into separate named functions.

4. Easy Debugging and Testing

Since each function performs a specific task, errors can be located and fixed more easily. Functions can be unit tested individually (tested separately) before being combined into the full program.

5. Reduced Program Length (Avoids Code Duplication)

Without functions, the same logic would need to be written multiple times. Functions reduce the total size of the program by replacing repeated code with a single function call.

6. Easy Maintenance

If a change is needed in a particular task, only the corresponding function needs to be modified. There is no need to search and change the same logic at multiple places throughout the program.

7. Abstraction

The user of a function does not need to know how it works internally. They only need to know what input to provide and what output to expect. This hides complexity and promotes abstraction.


Summary Table

BenefitDescription
ReusabilityWrite once, use many times
ModularityBreaks program into smaller parts
ReadabilityMakes code cleaner and easier to follow
Easy DebuggingErrors are isolated within individual functions
Reduced CodeEliminates repetition
Easy MaintenanceChanges are made in one place only
AbstractionHides internal complexity from the caller

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.