SlideShare a Scribd company logo
Outline
Introduction
Program Modules in C
Math Library Functions
Functions
Function Definitions
Function Prototypes
Header Files
Calling Functions: Call by Value and Call by
Reference
Random Number Generation
Recursion
Example Using Recursion: The Fibonacci Series
Recursion vs. Iteration
 Divide and conquer
◦ Construct a program from smaller pieces or
components
◦ Each piece more manageable than the original
program
 Functions
◦ Modules in C
◦ Programs written by combining user-defined functions with
library functions
 C standard library has a wide variety of functions
 Makes programmer's job easier - avoid reinventing the wheel
 Function calls
◦ Invoking functions
 Provide function name and arguments (data)
 Function performs operations or manipulations
 Function returns results
◦ Boss asks worker to complete task
 Worker gets information, does task, returns result
 Information hiding: boss does not know details
 Math library functions
◦ perform common mathematical calculations
◦ #include <math.h>
 Format for calling functions
FunctionName (argument);
 If multiple arguments, use comma-separated list
◦ printf( "%.2f", sqrt( 900.0 ) );
 Calls function sqrt, which returns the square root of its
argument
 All math functions return data type double
◦ Arguments may be constants, variables, or
expressions
 Functions
◦ Modularize a program
◦ All variables declared inside functions are local variables
 Known only in function defined
◦ Parameters
 Communicate information between functions
 Local variables
 Benefits
◦ Divide and conquer
 Manageable program development
◦ Software reusability
 Use existing functions as building blocks for new programs
 Abstraction - hide internal details (library functions)
◦ Avoids code repetition
 Function definition format
return-value-type function-name( parameter-list )
{
declarations and statements
}
◦ Function-name: any valid identifier
◦ Return-value-type: data type of the result (default int)
 void - function returns nothing
◦ Parameter-list: comma separated list, declares
parameters (default int)
 Function definition format (continued)
return-value-type function-name( parameter-list )
{
declarations and statements
}
◦ Declarations and statements: function body (block)
 Variables can be declared inside blocks (can be nested)
 Function can not be defined inside another function
◦ Returning control
 If nothing returned
 return;
 or, until reaches right brace
 If something returned
 return expression;
1. Function prototype
(3 parameters)
2. Input values
2.1 Call function
3. Function definition
Program Output
1 /* Fig. 5.4: fig05_04.c
2 Finding the maximum of three integers */
3 #include <stdio.h>
4
5 int maximum( int, int, int ); /* function prototype */
6
7 int main()
8 {
9 int a, b, c;
10
11 printf( "Enter three integers: " );
12 scanf( "%d%d%d", &a, &b, &c );
13 printf( "Maximum is: %dn", maximum( a, b, c ) );
14
15 return 0;
16 }
17
18 /* Function maximum definition */
19 int maximum( int x, int y, int z )
20 {
21 int max = x;
22
23 if ( y > max )
24 max = y;
25
26 if ( z > max )
27 max = z;
28
29 return max;
30 }
Enter three integers: 22 85 17
Maximum is: 85
 Function prototype
◦ Function name
◦ Parameters - what the function takes in
◦ Return type - data type function returns (default int)
◦ Used to validate functions
◦ Prototype only needed if function definition comes after use in
program
int maximum( int, int, int );
 Takes in 3 ints
 Returns an int
 Promotion rules and conversions
◦ Converting to lower types can lead to errors
 Header files
◦ contain function prototypes for library functions
◦ <stdlib.h> , <math.h> , etc
◦ Load with #include <filename>
#include <math.h>
 Custom header files
◦ Create file with functions
◦ Save as filename.h
◦ Load in other files with #include "filename.h"
◦ Reuse functions
 Used when invoking functions
 Call by value
◦ Copy of argument passed to function
◦ Changes in function do not effect original
◦ Use when function does not need to modify argument
 Avoids accidental changes
 Call by reference
◦ Passes original argument
◦ Changes in function effect original
◦ Only used with trusted functions
 For now, we focus on call by value
 rand function
◦ Load <stdlib.h>
◦ Returns "random" number between 0 and RAND_MAX (at least
32767)
i = rand();
◦ Pseudorandom
 Preset sequence of "random" numbers
 Same sequence for every function call
 Scaling
◦ To get a random number between 1 and n
1 + ( rand() % n )
 rand % n returns a number between 0 and n-1
 Add 1 to make random number between 1 and n
1 + ( rand() % 6) // number between 1 and 6
 srand function
◦ <stdlib.h>
◦ Takes an integer seed - jumps to location in "random"
sequence
srand( seed );
◦ srand( time( NULL ) ); //load <time.h>
 time( NULL )- time program was compiled in seconds
 "randomizes" the seed
 Recursive functions
◦ Function that calls itself
◦ Can only solve a base case
◦ Divides up problem into
 What it can do
 What it cannot do - resembles original problem
 Launches a new copy of itself (recursion step)
 Eventually base case gets solved
◦ Gets plugged in, works its way up and solves whole
problem
 Example: factorial:
5! = 5 * 4 * 3 * 2 * 1
Notice that
5! = 5 * 4!
4! = 4 * 3! ...
◦ Can compute factorials recursively
◦ Solve base case (1! = 0! = 1) then plug in
 2! = 2 * 1! = 2 * 1 = 2;
 3! = 3 * 2! = 3 * 2 = 6;
 Fibonacci series: 0, 1, 1, 2, 3, 5, 8...
◦ Each number sum of the previous two
fib(n) = fib(n-1) + fib(n-2) - recursive
formula
long fibonacci(long n)
{
if (n==0 || n==1) //base case
return n;
else return fibonacci(n-1) + fibonacci(n-2);
}
 
f( 3 )
f( 1 )f( 2 )
f( 1 ) f( 0 ) return 1
return 1 return 0
return +
+return
 
1. Function prototype
1.1 Initialize variables
2. Input an integer
2.1 Call function
fibonacci
2.2 Output results.
3. Define fibonacci
recursively
Program Output
1 /* Fig. 5.15: fig05_15.c
2 Recursive fibonacci function */
3 #include <stdio.h>
4
5 long fibonacci( long );
6
7 int main()
8 {
9 long result, number;
10
11 printf( "Enter an integer: " );
12 scanf( "%ld", &number );
13 result = fibonacci( number );
14 printf( "Fibonacci( %ld ) = %ldn", number, result );
15 return 0;
16 }
17
18 /* Recursive definition of function fibonacci */
19 long fibonacci( long n )
20 {
21 if ( n == 0 || n == 1 )
22 return n;
23 else
24 return fibonacci( n - 1 ) + fibonacci( n - 2 );
25 }
Enter an integer: 0
Fibonacci(0) = 0
Enter an integer: 1
Fibonacci(1) = 1
Program Output
Enter an integer: 2
Fibonacci(2) = 1
Enter an integer: 3
Fibonacci(3) = 2
Enter an integer: 4
Fibonacci(4) = 3
Enter an integer: 5
Fibonacci(5) = 5
Enter an integer: 6
Fibonacci(6) = 8
Enter an integer: 10
Fibonacci(10) = 55
Enter an integer: 20
Fibonacci(20) = 6765
Enter an integer: 30
Fibonacci(30) = 832040
Enter an integer: 35
Fibonacci(35) = 9227465
 Repetition
◦ Iteration: explicit loop
◦ Recursion: repeated function calls
 Termination
◦ Iteration: loop condition fails
◦ Recursion: base case recognized
 Both can have infinite loops
 Balance
◦ Choice between performance (iteration) and good software engineering
(recursion)

More Related Content

What's hot

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
 
Lecture#9 Arrays in c++
Lecture#9 Arrays in c++Lecture#9 Arrays in c++
Lecture#9 Arrays in c++
NUST Stuff
 
Functions in c
Functions in cFunctions in c
Functions in c
Innovative
 
Tail Recursion in data structure
Tail Recursion in data structureTail Recursion in data structure
Tail Recursion in data structure
Rumman Ansari
 
Call by value
Call by valueCall by value
Call by valueDharani G
 
Functions
FunctionsFunctions
Functions
PralhadKhanal1
 
C++ lecture 03
C++   lecture 03C++   lecture 03
C++ lecture 03
HNDE Labuduwa Galle
 
Presentation on function
Presentation on functionPresentation on function
Presentation on function
Abu Zaman
 
C programming function
C  programming functionC  programming function
C programming function
argusacademy
 
Function in c program
Function in c programFunction in c program
Function in c program
CGC Technical campus,Mohali
 
Types of function call
Types of function callTypes of function call
Types of function call
ArijitDhali
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
nikshaikh786
 
functions of C++
functions of C++functions of C++
functions of C++
tarandeep_kaur
 
Functions
FunctionsFunctions
Functions
Jesmin Akhter
 
parameter passing in c#
parameter passing in c#parameter passing in c#
parameter passing in c#
khush_boo31
 
20BCE1734.pdf
20BCE1734.pdf20BCE1734.pdf
20BCE1734.pdf
Mridul Jadon
 
Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)
Dharma Kshetri
 

What's hot (20)

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++
 
Lecture#9 Arrays in c++
Lecture#9 Arrays in c++Lecture#9 Arrays in c++
Lecture#9 Arrays in c++
 
Chap 9(functions)
Chap 9(functions)Chap 9(functions)
Chap 9(functions)
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Tail Recursion in data structure
Tail Recursion in data structureTail Recursion in data structure
Tail Recursion in data structure
 
Call by value
Call by valueCall by value
Call by value
 
Functions
FunctionsFunctions
Functions
 
C++ lecture 03
C++   lecture 03C++   lecture 03
C++ lecture 03
 
Functions
FunctionsFunctions
Functions
 
Presentation on function
Presentation on functionPresentation on function
Presentation on function
 
C programming function
C  programming functionC  programming function
C programming function
 
Function in c program
Function in c programFunction in c program
Function in c program
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Types of function call
Types of function callTypes of function call
Types of function call
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
 
functions of C++
functions of C++functions of C++
functions of C++
 
Functions
FunctionsFunctions
Functions
 
parameter passing in c#
parameter passing in c#parameter passing in c#
parameter passing in c#
 
20BCE1734.pdf
20BCE1734.pdf20BCE1734.pdf
20BCE1734.pdf
 
Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)
 

Similar to functions

Array Cont
Array ContArray Cont
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
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 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)
hhliu
 
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
 
Functions
FunctionsFunctions
Functions
Swarup Boro
 
C function
C functionC function
C function
thirumalaikumar3
 
Function in c program
Function in c programFunction in c program
Function in c program
umesh patil
 
Functions in c
Functions in cFunctions in c
Functions in c
KavithaMuralidharan2
 
how to reuse code
how to reuse codehow to reuse code
how to reuse code
jleed1
 
UNIT3.pptx
UNIT3.pptxUNIT3.pptx
UNIT3.pptx
NagasaiT
 
Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01Abdul Samee
 
User Defined Functions in C Language
User Defined Functions   in  C LanguageUser Defined Functions   in  C Language
User Defined Functions in C Language
Infinity Tech Solutions
 
eee2-day4-structures engineering college
eee2-day4-structures engineering collegeeee2-day4-structures engineering college
eee2-day4-structures engineering college
2017eee0459
 
Function in c
Function in cFunction in c
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
Sampath Kumar
 

Similar to functions (20)

functions
functionsfunctions
functions
 
Array Cont
Array ContArray Cont
Array Cont
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
 
Function
FunctionFunction
Function
 
lecture56.ppt
lecture56.pptlecture56.ppt
lecture56.ppt
 
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 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)
 
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
 
Functions
FunctionsFunctions
Functions
 
C function
C functionC function
C function
 
Function in c program
Function in c programFunction in c program
Function in c program
 
6. function
6. function6. function
6. function
 
Functions in c
Functions in cFunctions in c
Functions in c
 
how to reuse code
how to reuse codehow to reuse code
how to reuse code
 
UNIT3.pptx
UNIT3.pptxUNIT3.pptx
UNIT3.pptx
 
Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01
 
User Defined Functions in C Language
User Defined Functions   in  C LanguageUser Defined Functions   in  C Language
User Defined Functions in C Language
 
eee2-day4-structures engineering college
eee2-day4-structures engineering collegeeee2-day4-structures engineering college
eee2-day4-structures engineering college
 
Function in c
Function in cFunction in c
Function in c
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
 

More from teach4uin

Controls
ControlsControls
Controls
teach4uin
 
validation
validationvalidation
validation
teach4uin
 
validation
validationvalidation
validation
teach4uin
 
Master pages
Master pagesMaster pages
Master pages
teach4uin
 
.Net framework
.Net framework.Net framework
.Net framework
teach4uin
 
Scripting languages
Scripting languagesScripting languages
Scripting languages
teach4uin
 
Css1
Css1Css1
Css1
teach4uin
 
Code model
Code modelCode model
Code model
teach4uin
 
Asp db
Asp dbAsp db
Asp db
teach4uin
 
State management
State managementState management
State management
teach4uin
 
security configuration
security configurationsecurity configuration
security configuration
teach4uin
 
static dynamic html tags
 static dynamic html tags static dynamic html tags
static dynamic html tags
teach4uin
 
static dynamic html tags
static dynamic html tagsstatic dynamic html tags
static dynamic html tags
teach4uin
 
New microsoft office power point presentation
New microsoft office power point presentationNew microsoft office power point presentation
New microsoft office power point presentation
teach4uin
 
.Net overview
.Net overview.Net overview
.Net overview
teach4uin
 
Stdlib functions lesson
Stdlib functions lessonStdlib functions lesson
Stdlib functions lesson
teach4uin
 
enums
enumsenums
enums
teach4uin
 
memory
memorymemory
memory
teach4uin
 
array
arrayarray
array
teach4uin
 
storage clas
storage classtorage clas
storage clas
teach4uin
 

More from teach4uin (20)

Controls
ControlsControls
Controls
 
validation
validationvalidation
validation
 
validation
validationvalidation
validation
 
Master pages
Master pagesMaster pages
Master pages
 
.Net framework
.Net framework.Net framework
.Net framework
 
Scripting languages
Scripting languagesScripting languages
Scripting languages
 
Css1
Css1Css1
Css1
 
Code model
Code modelCode model
Code model
 
Asp db
Asp dbAsp db
Asp db
 
State management
State managementState management
State management
 
security configuration
security configurationsecurity configuration
security configuration
 
static dynamic html tags
 static dynamic html tags static dynamic html tags
static dynamic html tags
 
static dynamic html tags
static dynamic html tagsstatic dynamic html tags
static dynamic html tags
 
New microsoft office power point presentation
New microsoft office power point presentationNew microsoft office power point presentation
New microsoft office power point presentation
 
.Net overview
.Net overview.Net overview
.Net overview
 
Stdlib functions lesson
Stdlib functions lessonStdlib functions lesson
Stdlib functions lesson
 
enums
enumsenums
enums
 
memory
memorymemory
memory
 
array
arrayarray
array
 
storage clas
storage classtorage clas
storage clas
 

Recently uploaded

UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 

Recently uploaded (20)

UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 

functions

  • 1. Outline Introduction Program Modules in C Math Library Functions Functions Function Definitions Function Prototypes Header Files Calling Functions: Call by Value and Call by Reference Random Number Generation Recursion Example Using Recursion: The Fibonacci Series Recursion vs. Iteration
  • 2.  Divide and conquer ◦ Construct a program from smaller pieces or components ◦ Each piece more manageable than the original program
  • 3.  Functions ◦ Modules in C ◦ Programs written by combining user-defined functions with library functions  C standard library has a wide variety of functions  Makes programmer's job easier - avoid reinventing the wheel
  • 4.  Function calls ◦ Invoking functions  Provide function name and arguments (data)  Function performs operations or manipulations  Function returns results ◦ Boss asks worker to complete task  Worker gets information, does task, returns result  Information hiding: boss does not know details
  • 5.  Math library functions ◦ perform common mathematical calculations ◦ #include <math.h>  Format for calling functions FunctionName (argument);  If multiple arguments, use comma-separated list ◦ printf( "%.2f", sqrt( 900.0 ) );  Calls function sqrt, which returns the square root of its argument  All math functions return data type double ◦ Arguments may be constants, variables, or expressions
  • 6.  Functions ◦ Modularize a program ◦ All variables declared inside functions are local variables  Known only in function defined ◦ Parameters  Communicate information between functions  Local variables  Benefits ◦ Divide and conquer  Manageable program development ◦ Software reusability  Use existing functions as building blocks for new programs  Abstraction - hide internal details (library functions) ◦ Avoids code repetition
  • 7.  Function definition format return-value-type function-name( parameter-list ) { declarations and statements } ◦ Function-name: any valid identifier ◦ Return-value-type: data type of the result (default int)  void - function returns nothing ◦ Parameter-list: comma separated list, declares parameters (default int)
  • 8.  Function definition format (continued) return-value-type function-name( parameter-list ) { declarations and statements } ◦ Declarations and statements: function body (block)  Variables can be declared inside blocks (can be nested)  Function can not be defined inside another function ◦ Returning control  If nothing returned  return;  or, until reaches right brace  If something returned  return expression;
  • 9. 1. Function prototype (3 parameters) 2. Input values 2.1 Call function 3. Function definition Program Output 1 /* Fig. 5.4: fig05_04.c 2 Finding the maximum of three integers */ 3 #include <stdio.h> 4 5 int maximum( int, int, int ); /* function prototype */ 6 7 int main() 8 { 9 int a, b, c; 10 11 printf( "Enter three integers: " ); 12 scanf( "%d%d%d", &a, &b, &c ); 13 printf( "Maximum is: %dn", maximum( a, b, c ) ); 14 15 return 0; 16 } 17 18 /* Function maximum definition */ 19 int maximum( int x, int y, int z ) 20 { 21 int max = x; 22 23 if ( y > max ) 24 max = y; 25 26 if ( z > max ) 27 max = z; 28 29 return max; 30 } Enter three integers: 22 85 17 Maximum is: 85
  • 10.  Function prototype ◦ Function name ◦ Parameters - what the function takes in ◦ Return type - data type function returns (default int) ◦ Used to validate functions ◦ Prototype only needed if function definition comes after use in program int maximum( int, int, int );  Takes in 3 ints  Returns an int  Promotion rules and conversions ◦ Converting to lower types can lead to errors
  • 11.  Header files ◦ contain function prototypes for library functions ◦ <stdlib.h> , <math.h> , etc ◦ Load with #include <filename> #include <math.h>  Custom header files ◦ Create file with functions ◦ Save as filename.h ◦ Load in other files with #include "filename.h" ◦ Reuse functions
  • 12.  Used when invoking functions  Call by value ◦ Copy of argument passed to function ◦ Changes in function do not effect original ◦ Use when function does not need to modify argument  Avoids accidental changes  Call by reference ◦ Passes original argument ◦ Changes in function effect original ◦ Only used with trusted functions  For now, we focus on call by value
  • 13.  rand function ◦ Load <stdlib.h> ◦ Returns "random" number between 0 and RAND_MAX (at least 32767) i = rand(); ◦ Pseudorandom  Preset sequence of "random" numbers  Same sequence for every function call  Scaling ◦ To get a random number between 1 and n 1 + ( rand() % n )  rand % n returns a number between 0 and n-1  Add 1 to make random number between 1 and n 1 + ( rand() % 6) // number between 1 and 6
  • 14.  srand function ◦ <stdlib.h> ◦ Takes an integer seed - jumps to location in "random" sequence srand( seed ); ◦ srand( time( NULL ) ); //load <time.h>  time( NULL )- time program was compiled in seconds  "randomizes" the seed
  • 15.  Recursive functions ◦ Function that calls itself ◦ Can only solve a base case ◦ Divides up problem into  What it can do  What it cannot do - resembles original problem  Launches a new copy of itself (recursion step)  Eventually base case gets solved ◦ Gets plugged in, works its way up and solves whole problem
  • 16.  Example: factorial: 5! = 5 * 4 * 3 * 2 * 1 Notice that 5! = 5 * 4! 4! = 4 * 3! ... ◦ Can compute factorials recursively ◦ Solve base case (1! = 0! = 1) then plug in  2! = 2 * 1! = 2 * 1 = 2;  3! = 3 * 2! = 3 * 2 = 6;
  • 17.  Fibonacci series: 0, 1, 1, 2, 3, 5, 8... ◦ Each number sum of the previous two fib(n) = fib(n-1) + fib(n-2) - recursive formula long fibonacci(long n) { if (n==0 || n==1) //base case return n; else return fibonacci(n-1) + fibonacci(n-2); }  
  • 18. f( 3 ) f( 1 )f( 2 ) f( 1 ) f( 0 ) return 1 return 1 return 0 return + +return  
  • 19. 1. Function prototype 1.1 Initialize variables 2. Input an integer 2.1 Call function fibonacci 2.2 Output results. 3. Define fibonacci recursively Program Output 1 /* Fig. 5.15: fig05_15.c 2 Recursive fibonacci function */ 3 #include <stdio.h> 4 5 long fibonacci( long ); 6 7 int main() 8 { 9 long result, number; 10 11 printf( "Enter an integer: " ); 12 scanf( "%ld", &number ); 13 result = fibonacci( number ); 14 printf( "Fibonacci( %ld ) = %ldn", number, result ); 15 return 0; 16 } 17 18 /* Recursive definition of function fibonacci */ 19 long fibonacci( long n ) 20 { 21 if ( n == 0 || n == 1 ) 22 return n; 23 else 24 return fibonacci( n - 1 ) + fibonacci( n - 2 ); 25 } Enter an integer: 0 Fibonacci(0) = 0 Enter an integer: 1 Fibonacci(1) = 1
  • 20. Program Output Enter an integer: 2 Fibonacci(2) = 1 Enter an integer: 3 Fibonacci(3) = 2 Enter an integer: 4 Fibonacci(4) = 3 Enter an integer: 5 Fibonacci(5) = 5 Enter an integer: 6 Fibonacci(6) = 8 Enter an integer: 10 Fibonacci(10) = 55 Enter an integer: 20 Fibonacci(20) = 6765 Enter an integer: 30 Fibonacci(30) = 832040 Enter an integer: 35 Fibonacci(35) = 9227465
  • 21.  Repetition ◦ Iteration: explicit loop ◦ Recursion: repeated function calls  Termination ◦ Iteration: loop condition fails ◦ Recursion: base case recognized  Both can have infinite loops  Balance ◦ Choice between performance (iteration) and good software engineering (recursion)