π§ Introduction to Functions in C
In C programming, a function is a reusable block of code that performs a specific task. Functions help you break down your program into smaller, manageable parts, improve readability, and allow code reuse.
π Why Use Functions?
- Divide and conquer β break large problems into smaller tasks.
- Code reuse β write once, use many times.
- Improve readability and maintenance.
πΉ Syntax of a Function in C
return_type function_name(parameters) {
// Code to execute
}
π Example: Basic Function That Prints a Message
This function prints a simple greeting when called.
#include <stdio.h>
// Function declaration
void greet() {
printf("Hello from a function!\n");
}
int main() {
greet(); // Function call
return 0;
}
π Example: Function with Parameters
This function takes a name and prints a personalized greeting.
#include <stdio.h>
// Function with parameter
void greet(char name[]) {
printf("Hello, %s!\n", name);
}
int main() {
greet("Coder");
return 0;
}
π Example: Function That Returns a Value
Here we create a function that adds two numbers and returns the result.
#include <stdio.h>
// Function that returns a value
int add(int a, int b) {
return a + b;
}
int main() {
int sum = add(5, 3);
printf("Sum is: %d\n", sum);
return 0;
}
π Function Structure in C
- Declaration: Tells the compiler about the function name and return type.
- Definition: Contains the actual code for the function.
- Call: Executes the function.
π― Recap
voidmeans the function doesnβt return a value.- Functions can accept arguments and return results.
- Organize your code using functions for clarity and reuse.
π‘ Practice Time!
Try creating functions for tasks like checking even/odd numbers, calculating factorials, or converting units. Functions make your code modular and awesome!