C FUNCTION
Asmita Deshmukh
WHAT IS C FUNCTION?
• A large C program is divided into basic building
blocks called C function.
• C function contains set of instructions enclosed by
“{ }” which performs specific operation in a C
program.
• Actually, collection of these functions creates a C
program.
USES OF C FUNCTIONS
• C functions are used to avoid rewriting same
logic /code again and again in a program.
• There is no limit in calling C functions to make use of
same functionality wherever required.
• We can call functions any number of times in a
program and from any place in a program.
• A large C program can easily be tracked when it is
divided into functions.
• The core concept of C functions are, re-usability,
dividing a big task into small pieces to achieve the
functionality and to improve understandability of very
large C programs.
C FUNCTION DECLARATION, FUNCTION CALL
AND FUNCTION DEFINITION:
• There are 3 aspects in each C function. They are,
• Function declaration or prototype–
This informs compiler about the function name,
function parameters and return value’s data type.
• Function call – This calls the actual function
• Function definition – This contains all the
statements to be executed.
C functions syntax
aspects
function Return_type
definition function_name
(arguments list)
{ Body of function; }
function call function_name (arguments
list);
function return_type
declaration function_name (argument
list);
LOCAL VARIABLES
Calling function (Caller)
Called function (Callee) parameter
void main() float cent2fahr(float data)
6
{ float cent, fahr; {
scanf(“%f”,¢); float result;
fahr = cent2fahr(cent); result = data*9/5 + 32;
printf(“%fC = %fF\n”, cent, return result;
fahr); }
}
Parameter passed
Returning value
Calling/Invoking the cent2fahr function
RETURN STATEMENT
In a value-returning function (return type is not void), return does
two distinct things
⚫ specify the value returned by the execution of the function
⚫ terminate that execution of the callee and transfer control back
to the caller
A function can only return one value
⚫ The value can be any expression matching the return type
⚫ but it might contain more than one return statement.
In a void function
⚫ return is optional at the end of the function body.
⚫ return may also be used to terminate execution of the function
explicitly.
⚫ No return value should appear following return.
void compute_and_print_itax ()
{
float income;
scanf (“%f”, &income); Terminate function
if (income < 50000) { execution before
printf (“Income tax = Nil\n”);
reaching the end
return;
}
if (income < 60000) {
printf (“Income tax = %f\n”, 0.1*(income-50000));
return;
}
if (income < 150000) {
printf (“Income tax = %f\n”, 0.2*(income-60000)+1000);
return ;
}
printf (“Income tax = %f\n”, 0.3*(income-150000)+19000);
}
8
EXAMPLE
int sum(int a, int b); // Function declaration with parameter names
int sum(int , int); // Function declaration without parameter names
WORKING OF A C FUNCTION
FUNCTION FOR SUM OF 2 NUMBERS
#include <stdio.h>
// Function that takes two parameters
// a and b as inputs and returns
// their sum
int sum(int a, int b)
{
return a + b;
}
int main()
{
// Calling sum function and
// storing its value in add variable
int add = sum(10, 30);
printf("Sum is: %d", add);
return 0;
}
Output:
Sum is: 40
SIMPLE EXAMPLE PROGRAM FOR C FUNCTION
• As you know, functions should be declared and
defined before calling in a C program.
• In the below program, function “square” is called
from main function.
• The value of “m” is passed as argument to the
function “square”. This value is multiplied by itself
in this function and multiplied value “p” is returned
to main function from function “square”.
CONTI..
#include<stdio.h>
// function prototype, also called function declaration
float square ( float x );
int main( )
{
float m, n ;
printf ( "\nEnter some number for finding square \n");
scanf ( "%f", &m ) ;
n = square ( m ) ; // function call
printf ( "\nSquare of the given number %f is %f",m,n );
}
float square ( float x ) // function definition
{
float p ; Enter some number for finding square 2
p=x*x; Square of the given number 2.000000 is
return ( p ) ; 4.000000
}
Function declaration
(prototype)
int factorial (int m);
Another Example int main()
{
int n;
int factorial (int m)
for (n=1; n<=10; n++)
14
{ printf (“%d! = %d \n”,
int i, temp=1; n, factorial (n) );
for (i=1; i<=m; i++) }
temp = temp * i;
return (temp); Function call
} Output
1! = 1
2! = 2
Function definition 3! = 6 …….. upto 10!
FORMAL AND ACTUAL PARAMETERS IN PROGRAMMING
In programming, parameters are variables or values passed to a function or method
during its invocation. They enable the function to receive input data, perform
operations, and optionally return a result.
What are Formal Parameters?
Formal parameters, also known as formal arguments, are placeholders defined in the
function signature or declaration. They represent the data that the function expects to
receive when called. Formal parameters serve as variables within the function's scope
and are used to perform operations on the input data.
What are Actual Parameters?
Actual parameters, also called actual arguments or arguments, are the values or
expressions provided to a function or method when it is called. They correspond to the
formal parameters in the function's definition and supply the necessary input data for
the function to execute. Actual parameters can be constants, variables, expressions, or
even function calls.
#include <stdio.h>
// a and b are formal parameters
int sum_numbers(int a, int b)
{
return a + b;
}
int main()
{
// 3 and 5 are actual parameters
int result = sum_numbers(3, 5);
printf("Sum: %d\n", result);
return 0;
}
HOW DOES C FUNCTION WORK?
Working of the C function can be broken into the following steps as mentioned
below:
Declaring a function: Declaring a function is a step where we declare a function.
Here we specify the return types and parameters of the function.
Defining a function: This is where the function’s body is provided. Here, we
specify what the function does, including the operations to be performed when the
function is called.
Calling the function: Calling the function is a step where we call the function by
passing the arguments in the function.
Executing the function: Executing the function is a step where we can run all the
statements inside the function to get the final result.
Returning a value: Returning a value is the step where the calculated value after
the execution of the function is returned. Exiting the function is the final step
where all the allocated memory to the variables, functions, etc is destroyed before
giving full control back to the caller.
HOW TO CALL C FUNCTIONS IN A
PROGRAM
There are two ways that a C function can be called
from a program.
• Call by value
• Call by reference
CALL BY VALUE
• In call by value method, the value of the variable is
passed to the function as parameter.
• The value of the actual parameter can not be modified
by formal parameter.
• Different Memory is allocated for both actual and
formal parameters. Because, value of actual parameter
is copied to formal parameter.
• Note:
• Actual parameter – This is the argument which is used
in function call.
• Formal parameter – This is the argument which is used
in function definition
EXAMPLE PROGRAM FOR C FUNCTION
(USING CALL BY VALUE):
• In this program, the values of the variables “m”
and “n” are passed to the function “swap”.
• These values are copied to formal parameters “a”
and “b” in swap function and used.
CONTI..
#include<stdio.h>
// function prototype, also called function declaration
void swap(int a, int b);
int main()
{
int m = 22, n = 44;
// calling swap function by value
printf(" values before swap m = %d \nand n = %d", m, n);
swap(m, n);
}
void swap(int a, int b)
{
int tmp; tmp = a;
a = b;
b = tmp;
printf(" \nvalues after swap m = %d\n and n = %d", a, b);
}
OUTPUT
values before swap m = 22 and n = 44
values after swap m = 44 and n = 22
CALL BY REFERENCE:
• In call by reference method, the address of the
variable is passed to the function as parameter.
• The value of the actual parameter can be
modified by formal parameter.
• Same memory is used for both
// function call actual and formal
parameters since only address is used by both
parameters.
EXAMPLE PROGRAM FOR C FUNCTION
(USING CALL BY REFERENCE)
• In this program, the address of the variables “m” and
“n” are passed to the function “swap”.
• These values are not copied to formal parameters “a”
and “b” in swap function.
• Because, they are just holding the address of
those variables.
• This address is used to access and change the
values of the variables.
CONTI..
#include<stdio.h>
// function prototype, also called function declaration
void swap(int *a, int *b);
int main()
{
int m = 22, n = 44;
// calling swap function by reference
printf("values before swap m = %d \n and n = %d",m,n);
swap(&m, &n);
}
void swap(int *a, int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
printf("\n values after swap a = %d \nand b = %d", *a, *b);
}
OUTPUT
values before swap m = 22 and n = 44
values after swap a = 44 and b=22
CONDITIONS OF RETURN TYPES AND ARGUMENTS
In C programming language, functions can be called either with
or without arguments and might return values. They may or
might not return values to the calling functions.
Function with no arguments and no return value
Function with no arguments and with return value
Function with argument and with no return value
Function with arguments and with return value
DIFFERENCE B/W CALL BY VALUE & CALL BY REFERENCE
Call By Values Call By Reference
While calling a function, instead of passing the
While calling a function, we pass the values of
values of variables, we pass the address of
variables to it. This is known as “Call By
variables(location of variables) to the function
Values”.
known as “Call By References.
In this method, the value of each variable in the In this method, the address of actual variables in
calling function is copied into corresponding the calling function is copied into the dummy
dummy variables of the called function. variables of the called function.
With this method, the changes made to the
With this method, using addresses we would
dummy variables in the called function have no
have access to the actual variables and hence we
effect on the values of actual variables in the
would be able to manipulate them.
calling function.
In call-by-values, we cannot alter the values of In call by reference, we can alter the values of
actual variables through function calls. variables through function calls.
Values of variables are passed by the Simple Pointer variables are necessary to define to store
technique. the address values of variables.
This method is preferred when we have to pass This method is preferred when we have to pass a
some small values that should not change. large amount of data to the function.
Call by value is considered safer as original data Call by reference is risky as it allows direct
is preserved modification in original data
EXAMPLE: main calls ncr, ncr calls fact
int ncr (int n, int r)
int ncr (int n, int r); {
int fact (int n); return (fact(n) / (fact(r) *
fact(n-r)));
29
}
void main()
{ int fact (int n)
int i, m, n, sum=0; {
scanf (“%d %d”, &m, &n); int i, temp=1;
/*changes for i=i+2 if for all values for (i=1; i<=n; i++)
of n*/ temp *= i;
for (i=1; i<=m; i+=2) return (temp);
sum = sum + ncr (n, i); }
printf (“Result: %d \n”, sum); Output
for m and n as 3 and 5 is
} 15(5+10(3))
For i=i+1 is 25 (5+10+10)
SCOPE OF A VARIABLE
Part of the program from which the value of the variable can be
used (seen)
Scope of a variable - Within the block in which the variable is
defined
⚫ Block = group of statements enclosed within { }
Local variable – scope is usually the function in which it is defined
⚫ So two local variables of two functions can have the same
name, but they are different variables
Global variables – declared outside all functions (even main)
⚫ scope is entire program by default, but can be hidden in a block
if local variable of same name defined
#include <stdio.h>
int A = 1;
VARIABLE
void main() Global variable
{ SCOPE
myProc();
printf ( "A = %d\n", A);
} Hides the global A
void myProc()
Output:
{ int A = 2;
if ( A==2 ) A=3
{
A = 3;
printf ( "A = %d\n", A); A=1
}
}
/* User defined function sum that has two int parameters. The function
adds these numbers and return the result of addition. */
#include <stdio.h>
int sum(int a, int b)
{
return a+b;
}
int main()
{
int num1, num2, num3;
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);
//Calling the function
num3 = sum(num1, num2);
printf("Sum of the entered numbers: %d", num3);
return 0;
}
Program to check entered no is prime or not using function
#include <stdio.h> int main()
{ int N;
int isPrime(int N) printf("Enter a number:");
{ scanf("%d",&N);
for (int i = 2; i <= N/2; i++) printf("Is %d prime?\n", N);
{
if (N % i == 0) // Check if the number is prime
{
return 0; if (isPrime(N))
} { printf("Yes\n"); }
} else
return 1; { printf("No\n"); }
} return 0;
}
Output:
Enter a number:11
Is 11 prime?
Yes
Fibonacci Series Program In C using function
void fibo(int n)
#include<stdio.h> {
void fibo(int); int i,c, a=0, b=1;
void main() printf("Fibonacci series :\n");
{ if(n>=1)
int n; printf("%d ",a);
printf("Enter a number:"); if(n>=2)
scanf("%d",&n); printf("%d ",b);
fibo(n); for(i=3;i<=n;i++)
} {
c=a+b;
printf("%d ",c);
a=b;
Output: b=c;
Enter a number: 8
}
Fibonacci series: 0 1 1 2 3 5 8 13
}
Program to find Reverse and Sum of digits using function
int reverse (int Num)
#include <stdio.h>
{
int reverse(int); int remainder, Rev = 0;
int digitsum (int Num); while (Num > 0)
int main() {
{ remainder = Num %10;
int Num, Rev, sum; Rev = Rev *10+ remainder;
printf("\nEnter the number: "); Num = Num /10;
scanf("%d", &Num); }
sum=digitsum(Num); return Rev;
Rev = reverse (Num); }
printf("Reverse of %d is = %d\n", Num, int digitsum (int Num)
Rev); {
printf("Digit sum %d is = %d\n", Num, int remainder, sum = 0;
sum); while (Num > 0){
return 0; remainder = Num %10;
} sum = sum+ remainder;
Num = Num /10;
Output }
Enter the number: 8762
return sum;
Reverse of 8762 is = 2678
Digit sum 8762 is = 23
}
Program to find GCD and LCM using function
#include <stdio.h>
// Function to return gcd of a and b int main()
void gcd_lcm(int a, int b) {
{ int a ,b;
int gcd,lcm; printf("Enter two integers:");
// Find Minimum of a and b scanf("%d%d",&a,&b);
gcd = ((a < b) ? a : b); gcd_lcm(a,b);
while (gcd > 0) return 0;
{ }
// Check if both a and b are divisible by result
if (a % gcd == 0 && b % gcd == 0)
{ Output:
break;
} Enter two integers:10 15
gcd--; GCD of 10 and 15 is 5
}
lcm=(a*b)/gcd; LCM of 10 and 15 is 30
printf("GCD of %d and %d is %d \n", a, b,gcd);
printf("LCM of %d and %d is %d \n", a, b,lcm);
}
TYPES OF FUNCTIONS
There are two types of functions in C:
Library Functions
User Defined Functions
1. LIBRARY FUNCTION
A library function is also referred to as a “built-in function”. A compiler
package already exists that contains these functions, each of which has a
specific meaning and is included in the package. Built-in functions have the
advantage of being directly usable without being defined, whereas
user-defined functions must be declared and defined before being used.
For Example:
pow(), sqrt(), strcmp(), strcpy() etc.
Advantages of C library functions
C Library functions are easy to use and optimized for better performance.
C library functions save a lot of time i.e, function development time.
C library functions are convenient as they always work.