SlideShare a Scribd company logo
Unit 7.1
Function
Introduction
• A function is a block of code that performs a specific task.
• A function is a set of statements that take inputs, do some
specific computation and produces output.
• The idea is to put some commonly or repeatedly done task
together and make a function, so that instead of writing the
same code again and again for different inputs, we can call the
function.
• Function helps in dividing complex problem into small
components makes program easy to understand and use.
Types of function
• Depending on whether a function is defined by the user or
already included in C compilers, there are two types of
functions in C programming
• There are two types of function in C programming:
– Standard library functions
– User defined functions
Standard library functions
• The standard library functions are built-in functions in C
programming to handle tasks such as mathematical
computations, I/O processing, string handling etc.
• These functions are defined in the header file. When you
include the header file, these functions are available for use.
For 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 function
• Functions created by the user are called user-defined
functions.
• User defined function has basically following characteristics
– A function is named with unique name
– A function performs a specific task
– A function is independent
– A function may receive values from the calling program
(caller)
– A function may return a value to the calling program
Example
#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
}
Function Components
• Function prototype
• A function prototype is simply the declaration of a function
that specifies function's name, parameters and return type. It
doesn't contain function body.
• A function prototype gives information to the compiler that
the function may later be used in the program.
• Syntax of function prototype
• returnType functionName(type1 argument1, type2
argument2,...);
• For example
int addNumbers(int a, int b);
• It is the function prototype which provides following
information to the compiler:
• name of the function is addNumbers()
• return type of the function is int
• two arguments of type int are passed to the function
• The function prototype is not needed if the user-defined
function is defined before the main() function.
Function definition
• Function definition contains the block of code to perform a
specific task
• Syntax of function definition
returnType functionName(type1 arg1, type2 arg2, ...)
{
//body of the function
}
• When a function is called, the control of the program is
transferred to the function definition. And, the compiler starts
executing the codes inside the body of a function.
Calling a function
• Control of the program is transferred to the user-defined
function by calling it.
• Syntax of function call
functionName(argument1, argument2, ...);
• For example
void main()
{
addNumbers(n1,n2);
}
Passing arguments to a function
• In programming, argument refers to the variable passed to
the function.
• In the above example, two variables n1 and n2 are passed
during function call.
• The parameters a and b accepts the passed arguments in the
function definition. These arguments are called formal
parameters of the function.
• The type of arguments passed to a function and the formal
parameters must match, otherwise the compiler throws error.
• If n1 is of char type, a also should be of char type. If n2 is of
float type, variable b also should be of float type.
• A function can also be called without passing an argument.
Return Statement
• The return statement terminates the execution of a function
and returns a value to the calling function.
• The program control is transferred to the calling function after
return statement.
• In the above example, the value of variable result is returned
to the variable sum in the main() function.
Syntax of return statement
• return (expression);
• For example,
– return a;
– return (a+b);
• The type of value returned from the function and the return
type specified in function prototype and function definition
must match.
Types of User-defined Functions in C
Programming
• No arguments passed and no return value
• No arguments passed but a return value
• Argument passed but no return value
• Argument passed and a return value
C Recursion
• A function that calls itself is known as a recursive function.
And, this technique is known as recursion.
How recursion works?
void recurse()
{
... .. ...
recurse();
... .. ...
}
int main()
{
... .. ...
recurse();
... .. ...
}
• The recursion continues until some condition is met to
prevent it.
• To prevent infinite recursion, if...else statement (or similar
approach) can be used where one branch makes the recursive
call and other doesn't.
Sum of Natural Numbers Using
Recursion
#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 num)
{
if (num!=0)
return num + sum(num-1); // sum() function calls itself
else
return num;
}
• Initially, the sum() is called from the main() function
with number passed as an argument.
• Suppose, the value of num is 3 initially. During next function
call, 2 is passed to the sum() function. This process continues
until num is equal to 0.
• When num is equal to 0, the if condition fails and the else part
is executed returning the sum of integers to
the main() function.
Advantages and Disadvantages of
Recursion
• Recursion makes program elegant and more
readable. However, if performance is vital
then, use loops instead as recursion is usually much slower.
• Note that, every recursion can be modeled into a loop.
• Recursion Vs Iteration? Need performance, use loops,
however, code might look ugly and hard to read sometimes.
Need more elegant and readable code, use recursion,
however, you are sacrificing some performance.
How to pass arrays to a function
• Passing One-dimensional Array to a Function
• Passing a single element of an array to a function is similar
to passing variable to a function.
#include <stdio.h>
void display(int age)
{
printf("%d", age);
}
void main()
{
int a[] = {2, 3, 4};
display(a[2]); //Passing array element a[2]
}
Passing an entire array to a function
#include <stdio.h>
float average(int []);
void main()
{
float avg;
int age[] = {23, 55, 22, 5, 40, 18};
avg = average(age); // Only name of an array is passed as
an argument
printf("Average age = %.2f", avg);
}
float average(int age[])
{
int i,sum=0;
float avg;
for (i = 0; i < 6; ++i) {
sum += age[i];
}
avg = (float)sum / 6;
return avg;
}
Passing Multi-dimensional Arrays to Function
• To pass multidimensional arrays to a function, only the name
of the array is passed (similar to one dimensional array).
#include <stdio.h>
void displayNumbers(int num[2][2]);
void 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); // passing multi-dimensional array to a
function
}
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("%dn", num[i][j]);
}

More Related Content

Similar to Funtions of c programming. the functions of c helps to clarify all the tops

Similar to Funtions of c programming. the functions of c helps to clarify all the tops (20)

unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
 
arrays.ppt
arrays.pptarrays.ppt
arrays.ppt
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptx
 
4th unit full
4th unit full4th unit full
4th unit full
 
Functions struct&union
Functions struct&unionFunctions struct&union
Functions struct&union
 
unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx
 
Lecture6
Lecture6Lecture6
Lecture6
 
358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2
 
Functions
Functions Functions
Functions
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.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
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdf
 
Functions in C.pptx
Functions in C.pptxFunctions in C.pptx
Functions in C.pptx
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
 
5. Functions in C.pdf
5. Functions in C.pdf5. Functions in C.pdf
5. Functions in C.pdf
 
Functions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptxFunctions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptx
 
Functions in C.pptx
Functions in C.pptxFunctions in C.pptx
Functions in C.pptx
 
Function
Function Function
Function
 

Recently uploaded

Studiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting softwareStudiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting softwareinfo611746
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesKrzysztofKkol1
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEJelle | Nordend
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar
 
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product UpdatesGraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product UpdatesNeo4j
 
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with StrimziStrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzisteffenkarlsson2
 
10 Essential Software Testing Tools You Need to Know About.pdf
10 Essential Software Testing Tools You Need to Know About.pdf10 Essential Software Testing Tools You Need to Know About.pdf
10 Essential Software Testing Tools You Need to Know About.pdfkalichargn70th171
 
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdfImplementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdfVictor Lopez
 
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...rajkumar669520
 
Breaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdfBreaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdfMeon Technology
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Anthony Dahanne
 
Workforce Efficiency with Employee Time Tracking Software.pdf
Workforce Efficiency with Employee Time Tracking Software.pdfWorkforce Efficiency with Employee Time Tracking Software.pdf
Workforce Efficiency with Employee Time Tracking Software.pdfDeskTrack
 
A Guideline to Zendesk to Re:amaze Data Migration
A Guideline to Zendesk to Re:amaze Data MigrationA Guideline to Zendesk to Re:amaze Data Migration
A Guideline to Zendesk to Re:amaze Data MigrationHelp Desk Migration
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...Alluxio, Inc.
 
KLARNA - Language Models and Knowledge Graphs: A Systems Approach
KLARNA -  Language Models and Knowledge Graphs: A Systems ApproachKLARNA -  Language Models and Knowledge Graphs: A Systems Approach
KLARNA - Language Models and Knowledge Graphs: A Systems ApproachNeo4j
 
Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024Soroosh Khodami
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowPeter Caitens
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTier1 app
 
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfmbmh111980
 

Recently uploaded (20)

Studiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting softwareStudiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting software
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product UpdatesGraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
 
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with StrimziStrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi
 
10 Essential Software Testing Tools You Need to Know About.pdf
10 Essential Software Testing Tools You Need to Know About.pdf10 Essential Software Testing Tools You Need to Know About.pdf
10 Essential Software Testing Tools You Need to Know About.pdf
 
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdfImplementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdf
 
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
 
Breaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdfBreaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdf
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Workforce Efficiency with Employee Time Tracking Software.pdf
Workforce Efficiency with Employee Time Tracking Software.pdfWorkforce Efficiency with Employee Time Tracking Software.pdf
Workforce Efficiency with Employee Time Tracking Software.pdf
 
A Guideline to Zendesk to Re:amaze Data Migration
A Guideline to Zendesk to Re:amaze Data MigrationA Guideline to Zendesk to Re:amaze Data Migration
A Guideline to Zendesk to Re:amaze Data Migration
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
 
KLARNA - Language Models and Knowledge Graphs: A Systems Approach
KLARNA -  Language Models and Knowledge Graphs: A Systems ApproachKLARNA -  Language Models and Knowledge Graphs: A Systems Approach
KLARNA - Language Models and Knowledge Graphs: A Systems Approach
 
Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
5 Reasons Driving Warehouse Management Systems Demand
5 Reasons Driving Warehouse Management Systems Demand5 Reasons Driving Warehouse Management Systems Demand
5 Reasons Driving Warehouse Management Systems Demand
 
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
 

Funtions of c programming. the functions of c helps to clarify all the tops

  • 2. Introduction • A function is a block of code that performs a specific task. • A function is a set of statements that take inputs, do some specific computation and produces output. • The idea is to put some commonly or repeatedly done task together and make a function, so that instead of writing the same code again and again for different inputs, we can call the function. • Function helps in dividing complex problem into small components makes program easy to understand and use.
  • 3. Types of function • Depending on whether a function is defined by the user or already included in C compilers, there are two types of functions in C programming • There are two types of function in C programming: – Standard library functions – User defined functions
  • 4. Standard library functions • The standard library functions are built-in functions in C programming to handle tasks such as mathematical computations, I/O processing, string handling etc. • These functions are defined in the header file. When you include the header file, these functions are available for use. For 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.
  • 5. User-defined function • Functions created by the user are called user-defined functions. • User defined function has basically following characteristics – A function is named with unique name – A function performs a specific task – A function is independent – A function may receive values from the calling program (caller) – A function may return a value to the calling program
  • 6. Example #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; }
  • 7. int addNumbers(int a,int b) // function definition { int result; result = a+b; return result; // return statement }
  • 8. Function Components • Function prototype • A function prototype is simply the declaration of a function that specifies function's name, parameters and return type. It doesn't contain function body. • A function prototype gives information to the compiler that the function may later be used in the program. • Syntax of function prototype • returnType functionName(type1 argument1, type2 argument2,...);
  • 9. • For example int addNumbers(int a, int b); • It is the function prototype which provides following information to the compiler: • name of the function is addNumbers() • return type of the function is int • two arguments of type int are passed to the function • The function prototype is not needed if the user-defined function is defined before the main() function.
  • 10. Function definition • Function definition contains the block of code to perform a specific task • Syntax of function definition returnType functionName(type1 arg1, type2 arg2, ...) { //body of the function } • When a function is called, the control of the program is transferred to the function definition. And, the compiler starts executing the codes inside the body of a function.
  • 11. Calling a function • Control of the program is transferred to the user-defined function by calling it. • Syntax of function call functionName(argument1, argument2, ...); • For example void main() { addNumbers(n1,n2); }
  • 12. Passing arguments to a function • In programming, argument refers to the variable passed to the function. • In the above example, two variables n1 and n2 are passed during function call. • The parameters a and b accepts the passed arguments in the function definition. These arguments are called formal parameters of the function. • The type of arguments passed to a function and the formal parameters must match, otherwise the compiler throws error. • If n1 is of char type, a also should be of char type. If n2 is of float type, variable b also should be of float type. • A function can also be called without passing an argument.
  • 13.
  • 14. Return Statement • The return statement terminates the execution of a function and returns a value to the calling function. • The program control is transferred to the calling function after return statement. • In the above example, the value of variable result is returned to the variable sum in the main() function.
  • 15.
  • 16. Syntax of return statement • return (expression); • For example, – return a; – return (a+b); • The type of value returned from the function and the return type specified in function prototype and function definition must match.
  • 17. Types of User-defined Functions in C Programming • No arguments passed and no return value • No arguments passed but a return value • Argument passed but no return value • Argument passed and a return value
  • 18. C Recursion • A function that calls itself is known as a recursive function. And, this technique is known as recursion.
  • 19. How recursion works? void recurse() { ... .. ... recurse(); ... .. ... } int main() { ... .. ... recurse(); ... .. ... }
  • 20. • The recursion continues until some condition is met to prevent it. • To prevent infinite recursion, if...else statement (or similar approach) can be used where one branch makes the recursive call and other doesn't.
  • 21. Sum of Natural Numbers Using Recursion #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; }
  • 22. int sum(int num) { if (num!=0) return num + sum(num-1); // sum() function calls itself else return num; }
  • 23. • Initially, the sum() is called from the main() function with number passed as an argument. • Suppose, the value of num is 3 initially. During next function call, 2 is passed to the sum() function. This process continues until num is equal to 0. • When num is equal to 0, the if condition fails and the else part is executed returning the sum of integers to the main() function.
  • 24.
  • 25. Advantages and Disadvantages of Recursion • Recursion makes program elegant and more readable. However, if performance is vital then, use loops instead as recursion is usually much slower. • Note that, every recursion can be modeled into a loop. • Recursion Vs Iteration? Need performance, use loops, however, code might look ugly and hard to read sometimes. Need more elegant and readable code, use recursion, however, you are sacrificing some performance.
  • 26. How to pass arrays to a function • Passing One-dimensional Array to a Function • Passing a single element of an array to a function is similar to passing variable to a function. #include <stdio.h> void display(int age) { printf("%d", age); } void main() { int a[] = {2, 3, 4}; display(a[2]); //Passing array element a[2] }
  • 27. Passing an entire array to a function #include <stdio.h> float average(int []); void main() { float avg; int age[] = {23, 55, 22, 5, 40, 18}; avg = average(age); // Only name of an array is passed as an argument printf("Average age = %.2f", avg); }
  • 28. float average(int age[]) { int i,sum=0; float avg; for (i = 0; i < 6; ++i) { sum += age[i]; } avg = (float)sum / 6; return avg; }
  • 29. Passing Multi-dimensional Arrays to Function • To pass multidimensional arrays to a function, only the name of the array is passed (similar to one dimensional array). #include <stdio.h> void displayNumbers(int num[2][2]); void 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); // passing multi-dimensional array to a function }
  • 30. 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("%dn", num[i][j]); }