EST 102 MODULE 4
Functions in C
A function is a block of code that performs a particular task.
There are many situations where we might need to write same line of code for
more than once in a program.
This may lead to unnecessary repetition of code, bugs and even becomes
boring for the programmer.
So, C language provides an approach in which you can declare and define a
group of statements once in the form of a function and it can be called and
used whenever required.
These functions defined by the user are also known as User-defined Functions
C functions can be classified into two categories,
Library functions
User-defined functions
1
Library functions are those functions which are already defined in C library,
example printf(), scanf(), strcat() etc. You just need to include appropriate
header files to use these functions. These are already declared and defined in
C libraries.
A User-defined functions on the other hand, are those functions which are
defined by the user at the time of writing program. These functions are made
for code reusability and for saving time and space.
Benefits of Using Functions
It provides modularity to your program's structure.
It makes your code reusable. You just have to call the function by its name to
use it, wherever required.
In case of large programs with thousands of code lines, debugging and editing
becomes easier if you use functions.
It makes the program more readable and easy to understand.
Function Declaration
General syntax for function declaration is,
returntype functionName(type1 parameter1, type2 parameter2,...);
Like any variable or an array, a function must also be declared before it’s used.
Function declaration informs the compiler about the function name,
parameters is accept, and its return type.
The actual body of the function can be defined separately. It's also called
as Function Prototyping.
2
Function declaration consists of 4 parts.
returntype
function name
parameter list
terminating semicolon
returntype
When a function is declared to perform some sort of calculation or any
operation and is expected to provide with some result at the end, in such cases,
a return statement is added at the end of function body.
Return type specifies the type of value (int, float, char, double) that function
is expected to return to the program which called the function.
Note: In case your function doesn't return any value, the return type would be void.
functionName
Function name is an identifier and it specifies the name of the function.
The function name is any valid C identifier and therefore must follow the same
naming rules like other variables in C language.
parameter list
The parameter list declares the type and number of arguments that the function
expects when it is called.
Also, the parameters in the parameter list receives the argument values when
the function is called. They are often referred as formal parameters.
3
Example
Let's write a simple program with a main() function, and a user defined function to
multiply two numbers, which will be called from the main() function.
#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 muliplication is: %d", result);
return 0;
}
int multiply(int a, int b)
{
return (a*b); // function defintion, this can be done in one line
}
4
Function definition Syntax
Just like in the example above, the general syntax of function definition is,
returntype functionName(type1 parameter1, type2 parameter2,...)
// function body goes here
The first line returntype functionName(type1 parameter1, type2
parameter2,...) is known as function header and the statement(s) within curly
braces is called function body.
functionbody
The function body contains the declarations and the statements(algorithm)
necessary for performing the required task.
The body is enclosed within curly braces { ... } and consists of three parts.
(a) Local variable declaration (if required).
(b) Function statements to perform the task inside the function.
(c) A return statement to return the result evaluated by the function (if
return type is void, then no return statement is required).
Calling a function
When a function is called, control of the program gets transferred to the
function.
functionName(argument1, argument2,...);
5
Passing Arguments to a function
Arguments are the values specified during the function call, for which the
formal parameters are declared while defining the function.
It is possible to have a function with parameters but no return type. It is not
necessary, that if a function accepts parameter(s), it must return a result too.
While declaring the function, we have declared two parameters a and b of
type int. Therefore, while calling that function, we need to pass two
arguments, else we will get compilation error.
And the two arguments passed should be received in the function definition,
which means that the function header in the function definition should have
the two parameters to hold the argument values. T
These received arguments are also known as formal parameters. The name of
the variables while declaring, calling and defining a function can be different.
6
Returning a value from function
A function may or may not return a result. But if it does, we must use
the return statement to output the result. return statement also ends the
function execution, hence it must be the last statement of any function.
If you write any statement after the return statement, it won't be executed.
The
datatype
of the
value
returned
using
7
the return statement should be same as the return type mentioned at function
declaration and definition. If any of it mismatches, you will get compilation
error.
Type of User-defined Functions in C
There can be 4 different types of user-defined functions, they are:
Function with no arguments and no return value
Function with no arguments and a return value
Function with arguments and no return value
Function with arguments and a return value
Function with no arguments and no return value
Such functions can either be used to display information or they are
completely dependent on user inputs.
Below is an example of a function, which takes 2 numbers as input from user,
and display which is the greater number.
#include<stdio.h>
void greatNum(); // function declaration
int main()
{
greatNum(); // function call
return 0;
}
8
void greatNum() // function definition
{
int i, j;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
if(i > j) {
printf("The greater number is: %d", i);
}
else {
printf("The greater number is: %d", j);
}
}
Function with no arguments and a return value
We have modified the above example to make the function greatNum() return
the number which is greater amongst the 2 input numbers.
#include<stdio.h>
int greatNum(); // function declaration
int main()
{
int result;
result = greatNum(); // function call
printf("The greater number is: %d", result);
return 0;
}
9
int greatNum() // function definition
{
int i, j, greaterNum;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
if(i > j) {
greaterNum = i;
}
else {
greaterNum = j;
}
// returning the result
return greaterNum;
}
Function with arguments and no return value
This time, we have modified the above example to make the
function greatNum() take two int values as arguments, but it will not be
returning anything.
#include<stdio.h>
void greatNum(int a, int b); // function declaration
int main()
{
10
int i, j;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
greatNum(i, j); // function call
return 0;
}
void greatNum(int x, int y) // function definition
{
if(x > y) {
printf("The greater number is: %d", x);
}
else {
printf("The greater number is: %d", y);
}
}
Function with arguments and a return value
This is the best type, as this makes the function completely independent of
inputs and outputs, and only the logic is defined inside the function body.
#include<stdio.h>
int greatNum(int a, int b); // function declaration
int main()
{
int i, j, result;
11
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
result = greatNum(i, j); // function call
printf("The greater number is: %d", result);
return 0;
}
int greatNum(int x, int y) // function definition
{
if(x > y) {
return x;
}
else {
return y;
}
}
Nesting of Functions
C language also allows nesting of functions i.e to use/call one function inside
another function's body.
function1()
{
// function1 body here
function2();
// function1 body here }
12
If function2() also has a call for function1() inside it, then in that case, it will
lead to an infinite nesting. They will keep calling each other and the program
will never terminate.
What is Recursion?
Recursion is a special way of nesting functions, where a function calls itself
inside it.
We must have certain conditions in the function to break out of the recursion,
otherwise recursion will occur infinite times.
function1()
{
// function1 body
function1();
// function1 body
}
Example: Factorial of a number using Recursion
#include<stdio.h>
int factorial(int x); //declaring the function
void main()
{
int a, b;
printf("Enter a number...");
13
scanf("%d", &a);
b = factorial(a); //calling the function named factorial
printf("%d", b);
}
int factorial(int x) //defining the function
{
int r = 1;
if(x == 1)
return 1;
else
r = x*factorial(x-1); //recursion, since the function calls itself
return r;
}
Types of Function calls in C
In functions with arguments, we can call a function in two different ways,
based on how we specify the arguments, and these two ways are:
Call by Value
Call by Reference
Call by Value
Calling a function by value means, we pass the values of the arguments which
are stored or copied into the formal parameters of the function.
14
Hence, the original values are unchanged only the parameters inside the
function changes.
#include<stdio.h>
void calc(int x);
int main()
{
int x = 10;
calc(x);
// this will print the value of 'x'
printf("\nvalue of x in main is %d", x);
return 0;
}
void calc(int x)
{
// changing the value of 'x'
x = x + 10 ;
printf("value of x in calc function is %d ", x);
}
OUTPUT:
value of x in calc function is 20
value of x in main is 10
15
In this case, the actual variable x is not changed. This is because we are
passing the argument by value, hence a copy of x is passed to the function,
which is updated during function execution, and that copied value in the
function is destroyed when the function ends(goes out of scope).
So the variable x inside the main() function is never changed and hence, still
holds a value of 10.
But we can change this program to let the function modify the
original x variable, by making the function calc() return a value, and storing
that value in x.
#include<stdio.h>
int calc(int x);
int main()
{
int x = 10;
x = calc(x);
printf("value of x is %d", x);
return 0;
}
int calc(int x)
{
x = x + 10 ;
return x;
}
16
OUTPUT:
value of x is 20
Call by Reference
In call by reference we pass the address (reference) of a variable as argument
to any function.
When we pass the address of any variable as argument, then the function will
have access to our variable, as it now knows where it is stored and hence can
easily update its value.
In this case the formal parameter can be taken as a reference or a pointer(don't
worry about pointers, we will soon learn about them), in both the cases they
will change the values of the original variable.
#include<stdio.h>
void calc(int *p); // functin taking pointer as argument
int main()
{
int x = 10;
calc(&x); // passing address of 'x' as argument
printf("value of x is %d", x);
return(0);
}
17
void calc(int *p) //receiving the address in a reference pointer variable
{
/*
changing the value directly that is
stored at the address passed
*/
*p = *p + 10;
}
OUTPUT:
value of x is 20
Pointers as Function Argument
Pointer as a function parameter is used to hold addresses of arguments passed
during function call. This is also known as call by reference.
When a function is called by reference any change made to the reference
variable will affect the original variable.
Example: Swapping two numbers using Pointer
#include <stdio.h>
void swap(int *a, int *b);
int main()
{
int m = 10, n = 20;
18
printf("m = %d\n", m);
printf("n = %d\n\n", n);
swap(&m, &n); //passing address of m and n to the swap function
printf("After Swapping:\n\n");
printf("m = %d\n", m);
printf("n = %d", n);
return 0;
}
/*
pointer 'a' and 'b' holds and
points to the address of 'm' and 'n'
*/
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
OUTPUT:
m = 10
n = 20
After Swapping:
19
m = 20
n = 10
Functions returning Pointer variables
A function can also return a pointer to the calling function. In this case you
must be careful, because local variables of function doesn't live outside the
function.
They have scope only inside the function. Hence if you return a pointer
connected to a local variable, that pointer will be pointing to nothing when the
function ends.
#include <stdio.h>
int* larger(int*, int*);
void main()
{
int a = 15;
int b = 92;
int *p;
p = larger(&a, &b);
printf("%d is larger",*p);
}
int* larger(int *x, int *y)
{
if(*x > *y)
return x;
else
20
return y;
}
OUTPUT:
92 is larger
Pointer to functions
It is possible to declare a pointer pointing to a function which can then be used
as an argument in another function. A pointer to a function is declared as
follows,
type (*pointer-name)(parameter);
Here is an example :
int (*sum)(); //legal declaration of pointer to function
int *sum(); //This is not a declaration of pointer to function
A function pointer can point to a specific function when it is assigned the
name of that function.
int sum(int, int);
int (*s)(int, int);
s = sum;
Here s is a pointer to a function sum. Now sum can be called using function
pointer s along with providing the required argument values.
s (10, 20);
21
Example of Pointer to Function
#include <stdio.h>
int sum(int x, int y)
{
return x+y;
}
int main( )
{
int (*fp)(int, int);
fp = sum;
int s = fp(10, 15);
printf("Sum is %d", s);
return 0;
}
OUTPUT:
25
22
Introduction to Structure
Structure is a user-defined datatype in C language which allows us to combine data
of different types together. Structure helps to construct a complex data type which
is more meaningful.
It is somewhat similar to an Array, but an array holds data of similar type only. But
structure on the other hand, can store data of any type, which is practical more useful.
For example: If I have to write a program to store Student information, which will
have Student's name, age, branch, permanent address, father's name etc, which
included string values, integer values etc, how can I use arrays for this problem, I
will require something which can hold data of different types together.
In structure, data is stored in form of records.
Defining a structure
struct keyword is used to define a structure. struct defines a new data type which is
a collection of primary and derived datatypes.
Syntax:
struct [structure_tag]
//member variable 1
//member variable 2
//member variable 3
...
23
}[structure_variables];
As you can see in the syntax above, we start with the struct keyword, then it's
optional to provide your structure a name, we suggest you to give it a name, then
inside the curly braces, we have to mention all the member variables, which are
nothing but normal C language variables of different types like int, float, array etc.
After the closing curly brace, we can specify one or more structure variables, again
this is optional.
Note: The closing curly brace in the structure type declaration must be followed by
a semicolon(;).
Example of Structure
struct Student
char name[25];
int age;
char branch[10];
// F for female and M for male
char gender;
};
Here struct Student declares a structure to hold the details of a student which consists
of 4 data fields, namely name, age, branch and gender. These fields are
called structure elements or members.
24
Each member can have different datatype, like in this case, name is an array
of char type and age is of int type etc. Student is the name of the structure and is
called as the structure tag.
Declaring Structure Variables
It is possible to declare variables of a structure, either along with structure definition
or after the structure is defined. Structure variable declaration is similar to the
declaration of any normal variable of any other datatype. Structure variables can be
declared in following two ways:
1) Declaring Structure variables separately
struct Student
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
};
struct Student S1, S2; //declaring variables of struct Student
25
2) Declaring Structure variables with structure definition
struct Student
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
}S1, S2;
Here S1 and S2 are variables of structure Student. However this approach is not
much recommended.
Accessing Structure Members
Structure members can be accessed and assigned values in a number of ways.
Structure members have no meaning individually without the structure. In order to
assign a value to any structure member, the member name must be linked with
the structure variable using a dot . operator also called period or member
access operator.
For example:
#include<stdio.h>
#include<string.h>
26
struct Student
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
};
int main()
struct Student s1;
/*
s1 is a variable of Student type and
age is a member of Student
*/
s1.age = 18;
/*
using string function to add name
27
*/
strcpy(s1.name, "Viraaj");
/*
displaying the stored values
*/
printf("Name of Student 1: %s\n", s1.name);
printf("Age of Student 1: %d\n", s1.age);
return 0;
OUTPUT:
Name of Student 1: Viraaj
Age of Student 1: 18
We can also use scanf() to give values to structure members through terminal.
scanf(" %s ", s1.name);
scanf(" %d ", &s1.age);
Structure Initialization
Like a variable of any other datatype, structure variable can also be initialized at
compile time.
struct Patient
{
28
float height;
int weight;
int age;
};
struct Patient p1 = { 180.75 , 73, 23 }; //initialization
or,
struct Patient p1;
p1.height = 180.75; //initialization of each member separately
p1.weight = 73;
p1.age = 23;
Array of Structure
We can also declare an array of structure variables. in which each element of the
array will represent a structure variable. Example : struct employee emp[5];
The below program defines an array emp of size 5. Each element of the array emp is
of type Employee.
#include<stdio.h>
struct Employee
char ename[10];
int sal;
29
};
struct Employee emp[5];
int i, j;
void ask()
for(i = 0; i < 3; i++)
printf("\nEnter %dst Employee record:\n", i+1);
printf("\nEmployee name:\t");
scanf("%s", emp[i].ename);
printf("\nEnter Salary:\t");
scanf("%d", &emp[i].sal);
printf("\nDisplaying Employee record:\n");
for(i = 0; i < 3; i++)
printf("\nEmployee name is %s", emp[i].ename);
printf("\nSlary is %d", emp[i].sal);
30
}
void main()
ask();
Nested Structures
Nesting of structures, is also permitted in C language. Nested structures means, that
one structure has another stucture as member variable.
Example:
struct Student
char[30] name;
int age;
/* here Address is a structure */
struct Address
char[50] locality;
char[50] city;
31
int pincode;
}addr;
};
Structure as Function Arguments
We can pass a structure as a function argument just like we pass any other variable
or an array as a function argument.
Example:
#include<stdio.h>
struct Student
char name[10];
int roll;
};
void show(struct Student st);
void main()
struct Student std;
32
printf("\nEnter Student record:\n");
printf("\nStudent name:\t");
scanf("%s", std.name);
printf("\nEnter Student rollno.:\t");
scanf("%d", &std.roll);
show(std);
void show(struct Student st)
printf("\nstudent name is %s", st.name);
printf("\nroll is %d", st.roll);
Unions in C Language
Unions are conceptually similar to structures. The syntax to declare/define a union
is also similar to that of a structure.
The only differences is in terms of storage. In structure each member has its own
storage location, whereas all members of union uses a single shared memory
location which is equal to the size of its largest data member.
33
This implies that
although a union may contain many members of different types, it cannot handle all
the members at the same time. A union is declared using the union keyword.
union item
int m;
float x;
char c;
}It1;
This declares a variable It1 of type union item. This union contains three members
each with a different data type. However only one of them can be used at a time.
This is due to the fact that only one location is allocated for all the union variables,
irrespective of their size.
The compiler allocates the storage that is large enough to hold the largest variable
type in the union.
34
In the union declared above the member x requires 4 bytes which is largest amongst
the members for a 16-bit machine. Other members of union will share the same
memory address.
Accessing a Union Member
Syntax for accessing any union member is similar to accessing structure members,
union test
int a;
float b;
char c;
}t;
t.a; //to access members of union t
t.b;
t.c;
Example
#include <stdio.h>
union im
int a;
35
float b;
char ch;
};
int main( )
union item it;
it.a = 12;
it.b = 20.2;
it.ch = 'z';
printf("%d\n", it.a);
printf("%f\n", it.b);
printf("%c\n", it.ch);
return 0;
OUTPUT:
-26426
20.1999
36
z
As you can see here, the values of a and b get corrupted and only variable c prints
the expected result. This is because in union, the memory is shared among different
data types. Hence, the only member whose value is currently stored will have the
memory.
In the above example, value of the variable c was stored at last, hence the value of
other variables is lost.
37