7 Function
7 Function
1. What is a Function?
- A function is a reusable block of code that performs a specific task.
- Functions in C are called methods.
2. Defining a Function
- Syntax:
returnType FunctionName(parameters)
{
// Code to execute
return value; // If applicable
}
3. Calling a Function
- Use the function name followed by parentheses:
FunctionName(arguments);
4. Return Types
- Functions can return values (e.g., int, string) or void for no return.
5. Parameters
- Functions can take inputs as parameters:
6. Default Parameters
- Provide default values for parameters:
7. Function Overloading
- Define multiple functions with the same name but different parameters.
8. Recursive Functions
- A function that calls itself:
int Factorial(int n)
{
return n == 1 ? 1 : n Factorial(n - 1);
}
1. Simple Function Without Parameters
void SayHello()
{
Console.WriteLine("Hello, World!");
}
SayHello(); // Outputs: Hello, World!
string GetGreeting()
{
return "Welcome!";
}
Console.WriteLine(GetGreeting()); // Outputs: Welcome!
int Factorial(int n)
{
return n == 1 ? 1 : n Factorial(n - 1);
}
Console.WriteLine(Factorial(5)); // Outputs: 120
Print(10); // Outputs: 10
Print("Hello!"); // Outputs: Hello!