SlideShare a Scribd company logo
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

More Related Content

What's hot

C programming function
C  programming functionC  programming function
C programming function
argusacademy
 
C and C++ functions
C and C++ functionsC and C++ functions
C and C++ functions
kavitha muneeshwaran
 
Function in c program
Function in c programFunction in c program
Function in c program
umesh patil
 
Functions
FunctionsFunctions
Functions
Pragnavi Erva
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
Sampath Kumar
 
Prsentation on functions
Prsentation on functionsPrsentation on functions
Prsentation on functionsAlisha Korpal
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
v_jk
 
Functions
Functions Functions
Functions
Dr.Subha Krishna
 
Types of function call
Types of function callTypes of function call
Types of function call
ArijitDhali
 
Presentation on function
Presentation on functionPresentation on function
Presentation on function
Abu Zaman
 
Programming Fundamentals Decisions
Programming Fundamentals  Decisions Programming Fundamentals  Decisions
Programming Fundamentals Decisions
imtiazalijoono
 
C function presentation
C function presentationC function presentation
C function presentation
Touhidul Shawan
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++
Sachin Yadav
 
Function lecture
Function lectureFunction lecture
Function lecture
DIT University, Dehradun
 
Unit 4 (1)
Unit 4 (1)Unit 4 (1)
Unit 4 (1)
psaravanan1985
 
functions of C++
functions of C++functions of C++
functions of C++
tarandeep_kaur
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
NUST Stuff
 

What's hot (20)

C programming function
C  programming functionC  programming function
C programming function
 
C and C++ functions
C and C++ functionsC and C++ functions
C and C++ functions
 
Function in c program
Function in c programFunction in c program
Function in c program
 
Functions
FunctionsFunctions
Functions
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
 
Prsentation on functions
Prsentation on functionsPrsentation on functions
Prsentation on functions
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 
Functions
Functions Functions
Functions
 
Types of function call
Types of function callTypes of function call
Types of function call
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Presentation on function
Presentation on functionPresentation on function
Presentation on function
 
Parameter passing to_functions_in_c
Parameter passing to_functions_in_cParameter passing to_functions_in_c
Parameter passing to_functions_in_c
 
Programming Fundamentals Decisions
Programming Fundamentals  Decisions Programming Fundamentals  Decisions
Programming Fundamentals Decisions
 
C function presentation
C function presentationC function presentation
C function presentation
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++
 
Function
FunctionFunction
Function
 
Function lecture
Function lectureFunction lecture
Function lecture
 
Unit 4 (1)
Unit 4 (1)Unit 4 (1)
Unit 4 (1)
 
functions of C++
functions of C++functions of C++
functions of C++
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
 

Similar to Functions

Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and types
imtiazalijoono
 
unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
JVenkateshGoud
 
unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx
Venkatesh Goud
 
Function
FunctionFunction
Function
mshoaib15
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
Koteswari Kasireddy
 
Lecture6
Lecture6Lecture6
Functions struct&union
Functions struct&unionFunctions struct&union
Functions struct&union
UMA PARAMESWARI
 
CHAPTER 6
CHAPTER 6CHAPTER 6
CHAPTER 6
mohd_mizan
 
Functions
FunctionsFunctions
Unit iii
Unit iiiUnit iii
Unit iii
SHIKHA GAUTAM
 
3. functions modules_programs (1)
3. functions modules_programs (1)3. functions modules_programs (1)
3. functions modules_programs (1)
SaraswathiTAsstProfI
 
Fundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptxFundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptx
Chandrakant Divate
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdf
TeshaleSiyum
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdf
TeshaleSiyum
 
Function
Function Function
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
LPU
 
Funtions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the topsFuntions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the tops
sameermhr345
 
Functions in c
Functions in cFunctions in c
Functions in c
KavithaMuralidharan2
 
Array Cont
Array ContArray Cont
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptxUnit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
vekariyakashyap
 

Similar to Functions (20)

Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and types
 
unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
 
unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx
 
Function
FunctionFunction
Function
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
 
Lecture6
Lecture6Lecture6
Lecture6
 
Functions struct&union
Functions struct&unionFunctions struct&union
Functions struct&union
 
CHAPTER 6
CHAPTER 6CHAPTER 6
CHAPTER 6
 
Functions
FunctionsFunctions
Functions
 
Unit iii
Unit iiiUnit iii
Unit iii
 
3. functions modules_programs (1)
3. functions modules_programs (1)3. functions modules_programs (1)
3. functions modules_programs (1)
 
Fundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptxFundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptx
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdf
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdf
 
Function
Function Function
Function
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
Funtions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the topsFuntions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the tops
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Array Cont
Array ContArray Cont
Array Cont
 
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptxUnit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
 

Recently uploaded

Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 

Recently uploaded (20)

Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 

Functions

  • 1. Khanal Pralhad Navodit College, Samakhusi, Kathmandu Pkhanal95.pk@gmail.com
  • 2. 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.
  • 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 of Function • Function Declaration (Function Prototype) • Function Definition • Function Call
  • 5. 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.
  • 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);
  • 7.
  • 8. 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.
  • 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 }
  • 10.
  • 11. The first line of function definition is function declaration and followed by function body.
  • 12.
  • 13. 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.
  • 14. Syntax: Function Call • Variable= function_name(arg1,arg2,………,argN); • Function_name(arg1,arg2,…,argN);
  • 15.
  • 16.
  • 17. #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 }
  • 18. #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; }
  • 19. #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; }
  • 20. 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).
  • 21. 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.
  • 22. 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.
  • 23.
  • 24.
  • 25. #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; }
  • 26. #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; }
  • 27.
  • 28. 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++) {
  • 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; }
  • 30.
  • 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> 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; }
  • 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(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 }