Functions
Introduction to C
Structure of a C Program
Variables and Data Types
Input and Output
Operators in C
Decision Making
If Statement
if...else Statement
Nested if Statement
Nested if...else Statement
Switch Statement
Loops
For Loop
While Loop
Do While Loop
Loop Comparison
Arrays
Strings
Functions
Function Types
Library Functions
User-Defined Functions
Recursion Function
Pointers
Structures
File Handling
Common Mistakes
Ideas
Functions
Functions in C
What is a Function?
A Function is a self-contained block of code that performs a specific task. Think of it as a "sub-program" that you can call whenever you need it.
Using functions offers three major benefits:
- Reusability: Write the code once, use it many times.
- Readability: Makes your main program cleaner and easier to understand.
- Easy Debugging: If something is wrong with a specific task, you only need to check that specific function.
Syntax: The Three Parts of a Function
To use a function, you generally need to understand three things: the declaration, the definition, and the call.
return_type function_name(parameter_list) {
// Body of the function
return value;
}
// Body of the function
return value;
}
| Component | Description |
|---|---|
| Return Type | The type of data the function sends back (e.g., int, float, or void if it returns nothing). |
| Parameters | The inputs you pass into the function to work with. |
Practical Examples
Example 1: A Simple Greeting (No Return Value)
// Defining the function void greet() { printf("Welcome to SkillEco!\n"); } int main() { greet(); // Calling the function return 0; }
Example 2: Adding Two Numbers (With Parameters and Return)
int add(int a, int b) { return a + b; } int main() { int result = add(10, 20); printf("The sum is: %d", result); return 0; }
Mental Model: Think of a function like a Juicer. The Fruits are the Parameters (Input), the Machine is the Function Body (Logic), and the Juice is the Return Value (Output).
Example
Executing...
❌ Error:
✅ Output:
// Click Run ▶ to execute