Function
Function
Function
A function is a group of statements that together perform a task.
Every C program has at least one function, which is main(), and all the
most trivial programs can define additional functions.
Example: main()
Need of Function
1. REUSABILITY.
Once a function is defined, it can be used over and over and over again.
We can invoke the same function many times in our program, which saves
our work.
Example: Imagine what programming would be like if we had to teach the
computer about square root function every time we needed to find the
square root of a number.
NOTE:: We can also reuse functions that somebody else has written for
us, such as the sqrt, sine and cosine functions.
Contd..
2. ABSTRACTION
NOTE : If we just want to use the function in our program, we don't have to
know how it works inside! We don't have to understand anything about what
goes on inside the function.
• We can call functions any number of times in a program and from any place
in a program.
• 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.
Types of functions in C
These functions are defined in the header file. When you include the header
file, these functions are available for use.
Example:
The printf() is a standard library function to send formatted output to the
screen (display output on the screen). This function is defined in "stdio.h"
header file.
There are other numerous library functions defined under "stdio.h", such as
scanf(), fprintf(), getchar() etc.
Once you include "stdio.h" in your program, all these functions are available for
use.
User-defined functions
How user-defined function works?
The argument-list contains the types and names of arguments that must be passed to
the function.
Example: int max(int x, int y);
NOTE:
Each argument must be declared independently inside the parenthesis.
In a function declaration names of arguments are dummy variables and therefore
are optional.
Example: int max(int, int);
Function Definition
A function definition provides the actual body of the 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.
Function Declaration
Function Calling
Function Defining
Passing arguments to a function
• In programming, argument refers to the variable
passed to the function. In the given example, two
variables n1 and n2 are passed during function
call.
Actual Argument
Formal
Argument
Types of User-defined Functions
Function with no arguments and no return value
//checks whether it is a prime number or not and displays it on the screen.
#include <stdio.h>
void checkPrimeNumber();
int main()
{
checkPrimeNumber(); // no argument is passed to prime()
return 0;
}
/*return type of the function is void no value is returned from the function */
void checkPrimeNumber() {
int n, i, flag=0;
printf("Enter a positive integer: ");
scanf("%d",&n);
for(i=2; i <= n/2; ++i) {
if(n%i == 0)
{ flag = 1; break; }
}
if (flag == 1)
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);
}
Function with no arguments and no return value
#include <stdio.h>
void checkPrimeNumber();
int main() { •The checkPrimeNumber() function
// no argument is passed to prime() takes input from the user, checks
checkPrimeNumber(); whether it is a prime number or not
return 0; } and displays it on the screen.
/*return type of the function is void
no value is returned from the function */
void checkPrimeNumber() •The empty parentheses in
{ int n, i, flag=0; checkPrimeNumber(); statement
printf("Enter a positive integer: "); inside the main() function indicates
scanf("%d",&n); that no argument is passed to the
for(i=2; i <= n/2; ++i) { function.
if(n%i == 0) { flag = 1; break; }
} •The return type of the function
if (flag == 1) is void. Hence, no value is returned
printf("%d is not a prime number.", n);
from the function.
else
printf("%d is a prime number.", n);
}
No arguments passed but a return value
#include <stdio.h> int getInteger() {
int getInteger(); int n;
int main() { printf("Enter a positive integer: ");
int n, i, flag = 0; scanf("%d",&n);
n = getInteger(); return n;
for(i=2; i<=n/2; ++i) }
{
if(n%i==0)
{ The empty parentheses in n = getInteger();
flag = 1; statement indicates that no argument is
break; passed to the function and, the value
} returned from the function is assigned to n.
}
if (flag == 1) Here, the getInteger() function takes
printf("%d is not a prime number.", n); input from the user and returns it.
else
printf("%d is a prime number.", n);
return 0;
}
Argument passed but no return value
#include <stdio.h>
void checkPrimeAndDisplay(int n);
int main()
{ int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
checkPrimeAndDisplay(n); // n is passed to the function
return 0;
}
// void indicates that no value is returned from the function
void checkPrimeAndDisplay(int n) {
int i, flag = 0;
for(i=2; i <= n/2; ++i) {
if(n%i == 0) {
flag = 1;
break;
}
}
if(flag == 1)
printf("%d is not a prime number.",n);
else
printf("%d is a prime number.", n);
}
Argument passed but no return value
#include <stdio.h>
void checkPrimeAndDisplay(int n);
int main() {
int n;
The integer value entered by the user is
printf("Enter a positive integer: ");
passed to checkPrimeAndDisplay()
scanf("%d",&n);
function.
checkPrimeAndDisplay(n);
Here, the checkPrimeAndDisplay()
return 0;
function checks whether the argument
}
passed is a prime number or not and
void checkPrimeAndDisplay(int n) {
displays the appropriate message.
int i, flag = 0;
for(i=2; i <= n/2; ++i) {
if(n%i == 0)
{ flag = 1; break; }
}
if(flag == 1)
printf("%d is not a prime number.",n);
else
printf("%d is a prime number.", n);
}
Argument passed and a return value
#include <stdio.h>
int checkPrimeNumber(int n);
int main() {
int n, flag;
printf("Enter a positive integer: ");
scanf("%d",&n);
flag = checkPrimeNumber(n); // n is passed to the checkPrimeNumber() function the value
returned from the function is assigned to flag variable
if(flag==1)
printf("%d is not a prime number",n);
else printf("%d is a prime number",n);
return 0;
}
int checkPrimeNumber(int n) { // integer is returned from the function
int i; /* Integer value is returned from function checkPrimeNumber() */
for(i=2; i <= n/2; ++i) {
if(n%i == 0)
return 1;
}
return 0; }
Argument passed and a return value
#include <stdio.h>
int checkPrimeNumber(int n);
int main() { •The input from the user is passed to
int n, flag; checkPrimeNumber() function.
•The checkPrimeNumber() function
printf("Enter a positive integer: ");
checks whether the passed argument
scanf("%d",&n); is prime or not.
flag = checkPrimeNumber(n); •If the passed argument is a prime
if(flag==1) number, the function returns 0.
printf("%d is not a prime number",n); •If the passed argument is a non-prime
number, the function returns 1.
else printf("%d is a prime number",n);
•The return value is assigned to flag
return 0; } variable.
int checkPrimeNumber(int n) { •Then, the appropriate message is
int i; displayed from the main() function.
for(i=2; i <= n/2; ++i) {
if(n%i == 0)
return 1; }
return 0; }
Argument passing in function
While calling a function, there are two ways in which arguments can be
passed to a function −
1. Call by value
2. 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
In this program, the values of the variables “a” and “b” are passed to the function “swap”.
These values are copied to formal parameters “x” and “y” in swap function and used.
#include<stdio.h>
int swap(int , int); //Declaration of function
int main( )
{
int a = 10, b = 20 ; // a and b are actual parameters
swap(a,b); // call by value
printf ( "\n a = %d b = %d", a, b ) ;
} Output:
int swap( int x, int y ) // x and y are formal parameters x=20 y=10
{ a=10 b=20
int t ;
t=x;
x=y;
y=t;
printf ( "\nx = %d y = %d", x, y ) ;
}
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 actual and formal parameters since only
address is used by both parameters.
}
Scope of variables
A scope in any programming is a region of the program where a defined
variable can have its existence and beyond that variable it cannot be accessed
include <stdio.h>
int main () {
int a, b,c; /* local variable declaration */
a = 10; b = 20; /* actual initialization */
c = a + b;
printf ("value of a = %d, b = %d and c = %d\n", a, b, c);
return 0;
}
Global Variables
Global variables are defined outside a function, usually on top of the
program.
Global variables hold their values throughout the lifetime of your program
and they can be accessed inside any of the functions defined for the
program.
A global variable can be accessed by any function. That is, a global variable
is available for use throughout your entire program after its declaration.
The following program show how global variables are used in a program.
#include <stdio.h>
int g; /* global variable declaration */
int main ()
{
int a, b; /* local variable declaration */
a = 10; b = 20; /* actual initialization */
g=a+b
printf ("value of a = %d, b = %d and g = %d\n", a, b, g);
return 0;
}
Local and Global Variables
A program can have same name for local and global variables but the value of
local variable inside a function will take preference.
Here is an example −
#include <stdio.h>
/* global variable declaration */
int g = 20;
Output:
int main () { value of g = 10
/* local variable declaration */
int g = 10;
printf ("value of g = %d\n", g);
return 0;
}
Formal Parameters
Formal parameters, are treated as local variables with-in a function and they
take precedence over global variables.
Following is an example −
#include <stdio.h>
int a = 20; /* global variable declaration */
int main ()
{
int a = 10; int b = 20; int c = 0; /* local variable declaration in main */
printf ("value of a in main() = %d\n", a);
c = sum( a, b); /* a & b are actual parameter */
printf ("value of c in main() = %d\n", c);
return 0;
}
int sum(int a, int b) /* function to add two integers */
{
printf ("value of a in sum() = %d\n", a);
printf ("value of b in sum() = %d\n", b);
return a + b;
}
Formal Parameters
#include <stdio.h>
int a = 20;
int main ()
{
int a = 10; int b = 20; int c = 0;
printf ("value of a in main() = %d\n", a);
c = sum( a, b);
printf ("value of c in main() = %d\n", c);
return 0;
}
int sum(int a, int b)
{
printf ("value of a in sum() = %d\n", a);
printf ("value of b in sum() = %d\n", b);
return a + b;
}
Initializing Local and Global Variables
When a local variable is defined, it is not initialized by the system, you must
initialize it yourself.
Global variables are initialized automatically by the system when you define them
as follows:
Auto variables have local scope ie. can be accessed within the
function or block it is declared.
Variables having automatic storage class are local to the block which
they are defined in, and get destroyed on exit from the block.
Example
Output:
0000
Extern
Extern variables are stored in CPU Memory.
Initial/default value of the variable is 0.
Extern variables have global scope ie. Can be accessed from anywhere in
the program.
It exists till the end of the main program. Variable definition might be
anywhere in the C program.
The principal use of extern is to specify that a variable is declared
with external linkage elsewhere in the program.
When extern specifier is used with a variable declaration then no storage is
allocated to that variable and it is assumed that the variable has already been
defined elsewhere in the program.
When we use extern specifier the variable cannot be initialized because
with extern specifier variable is declared, not defined.
Example
Output:
The value of x is 10
The value of y is 50
Static
Static variables are stored in CPU Memory.
Initial/default value of the variable is 0.
Static variables have local scope ie. Can be accessed within the function or
block it is declared.
Retains the value of the variable between different function calls.
It has program lifetime.
The static specifier gives the declared variable static storage class. Static
variables can be used within function or file.
Unlike global variables, static variables are not visible outside their function
or file, but they maintain their values between calls.
The static specifier has different effects upon local and global variables.
When static specifier is applied to a local variable inside a function or block,
the compiler creates permanent storage for it, much as it creates storage for
a global variable but static local variable remains visible only to the function
or block in which it is defined.
In simple terms, a static local variable is a local variable that retains its
value between function calls.
Example
Output:
0123
Register
The register specifier declares a variable of register storage class.
Register variables are stored in register Memory.
Initial/default value of the variable is garbage value.
Register variables have local scope ie. Can be accessed within the function
or block it is declared.
Variables belonging to register storage class are local to the block which
they are defined in, and get destroyed on exit from the block.
It has function lifetime.
A register declaration is equivalent to an auto declaration, but hints
that the declared variable will be accessed frequently; therefore they
are placed in CPU registers, not in memory.
Only a few variables are actually placed into registers, and only certain
types are eligible; the restrictions are implementation-dependent.
However, if a variable is declared register, the unary & (address of)
operator may not be applied to it, explicitly or implicitly.
Note
For faster access of a variable, it is better to go for register specifiers rather
than auto specifiers.
Only few variables can be stored in register memory. So, we can use
variables as register that are used very often in a C program.
But, only limited variables can be used as register since register size is very
low. (16 bits, 32 bits or 64 bits)
Example
Output:
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50
Passing Array to function
In C programming, a single array element or an
entire array can be passed to a function.
This can be done for both one-dimensional array or a
multi-dimensional array.
If we want to pass a single-dimension array as an
argument in a function, we would have to declare a
formal parameter in one of following three ways.
All three declaration methods produce similar results
because each tells the compiler that an integer pointer
is going to be received.
Similarly, we can pass multi-dimensional arrays as
formal parameters
Way 1
Formal parameters as a pointer −
void myFunction(int *param)
{.....
.....
.....
}
Way 2
Formal parameters as a sized array −
#include <stdio.h>
void display(int age)
{
printf("%d", age);
}
int main()
{
int ageArray[] = { 2, 3, 4 };
display(ageArray[2]);
return 0;
}
Example
Passing an entire one-dimensional array to a function
Now, consider the following function, which takes an array as an argument
along with another argument and based on the passed arguments, it returns the
average of the numbers passed through the array as follows −
#include <stdio.h>
double getAverage(int arr[], int size);
int main () {
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
avg = getAverage( balance, 5 ) ;
printf( "Average value is: %f ", avg );
return 0; }
double getAverage(int arr[], int size) {
int i; double avg; double sum = 0;
for (i = 0; i < size; ++i)
{ sum += arr[i]; }
avg = sum / size; return avg;
}
Example
Passing an entire one-dimensional array to a function
While passing arrays as arguments to the function, only the name of the array is
passed (,i.e, starting address of memory area is passed as argument).
#include <stdio.h>
float average(float age[]);
int main()
{
float avg, age[] = { 23.4, 55, 22.6, 3, 40.5, 18 };
avg = average(age);
printf("Average age=%.2f", avg);
return 0;
}
float average(float age[]) {
int i; float avg, sum = 0.0;
for (i = 0; i < 6; ++i)
{ sum += age[i]; }
avg = (sum / 6);
return avg; }
Example
Passing Multi-dimensional Arrays to Function :To pass two-dimensional array to a
function as an argument, starting address of memory area reserved is passed as in one
dimensional array.
#include <stdio.h>
void displayNumbers(int num[2][2]);
int main()
{ int num[2][2], i, j;
printf("Enter 4 numbers:\n");
for (i = 0; i < 2; ++i)
for (j = 0; j < 2; ++j)
scanf("%d", &num[i][j]);
displayNumbers(num);
return 0; }
void displayNumbers(int num[2][2])
{ int i, j;
printf("Displaying:\n");
for (i = 0; i < 2; ++i)
for (j = 0; j < 2; ++j)
printf("%d\n", num[i][j]); }