Khanal Pralhad
Navodit College, Samakhusi, Kathmandu
Pkhanal95.pk@gmail.com
Functions
• When we write a program to solve a larger problem, we divide that larger problem
into smaller sub problems and are solved individually to make the program easier.
• In C, this concept is implemented using functions. Functions are used to divide a
larger program into smaller subprograms such that the program becomes
easy to understand and easy to implement.
• Function is a subpart of a program used to perform a specific task and is
executed individually.
• Is a self-contained block of code that performs a particular task.
• Every C program has at least one function, which is main(), and all the most trivial
programs can define additional functions.
Advantage of Function
• It increases code reusability.
• Program development will be faster.
• Program debugging is faster.
• Can be developed in shorter period of time.
• Many programmers can be involved and perform same task at the same or
different period of time.
Function Aspects/Components of Function
• Function Declaration (Function Prototype)
• Function Definition
• Function Call
Function Declaration(Prototype)
• The function declaration tells the compiler about function name, the
data type of the return value and parameters.
• The function declaration is also called a function prototype.
• The function declaration is performed before the main function or
inside the main function or any other function.
Syntax: function Prototype(declaration)
• return_type function_name( parameter list );
• Return_value function_name(args1,args2,…..,argsN);
• Example:
• Int sum(int , int);
• Float sum(float, float);
• Int max(int,int);
Function definition
• The function definition provides the actual code of that function. The
function definition is also known as the body of the function.
• The actual task of the function is implemented in the function definition.
• That means the actual instructions to be performed by a function are
written in function definition. The actual instructions of a function are
written inside the braces "{ }".
• The function definition is performed before the main function or after the
main function.
• The first line of function definition is function declaration and followed
by function body.
Syntax: Function Definition
• returnType functionName(parametersList)
{
Actual code...
}
• Data_type function_name(data_type args1, data_type args2,…,
data_type argsN)
{
// body of function
}
The first line of function definition is function declaration and followed by function body.
Call the function/Function Call
• The function call tells the compiler when to execute the function
definition.
• When a function call is executed, the execution control jumps to the
function definition where the actual code gets executed and returns
to the same functions call once the execution completes.
• The function call is performed inside the main function or any other
function or inside the function itself.
• 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.
Syntax: Function Call
• Variable= function_name(arg1,arg2,………,argN);
• Function_name(arg1,arg2,…,argN);
#include <stdio.h>
int addNumbers(int a, int b); // function prototype
int main()
{
int n1,n2,sum;
printf("Enters two numbers: ");
scanf("%d %d",&n1,&n2);
sum = addNumbers(n1, n2); // function call
printf("sum = %d",sum);
return 0;
}
int addNumbers(int a, int b) // function definition
{
int result;
result = a+b;
return result; // return statement
}
#include <stdio.h>
/* function declaration */
int max(int num1, int num2);
int main () {
int a = 100;
int b = 200;
int ret;
/* calling a function to get max value */
ret = max(a, b);
printf( "Max value is : %dn", ret );
return 0;
}
/* function returning the max between two numbers */
int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("nGoing to calculate the sum of two numbers:");
printf("nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("nThe sum is : %d",result);
}
int sum(int a, int b)
{
return a+b;
}
Assignments
• WAP to print the smallest numbers among three numbers.
• WAP to check whether the entered number is odd or even.
• +ve,-ve or zero, using function.
• Sum of N numbers.
• Multiplication table.
• Reverse of a number.
• 1 1 2 3 5 8… upto nth term(Fibonacci).
Recursion
• Recursion is the process of repeating items in a self-similar way.
• If a program allows you to call a function inside the same function, then it is
called a recursive call of the function.
• Recursion is a programming technique that allows the programmer to express
operations in terms of themselves.
• In C, this takes the form of a function that calls itself. A useful way to think of
recursive functions is to imagine them as a process being performed where one
of the instructions is to "repeat the process".
• This makes it sound very similar to a loop because it repeats the same code, and
in some ways it is similar to looping. On the other hand, recursion makes it easier
to express ideas in which the result of the recursive call is necessary to complete
the task. Of course, it must be possible for the "process" to sometimes be
completed without the recursive call.
One simple example is the idea of building a wall that is ten feet high; if I want to
build a ten foot high wall, then I will first build a 9 foot high wall, and then add an
extra foot of bricks. Conceptually, this is like saying the "build wall" function takes
a height and if that height is greater than one, first calls itself to build a lower wall,
and then adds one a foot of bricks.
#include <stdio.h>
int fibonacci(int i) {
if(i == 0) {
return 0;
}
if(i == 1) {
return 1;
}
return fibonacci(i-1) + fibonacci(i-2);
}
int main() {
int i;
for (i = 0; i < 10; i++) {
printf("%dtn", fibonacci(i));
}
return 0;
}
#include <stdio.h>
int sum(int n);
int main() {
int number, result;
printf("Enter a positive integer: ");
scanf("%d", &number);
result = sum(number);
printf("sum = %d", result);
return 0;
}
int sum(int n) {
if (n != 0)
// sum() function calls itself
return n + sum(n-1);
else
return n;
}
int rows, columns;
int main() {
int matrix1[10][10], matrix2[10][10];
int matrix3[10][10], i, j;
printf(“Enter the no of rows and columns(<=10):”);
scanf(“%d%d”, &rows, &columns);
if (rows > 10 || columns > 10) {
printf(“No of rows/columns is greater than 10n”);
return 0;}
printf(“Enter the input for first matrix:”);
for (i = 0; i < rows; i++) {
for (j = 0; j < columns; j++) {
scanf(“%d”, &matrix1[i][j]);}}
printf(“Enter the input for second matrix:”);
for (i = 0; i < rows; i++) {
for (j = 0; j < columns; j++) {
scanf(“%d”, &matrix2[i][j]);}}
matrixAddition(matrix1, matrix2, matrix3);
printf(“nResult of Matrix Addition:n”);
for (i = 0; i < rows; i++) {
for (j = 0; j < columns; j++) {
printf(“%5d”, matrix3[i][j]);}
printf(“n”);}
getch();
return 0;
}
void matrixAddition(int mat1[][10], int mat2[][10], int mat3[][10]) {
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < columns; j++) {
mat3[i][j] = mat1[i][j] + mat2[i][j];
}
}
return;
}
System Defined/Library Function
• The system defined functions are also called as Library Functions or
Standard Functions or Pre-Defined Functions. The implementation of
system defined functions is already defined by the system.
• In C, all the system defined functions are defined inside the header files like
stdio.h, conio.h, math.h, string.h etc.,
• For example, the funtions printf() and scanf() are defined in the header file
called stdio.h.
• Whenever we use system defined functions in the program, we must
include the respective header file using #include statement.
• For example, if we use a system defined function sqrt() in the program, we
must include the header file called math.h because the function sqrt() is
defined in math.h.
#include <stdio.h>
#include <math.h>
int main()
{
float num, root;
printf("Enter a number: ");
scanf("%f", &num);
// Computes the square root of num
and stores in root.
root = sqrt(num);
printf("Square root of %.2f = %.2f",
num, root);
return 0;
}
User Defined Function
• The function that is implemented by user is called as user defined
function.
• For example, the function main is implemented by user so it is called
as user defined function.
• In C every user defined function must be declared and implemented.
Whenever we make function call the function definition gets
executed.
• For example, consider the following program in which we create a
fucntion called addition with two paramenters and a return value.
#include <stdio.h>
int addNumbers(int a, int b); // function prototype
int main()
{
int n1,n2,sum;
printf("Enters two numbers: ");
scanf("%d %d",&n1,&n2);
sum = addNumbers(n1, n2); // function call
printf("sum = %d",sum);
return 0;
}
int addNumbers(int a, int b) // function definition
{
int result;
result = a+b;
return result; // return statement
}
Functions
Functions

Functions

  • 1.
    Khanal Pralhad Navodit College,Samakhusi, Kathmandu Pkhanal95.pk@gmail.com
  • 2.
    Functions • When wewrite a program to solve a larger problem, we divide that larger problem into smaller sub problems and are solved individually to make the program easier. • In C, this concept is implemented using functions. Functions are used to divide a larger program into smaller subprograms such that the program becomes easy to understand and easy to implement. • Function is a subpart of a program used to perform a specific task and is executed individually. • Is a self-contained block of code that performs a particular task. • Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions.
  • 3.
    Advantage of Function •It increases code reusability. • Program development will be faster. • Program debugging is faster. • Can be developed in shorter period of time. • Many programmers can be involved and perform same task at the same or different period of time.
  • 4.
    Function Aspects/Components ofFunction • Function Declaration (Function Prototype) • Function Definition • Function Call
  • 5.
    Function Declaration(Prototype) • Thefunction declaration tells the compiler about function name, the data type of the return value and parameters. • The function declaration is also called a function prototype. • The function declaration is performed before the main function or inside the main function or any other function.
  • 6.
    Syntax: function Prototype(declaration) •return_type function_name( parameter list ); • Return_value function_name(args1,args2,…..,argsN); • Example: • Int sum(int , int); • Float sum(float, float); • Int max(int,int);
  • 8.
    Function definition • Thefunction definition provides the actual code of that function. The function definition is also known as the body of the function. • The actual task of the function is implemented in the function definition. • That means the actual instructions to be performed by a function are written in function definition. The actual instructions of a function are written inside the braces "{ }". • The function definition is performed before the main function or after the main function. • The first line of function definition is function declaration and followed by function body.
  • 9.
    Syntax: Function Definition •returnType functionName(parametersList) { Actual code... } • Data_type function_name(data_type args1, data_type args2,…, data_type argsN) { // body of function }
  • 11.
    The first lineof function definition is function declaration and followed by function body.
  • 13.
    Call the function/FunctionCall • The function call tells the compiler when to execute the function definition. • When a function call is executed, the execution control jumps to the function definition where the actual code gets executed and returns to the same functions call once the execution completes. • The function call is performed inside the main function or any other function or inside the function itself. • 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.
  • 14.
    Syntax: Function Call •Variable= function_name(arg1,arg2,………,argN); • Function_name(arg1,arg2,…,argN);
  • 17.
    #include <stdio.h> int addNumbers(inta, int b); // function prototype int main() { int n1,n2,sum; printf("Enters two numbers: "); scanf("%d %d",&n1,&n2); sum = addNumbers(n1, n2); // function call printf("sum = %d",sum); return 0; } int addNumbers(int a, int b) // function definition { int result; result = a+b; return result; // return statement }
  • 18.
    #include <stdio.h> /* functiondeclaration */ int max(int num1, int num2); int main () { int a = 100; int b = 200; int ret; /* calling a function to get max value */ ret = max(a, b); printf( "Max value is : %dn", ret ); return 0; } /* function returning the max between two numbers */ int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
  • 19.
    #include<stdio.h> int sum(int, int); voidmain() { int a,b,result; printf("nGoing to calculate the sum of two numbers:"); printf("nEnter two numbers:"); scanf("%d %d",&a,&b); result = sum(a,b); printf("nThe sum is : %d",result); } int sum(int a, int b) { return a+b; }
  • 20.
    Assignments • WAP toprint the smallest numbers among three numbers. • WAP to check whether the entered number is odd or even. • +ve,-ve or zero, using function. • Sum of N numbers. • Multiplication table. • Reverse of a number. • 1 1 2 3 5 8… upto nth term(Fibonacci).
  • 21.
    Recursion • Recursion isthe process of repeating items in a self-similar way. • If a program allows you to call a function inside the same function, then it is called a recursive call of the function. • Recursion is a programming technique that allows the programmer to express operations in terms of themselves. • In C, this takes the form of a function that calls itself. A useful way to think of recursive functions is to imagine them as a process being performed where one of the instructions is to "repeat the process". • This makes it sound very similar to a loop because it repeats the same code, and in some ways it is similar to looping. On the other hand, recursion makes it easier to express ideas in which the result of the recursive call is necessary to complete the task. Of course, it must be possible for the "process" to sometimes be completed without the recursive call.
  • 22.
    One simple exampleis the idea of building a wall that is ten feet high; if I want to build a ten foot high wall, then I will first build a 9 foot high wall, and then add an extra foot of bricks. Conceptually, this is like saying the "build wall" function takes a height and if that height is greater than one, first calls itself to build a lower wall, and then adds one a foot of bricks.
  • 25.
    #include <stdio.h> int fibonacci(inti) { if(i == 0) { return 0; } if(i == 1) { return 1; } return fibonacci(i-1) + fibonacci(i-2); } int main() { int i; for (i = 0; i < 10; i++) { printf("%dtn", fibonacci(i)); } return 0; }
  • 26.
    #include <stdio.h> int sum(intn); int main() { int number, result; printf("Enter a positive integer: "); scanf("%d", &number); result = sum(number); printf("sum = %d", result); return 0; } int sum(int n) { if (n != 0) // sum() function calls itself return n + sum(n-1); else return n; }
  • 28.
    int rows, columns; intmain() { int matrix1[10][10], matrix2[10][10]; int matrix3[10][10], i, j; printf(“Enter the no of rows and columns(<=10):”); scanf(“%d%d”, &rows, &columns); if (rows > 10 || columns > 10) { printf(“No of rows/columns is greater than 10n”); return 0;} printf(“Enter the input for first matrix:”); for (i = 0; i < rows; i++) { for (j = 0; j < columns; j++) { scanf(“%d”, &matrix1[i][j]);}} printf(“Enter the input for second matrix:”); for (i = 0; i < rows; i++) { for (j = 0; j < columns; j++) { scanf(“%d”, &matrix2[i][j]);}} matrixAddition(matrix1, matrix2, matrix3); printf(“nResult of Matrix Addition:n”); for (i = 0; i < rows; i++) {
  • 29.
    for (j =0; j < columns; j++) { printf(“%5d”, matrix3[i][j]);} printf(“n”);} getch(); return 0; } void matrixAddition(int mat1[][10], int mat2[][10], int mat3[][10]) { int i, j; for (i = 0; i < rows; i++) { for (j = 0; j < columns; j++) { mat3[i][j] = mat1[i][j] + mat2[i][j]; } } return; }
  • 31.
    System Defined/Library Function •The system defined functions are also called as Library Functions or Standard Functions or Pre-Defined Functions. The implementation of system defined functions is already defined by the system. • In C, all the system defined functions are defined inside the header files like stdio.h, conio.h, math.h, string.h etc., • For example, the funtions printf() and scanf() are defined in the header file called stdio.h. • Whenever we use system defined functions in the program, we must include the respective header file using #include statement. • For example, if we use a system defined function sqrt() in the program, we must include the header file called math.h because the function sqrt() is defined in math.h.
  • 32.
    #include <stdio.h> #include <math.h> intmain() { float num, root; printf("Enter a number: "); scanf("%f", &num); // Computes the square root of num and stores in root. root = sqrt(num); printf("Square root of %.2f = %.2f", num, root); return 0; }
  • 33.
    User Defined Function •The function that is implemented by user is called as user defined function. • For example, the function main is implemented by user so it is called as user defined function. • In C every user defined function must be declared and implemented. Whenever we make function call the function definition gets executed. • For example, consider the following program in which we create a fucntion called addition with two paramenters and a return value.
  • 34.
    #include <stdio.h> int addNumbers(inta, int b); // function prototype int main() { int n1,n2,sum; printf("Enters two numbers: "); scanf("%d %d",&n1,&n2); sum = addNumbers(n1, n2); // function call printf("sum = %d",sum); return 0; } int addNumbers(int a, int b) // function definition { int result; result = a+b; return result; // return statement }