Mada za sehemu hiiDeveloping programs using functions and arraysMada 3
- Constructing reusable functions
- Implementing single-dimensional and multi-dimensional arrays
- Using control structures to traverse and process arrays
Constructing Reusable Functions
A function (also called a method in C#) is a block of code that performs a specific task. Instead of writing the same code many times throughout a program, you write it once inside a function and then call that function whenever you need it. This makes your code easier to read, maintain, and reuse.
For example, if your program needs to calculate the average of numbers in several places, you can create one function called CalculateAverage() and call it whenever needed.
- Saves time: Write the code once, use it many times
- Reduces errors: Fix a bug in one place, and it fixes everywhere
- Easier to read: Your main program becomes shorter and clearer
- Easier to maintain: Changes only need to be made in one location
In C#, a method follows this basic structure:
returnType MethodName(parameters)
{
// method body
}
Key parts:
- returnType: The type of value the method returns (use
voidif it returns nothing) - MethodName: The name you give the function (should describe what it does)
- parameters: Inputs the method receives (optional)
Built-in Methods
These are ready-made methods provided by C#. For example:
Console.WriteLine("Hello!");
WriteLine() is a built-in method that displays text on the screen.
User-Defined Methods
These are methods you create yourself to perform specific tasks.
Here is a simple method that displays a message:
static void GreetStudent()
{
Console.WriteLine("Welcome to Form Three!");
}
static void Main()
{
GreetStudent(); // Calling the method
GreetStudent(); // Calling it again
}
When you call GreetStudent() twice, the message prints both times, but you only wrote the code once.
Parameters allow you to pass data into a method. This makes the method more flexible.
static void DisplayName(string name)
{
Console.WriteLine("Hello, " + name + "!");
}
static void Main()
{
DisplayName("Amina");
DisplayName("Rajabu");
}
Output:
Hello, Amina!
Hello, Rajabu!
To return a result from a method, specify the return type and use the return keyword:
static int AddNumbers(int a, int b)
{
int sum = a + b;
return sum;
}
static void Main()
{
int result = AddNumbers(15, 25);
Console.WriteLine("The sum is: " + result);
}
This program outputs: The sum is: 40
Write a program with a function that accepts three subject marks and returns the total:
using System;
class Program
{
// Function to calculate total marks
static int CalculateTotal(int mark1, int mark2, int mark3)
{
int total = mark1 + mark2 + mark3;
return total;
}
static void Main()
{
Console.WriteLine("Enter marks for three subjects:");
Console.Write("Mathematics: ");
int m1 = Convert.ToInt32(Console.ReadLine());
Console.Write("English: ");
int e1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Science: ");
int s1 = Convert.ToInt32(Console.ReadLine());
// Call the reusable function
int totalMarks = CalculateTotal(m1, e1, s1);
Console.WriteLine("Total marks: " + totalMarks);
}
}
If a student scores 75 in Mathematics, 82 in English, and 68 in Science, the output will be:
Total marks: 225
A recursive function is a function that calls itself. It solves a problem by breaking it into smaller versions of the same problem.
Every recursive function needs:
- Base case: The condition that stops the recursion
- Recursive case: The part where the function calls itself
Example: Calculating Factorial
The factorial of 5 (written as 5!) equals 5 × 4 × 3 × 2 × 1 = 120.
static int Factorial(int n)
{
// Base case
if (n <= 1)
return 1;
// Recursive case
else
return n * Factorial(n - 1);
}
static void Main()
{
int number = 5;
int result = Factorial(number);
Console.WriteLine(number + "! = " + result);
}
Output:
5! = 120
In Tanzania, reusable functions are used in many applications you encounter daily. For example, when mobile banking apps like M-Pesa calculate transaction fees or convert Tanzanian shillings between different amounts, they use reusable functions that developers wrote once but use many times throughout the application. This makes the apps faster, less prone to errors, and easier to update when fee structures change.
Jinsi utakavyotathminiwaTathmini ya mchakato · Tathmini ya matokeo · Tathmini ya maarifa
Tathmini ya mchakato
The student should be able to:
- Write functions with appropriate parameters and return values.
- Use functions effectively to organize code and reduce redundancy.
Tathmini ya matokeo
Reusable functions that meet task requirements are correctly implemented, and exhibit expected behaviour.
Tathmini ya maarifa
Methods used: The trainee should explain how to:
- Define and call reusable functions in a program.
- Pass parameters to functions and handle return values effectively.
Principles: The student should explain the principle of:
- Function modularity to simplify code structure and reduce duplication.
- Parameterization and how it enhances function reusability.
Theories: The trainee should explain: The trainee should explain:
- The role of functions in improving software scalability and maintainability.
- How function reusability contributes to efficient programming workflows.
Circumstantial knowledge:
Detailed knowledge about:
- Common errors in function design, such as incorrect parameter usage or scope issues, and how to resolve them
Swali
According to the lesson, what is the PRIMARY benefit of using reusable functions in a program?
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