C function definitions
Created By: chatGPT
In C, a function is a block of code that performs a specific task. Functions are used to modularize your code, making it more organized and reusable. A function is defined with a return type, name, and parameters (if any). Here’s the basic syntax of a function definition in C:
return_type function_name(parameter_list) {
// function body
// statements
return value; // if return_type is not void
}
Let’s create a function that computes the area of a rectangle. The function will take two parameters: the length and the width of the rectangle, and it will return the calculated area.
float calculate_area(float length, float width) {
return length * width;
}
Next, we can use this function in a main program. We'll declare the main function, call
calculate_area
, and display the result. Here's how this is done:#include <stdio.h>
float calculate_area(float length, float width);
int main() {
float length = 5.0;
float width = 4.0;
float area;
area = calculate_area(length, width);
printf("Area of the rectangle: %.2f\n", area);
return 0;
}
float calculate_area(float length, float width) {
return length * width;
}
In this example, we have:
- Included the standard input-output library (
stdio.h
) for using printf. - Declared the
calculate_area
function above the main function to inform the compiler about it before use. - Called the
calculate_area
function insidemain
and stored the result in the variablearea
. - Printed the area with two decimal points using the
printf
function.
Functions can also return different types of values as per the requirement. If a function does not return a value, you should use the
void
return type. Here’s how you define a void function that simply prints a greeting.void greet() {
printf("Hello, welcome to C programming!\n");
}
You can call this function in your main program as well.
int main() {
greet(); // Calling the greet function
return 0;
}