Functions - 1
Functions - 1
Introduction
• A function is a block of code that performs a specific task.
Types of function
There are two types of function in C programming:
1. Standard library functions
2. User-defined functions
Standard library functions
Example
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required, so the following is
also a valid declaration-
Note: While defining a function, there is no semicolon(;) after the parenthesis in the function header,
unlike while declaring the function or calling the function.
Function body
The function body contains the declarations and the statements necessary for performing the
required task. The body is enclosed within curly braces { ... } and consists of three parts.
•local variable declaration(if required).
•function statements to perform the task inside the function.
•a return statement to return the result evaluated by the function(if return type is void, then no
return statement is required).
Example:
Calling a Function
• To use a function, we need to call that function to perform the defined task.
• When a program calls a function, the program control is transferred to the called function.
• A called function performs a defined task and when its return statement is executed or when its
function-ending closing brace is reached, it returns the program control back to the main program.
• To call a function, you simply need to pass the required parameters along with the function name,
and if the function returns a value, then you can store the returned value.
Example 1
#include <stdio.h>
int max(int num1, int num2); // function declaration
int main ()
{
int a = 100; int b = 200; int ret; //local variable definition
ret = max(a, b); // calling a function to get max value
printf( "Max value is : %d\n", ret );
return 0;
}
int max(int num1, int num2) // function returning the max between two numbers
{
int result; // local variable declaration
if (num1 > num2)
result = num1;
else result = num2;
return result;
}
Example 2
#include<stdio.h>
int multiply(int a, int b); // function declaration
int main()
{
int i, j, result;
printf("Please enter 2 numbers you want to multiply...");
scanf("%d%d", &i, &j);
result = multiply(i, j); // function call
printf("The result of multiplication is: %d", result);
return 0;
}
int multiply(int a, int b)
{
return (a*b); // function definition, this can be done in one line
}