Functions in C Programming
Functions in C Programming
Functions in C Programming
Section 1 Functions:
A function is a block of statements, which is used to perform a specific task.
Suppose you are building an application in C language and in one of your program,
you need to perform a same task more than once. So in such scenario you have two
options
a)Use the same set of statements every time you want to perform the task
b)Create a function, which would do the task, and just call it every time you need to
perform the same task.
Using option (b) is a good practice and a good programmer always uses functions
while writing codes.
Benefits of Using Functions
1.
It provides modularity to the program.
2.
Easy code Reusability. You just have to call the function by its name to use it.
3.
In case of large programs with thousands of code lines, debugging and
editing becomes easier if you use functions.
General syntax of function declaration is,
return-type function-name (parameter-list);
Like variable and an array, a function must also be declared before its called. A
function declaration tells the compiler about a function name and how to call the
function. The actual body of the function can be defined separately.
A function declaration consist of 4 parts.
return-type
function name
parameter list
terminating semicolon
General syntax of function definition is,
return-type function-name (parameter-list)
{
function-body ;
}
The first line return-type function-name(parameter) is known as function header and
the statement within curly braces is called function body.
return-type : return type specifies the type of value(int,float,char,double) that
function is expected to return to the program calling the function.
function-name : function name specifies the name of the function. The function
name is any valid C identifier and therefore must follow the same rule of formation
as other variables in C.
parameter-list : The parameter list declares the variables that will receive the
data sent by calling program. They often referred to as formal parameters. These
parameters are also used to send values to calling program.
function-body: The function body contains the declarations and the
statement(algorithm) necessary for performing the required task. The body is
enclosed within curly braces { } and consists of three parts.
local variable declaration.
function statement that performs the tasks of the function.
a return statement that return the value evaluated by the function.
Example 1: Write a function that returns the larger of two input numbers
along with the driver code.
#include<stdio.h>
int larger(int a,int b); // function declaration
int main()
/* main is called as driver code since
it is not performing any computation*/
{
int i,j,k;
printf(enter two numbers);
scanf(%d%d,&i,*j);
k=larger(i,j);
// function call
printf("%d",k);
return 0;
}
int larger(int a,int b){
// function declaration
if(a>b)
return a;
else
return b;
}
Lets try few more examples:
Exercise 1: Write a function to find if a given number is prime or not. Function
takes number as input argument. It returns 1 if number is prime else return 0. Based
on the return value, print the appropriate
message in main function.
Exercise 2: Write a program that takes the x-y coordinates of a point in the
Cartesian plane. Write a function which takes as input the x-y coordinates and
returns the quadrant in which it lies.
When the above code is compiled and executed, it produces the following result
value of a in main() = 10
value of a in sum() = 10
value of b in sum() = 20
value of c in main() = 30
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
Data Type Initial Default Value
int
0
char
'\0'
float
0
double
0
pointer
NULL
It is a good programming practice to initialize variables properly, otherwise your
program may produce unexpected results, because uninitialized variables will take
some garbage value already available at their memory location.
Example 3: Write a function that finds the minimum of three numbers. The function
then decrements this minimum number by one and increment other two numbers
(by one). Pass three integers as input arguments to the function and return the
decremented minimum number to main function. Print values of three integers from
within the function, before and after calling the function in main. Emphasize on
scope of variables and pass by value.
Exercise 43: Write a program for the following series. Divide the program into two
functions as follows:
(a) Write a power() function to compute 2a. This function takes variable 'a' as input
argument and
returns 2a.
(b) Write a function to compute sum of series. This function takes 'N' as input
argument and returns the
sum of the series. power() function will be called in this function. Call this function in
main().
Exercise 5: Calculate and print the value of 'i' using the following formula for
different values of x and y:
i = 2 + (y + 0.5x)
Write a program, which will produce a table of values of i, y and x, where y varies
from 1 to 6, and, for
each value of y, x varies from 5.5 to 12.5 in steps of 0.5. Write a function for
implementing the formula.
Pass value of x and y as an input argument. Function returns the value of i. Call this
function inside the
nested loops for different values of x and y.
We can access the value 10 by either using the variable name a or the address 80F.
Since the memory addresses are simply numbers they can be assigned to some
other variable. The variable that holds memory address are called pointer variables.
A pointer variable is therefore nothing but a variable that contains an address,
which is a location of another variable. Value of pointer variable will be stored in
another memory location.
datatype * identifier ;
int *a;
The meaning of the above statement is that a is a pointer variable that holds
address in which integer data is stored.
Note: a itself is not an integer
Example 1: declare a pointer variable that points to float data.
float *f;
Exercise 1: declare a pointer variable that points to character data.
Exercise 2: What is the size of memory for a, f and c pointer variables?
Unlike the variable the pointer variables also will have junk/garbage values. They
have to be initialized before using.
For example:
int a=10;
int *ptra;
ptra=&a; //This statement assigns the pointer address where a is
stored .
*ptra=20; // This statement assign 20 to the memory location pointed by
ptra
Note: & is the address operator also called as reference operator and * is
called as deference operator
Pointers and functions:
There are two ways of passing parameters to functions
1.pass by value
2.pass by reference
Example 2: Demonstrate the implementation of call by value and reference
for a program that swaps two input numbers.
pass by value
pass by reference
#include<stdio.h>
#include<stdio.h>
void swap(int num1, int num2);
void swap(int *num1, int
int main() {
*num2);
int x, y;
int main() {
printf("\nEnter two
int x, y;
numbers : ");
printf("\nEnter two
scanf("%d%d",&x,&y);
numbers : ");
printf("\nBefore Swaping x =
scanf("%d%d",&x,&y);
%d and y = %d", x, y);
printf("\nBefore Swaping x =
swap(x, y); // Function Call %d and y = %d", x, y);
- Pass By Reference
swap(&x, &y); // Function
printf("\nAfter Swaping x =
Call - Pass By Reference
%d and y = %d", x, y);
printf("\nAfter Swaping x =
return 0;
%d and y = %d", x, y);
}
return 0;
void swap(int num1, int num2) { }
int temp;
void swap(int *num1, int *num2)
temp = num1;
{
num1 = num2;
int temp;
num2 = temp;
temp = *num1;
}
*num1 = *num2;
*num2 = temp;
}
Enter two numbers : 2 3
Before Swapping x = 2 and y = 3
After Swaping x = 3 and y = 2
}
return 0;
}
Address of c[0]=28ff44
Address of c[1]=28ff45
Address of c[2]=28ff46
Address of c[3]=28ff47
Notice, that there is equal difference (difference of 1 byte) between any two
consecutive elements of array.
Note: You may get different address of an array.
Relation between Arrays and Pointers
Consider and array:
int arr[4];
Relation between arrays and pointers
In arrays of C programming, name of the array always points to the first element of
an array. Here, address of first element of an array is &arr[0]. Also, arr represents
the address of the pointer where it is pointing. Hence, &arr[0] is equivalent to arr.
Also, value inside the address &arr[0] and address arr are equal. Value in address
&arr[0] is arr[0] and value in address arr is *arr. Hence, arr[0] is equivalent to *arr.
Similarly,
&a[1] is equivalent
&a[2] is equivalent
&a[3] is equivalent
.
.
&a[i] is equivalent
In C, you can declare an
to (a+1)
to (a+2)
to (a+1)
Example 5: Write a C program to find the sum of six numbers with arrays
and pointers
//Program to find the sum of six numbers with arrays and pointers.
#include <stdio.h>
int main(){
int i,class[6],sum=0;
printf("Enter 6 numbers:\n");
for(i=0;i<6;++i){
scanf("%d",(class+i)); // (class+i) is equivalent to &class[i]
sum += *(class+i); // *(class+i) is equivalent to class[i]
}
printf("Sum=%d",sum);
return 0;
}
Output
Enter 6 numbers:
2
3
4
5
3
4
Sum=21
Exercise: Modularize the following program into multiple functions. Consider a list
of prices of books represented as one dimensional array. Traverse the list and
modify the prices according to the following conditions:
(i) if price > 250, offer discount of 10%. Update the price with respect to discount.
(ii) if price > 500, offer discount of 25%. Update the price w.r.t discount.
Modularize it into following functions.
(i) readList(): Populate prices of the items.
(ii) printList(): Prints the price list.
(iii) modifyList(): Modify the prices in the list according to the conditions given
above.
Identify input arguments and return types for all the functions. Also write main
function where the functions are called.
Exercise: Implement insertion sort and bubble sort. First modularize the problem
into separate
functions by identifying arguments and return types. Now implement any one
sorting technique.