Mada za sehemu hiiImplementing functionsMada 2
- Implementing user-defined functions and function calls in a program
- Implementing recursive function in a program
Implementing User-Defined Functions and Function Calls
A user-defined function is a block of code created by the programmer to perform a specific task. It is called "user-defined" because you create it yourself, unlike library functions which are already built into the programming language.
Think of a function like a machine in a factory. You give it some input (materials), it processes them, and gives you an output (finished product). For example, a calculator has different buttons (functions) for addition, subtraction, multiplication, and division — each button does a specific job.
Functions provide three important benefits:
- Modularity: Break a complex program into smaller, manageable parts. Each function handles one task.
- Code Reusability: Write the function once, then use it many times in your program without rewriting the code.
- Easier Debugging: When an error occurs, you can find and fix it in one function without affecting the rest of your program.

User-defined functions can be classified into four types based on whether they have parameters (arguments) and whether they return a value:
| Type | Has Parameters? | Returns a Value? |
|---|---|---|
| 1. With arguments and with return value | Yes | Yes |
| 2. With arguments and without return value | Yes | No |
| 3. Without arguments and with return value | No | Yes |
| 4. Without arguments and without return value | No | No |
A function declaration tells the computer about your function: its name, what data type it returns, and what parameters it accepts (if any).
Non-Parameterized Functions
These functions do not accept any input values. They are declared with empty parentheses.
// Syntax
return_type function_name() {
// code to execute
}
Example:
void Greetings() {
cout << "Hello, welcome to class!";
}
In this example:
voidmeans the function returns nothingGreetingsis the function name- Empty parentheses
()mean no parameters
Parameterized Functions
These functions accept input values (called parameters or arguments) to work with.
// Syntax
return_type function_name(parameter1, parameter2) {
// code to execute
return value; // if return type is not void
}
Example:
int Addition(int firstnum, int secondnum) {
int summation = firstnum + secondnum;
return summation;
}
In this example:
intis the return type (the function returns an integer)Additionis the function namefirstnumandsecondnumare parameters (both integers)
To use a function, you must call it by its name. When a function is called, the program jumps to that function's code, executes it, and then returns to the place where it was called.
Important Rule: Declare your function before calling it in main().
#include <iostream>
using namespace std;
// Function declaration
void Display() {
cout << "Hello World";
}
// Main function
int main() {
Display(); // Calling the function
return 0;
}
Output:
Hello World
This program uses a parameterized function that returns a value.
#include <iostream>
using namespace std;
// Function to add two numbers
int addition(int a, int b) {
return a + b;
}
int main() {
int num1, num2, add;
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
// Call the function
add = addition(num1, num2);
cout << "Addition is: " << add << endl;
return 0;
}
Sample Output:
Enter first number: 25
Enter second number: 11
Addition is: 36
How it works:
- The user enters two numbers: 25 and 11
- The
additionfunction receives these values as parametersaandb - It returns
a + bwhich is 36 - The result is stored in variable
addand printed
This program uses a function with parameters to compare two numbers.
#include <iostream>
using namespace std;
int max(int x, int y) {
if (x > y)
return x;
else
return y;
}
int main() {
int a = 10, b = 20;
int m = max(a, b);
cout << "Maximum number is " << m;
return 0;
}
Output:
Maximum number is 20
At this level, we use call by value method. This means when you call a function, the actual values are copied into the parameters. Any changes made inside the function do not affect the original variables in main().
For example, if you pass a = 5 to a function and the function changes it to 10, the original a in main() remains 5.
Write a program that uses a user-defined function to check if a number is even or odd.
Solution:
#include <iostream>
using namespace std;
void checkEvenOdd(int num) {
if (num % 2 == 0)
cout << num << " is Even";
else
cout << num << " is Odd";
}
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
checkEvenOdd(number);
return 0;
}
Sample Output:
Enter a number: 17
17 is Odd
In Tanzanian markets, shop owners can use programs with user-defined functions to calculate profits. For example, a duka owner in Kariakoo can create a function that takes the selling price and buying price of goods (like rice or beans), then automatically calculates the profit for each item. This separates the calculation logic from the rest of the program, making it easy to reuse the same function for different products throughout the day.
Jinsi utakavyotathminiwaTathmini ya mchakato · Tathmini ya matokeo · Tathmini ya maarifa
Tathmini ya mchakato
The student should be able to:
- Define functions with proper syntax and structure.
- Pass parameters to functions and use return values effectively.
- Debug and test functions for correctness and efficiency.
- Write modular and reusable code.
Tathmini ya matokeo
User-defined functions that operate correctly and produce the expected results are created.
Tathmini ya maarifa
Methods used: The trainee should explain how to:
- Create and call user-defined functions in a program.
- Use parameters and return values to transfer data between functions.
Principles: The student should explain the principle of:
- The role of functions in simplifying program design.
- The impact of modular programming on scalability and debugging.
Theories: The trainee should explain: The trainee should explain:
- How nested structures contribute to solving complex programming problems.
- The role of logical hierarchies in program design and decision-making.
- The importance of testing edge cases in nested conditions.
Detailed knowledge about:
- Common errors in function definition and usage and how to resolve them.
- Real-world applications of user-defined functions in software development.
Swali
Which of the following best describes a function in computer programming?
Ingia ili kuwasilisha jibu lako na lihesabiwe katika umahiri wako.
Ingia ili kufanya mazoeziMwalimu
Umekwama? Niulize chochote kuhusu mada hii.
Ingia ili kumuuliza Mwalimu wa AI wa Sonza kuhusu swali hili.
Ingia ili kuulizaMajadiliano
Hakuna maswali bado