Learning Sections show
Functions in C
Example
#include<stdio.h> // Include the standard input-output library
// Function declaration
int add(int a, int b);
int main() {
// Variables declaration
int result;
// Function call
result = add(5, 3);
// Print the result
printf("Result: %d\n", result);
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
Explanation:
Functions in C are blocks of code that perform specific tasks. They help in breaking the program into smaller, manageable parts.
In this example:
#include<stdio.h>: Includes the standard input-output library which allows us to use theprintffunction.int add(int a, int b);: Declaration of the functionadd, which takes two integer arguments and returns an integer.int main(): The main function where the program execution begins.result = add(5, 3);: Calls theaddfunction with arguments 5 and 3, and stores the return value in the variableresult.printf("Result: %d\n", result);: Prints the result to the console.int add(int a, int b): Definition of theaddfunction. It returns the sum ofaandb.return 0;: Ends the main function and returns 0 to the operating system, indicating that the program ended successfully.
In summary, functions in C allow you to encapsulate code for reuse and better organization. You declare functions before using them, define them with the actual code, and call them when needed.