05 - Unit 5. Subprograms
05 - Unit 5. Subprograms
Introduction
Declaring functions
Returning values
Recursion
2
INTRODUCTION
3
INTRODUCTION
4
INTRODUCTION
6
CONTENTS
Introduction
Declaring functions
Returning values
Recursion
7
DECLARING FUNCTIONS
ret_type: Specifies the type of the data that the function returns.
‘Void’ can be used to specify that no information is returned by the function.
If ret_type is omitted, int is assumed.
list_of_arguments: comma-separated list of variable names and their types.
An empty parameter list can be used. ‘Void’ can again be used to state that there
are no parameters. 8
DECLARING FUNCTIONS
body of the function: list of sentences that carry out the task for which the function
was created.
Can include declaration of variables, operations, calls to functions and any other
valid sentence.
If there is a return type, the function must return something
Keyword ‘return’ followed by a literal, variable or constant...
9
DECLARING FUNCTIONS
Examples:
float inverse(int x)
{
return 1.0 / x;
}
10
DECLARING FUNCTIONS
Examples:
#include <stdio.h>
#include <stdio.h>
float squareOfTheDifference(float a, float b)
{
void main()
float dif;
{
dif = a - b;
float n1, n2;
return dif * dif;
float result;
}
scanf("%f %f", &n1, &n2);
void main()
{
float dif;
float n1, n2;
dif = n1 – n2;
float result;
result = dif * dif;
scanf("%f %f", &n1, &n2);
printf("%f\n", result);
result = squareOfTheDifference(n1, n2);
}
printf("%f\n", result);
}
11
DECLARING FUNCTIONS
Prototypes
Depending on the compiler, functions need to be declared before they are
used.
Function prototypes allow the definition of a function without implementing
it.
The implementation comes later in the code.
Function prototypes are usually written at the beginning of a program,
ahead of any programmer-defined functions (including main).
The prototype and the actual declaration of the function must coincide.
12
DECLARING FUNCTIONS
#include <stdio.h>
Introduction
Declaring functions
Returning values
Recursion
14
RETURNING VALUES
Only if it is a void-type
void main() function:
return;
{
Otherwise, the return statement must be accompanied with a value of the
int number;
type specified in the function description.
printf("Enter an integer: ");
scanf("%d", &number);
The calling code is free to ignore the returned value…
if (isEven(number))
If a return type is specified, all the possible execution paths must
else
printf("%d is even.", number);
printf("%d is a negativereturn;
number.\n", num);
Only if it is a} void-type function:
Otherwise, the return statement must be accompanied with a value of the
void main()
type specified
{ in the function description.
int number;
The calling code is free to ignore the returned value…
printf("Enter an integer: ");
scanf("%d", &number);
If a return type is specified, all the possible execution paths must
printPositive(number);
return something.
}
18
#include <stdio.h>
RETURNING VALUES
int isEven(int num)
{
We can have several return
return 1; statements in a function.
if (num % 2 == 0)
Return missing if num is odd
else
Return different values depending
printf("Odd on a condition.
number!");
Introduction
Declaring functions
Returning values
Recursion
20
FUNCTIONS AND VARIABLES
21
FUNCTIONS AND VARIABLES
Local Variables
They are declared inside a function or a block of code ({…}).
They can ONLY be used inside that function or block.
They only exist while the function or block of code is being executed.
Can’t be accessed after that from anywhere.
Several functions or blocks of code can use variables with the same name.
They would be independent from each other.
22
FUNCTIONS AND VARIABLES
Local Variables
They are declared inside a function or a block of code ({…}).
They can ONLY be used inside that function or block.
#include <stdio.h> #include <stdio.h>
23
FUNCTIONS AND VARIABLES
Local Variables
They are declared inside a function or a block of code ({…}).
TheyFunction()
void can ONLY {
be used inside that function or block.
int x = 3;
They only exist while the function or block
if (x>0)
of code
#include is being executed.
<stdio.h>
Can’t
{ be accessed after that from anywhere. void main() {
int y = 4;
printf("%d %d\n",x,y); {
} int variableB = 10;
printf("%d",x); }
printf("%d \n", variableB);
printf("%d",y); }
}
24
FUNCTIONS AND VARIABLES
Local Variables
#include <stdio.h>
They
#include are declared inside a function or avoid
<stdio.h> block of code ({…}).
TestFunction()
void TestFunction() {
{ They can ONLY be used inside that function int or block.
variableA;
int variableA = 5; variableA = variableA + 1;
They only exist
printf("function while variableA);
-> %d\n", the function or blockprintf("function
or code is being
-> executed.
%d\n", variableA);
} }
Can’t be accessed after that from anywhere.
void main() void main()
{ Several functions or blocks of code can{ use variables with the same name.
int variableA = 10; int variableA = 10;
They would be independent from each other.
TestFunction(); TestFunction();
printf("main -> %d\n", variableA); printf("main -> %d\n", variableA);
} }
Formal Parameters
1024
Variables declared in the definition of a function.
They behave like local variables inside the function.
Assignments to any valid expression can be done.
Their scope is limited to the function.
26
FUNCTIONS AND VARIABLES
void main()
{
int a = 2;
int b = 10;
printf("%ld \n", power(a, b));
27
}
FUNCTIONS AND VARIABLES
Global Variables
They are known throughout the program and may be used by any piece of
code.
They will hold their value throughout the program's execution.
Create global variables by declaring them outside of any function.
28
FUNCTIONS AND VARIABLES
Global Variables
#include <stdio.h>
They are known throughout the program and may be used by any piece of
code.
int variableA = 100;
void main()
{
printf("main (1) -> %d\n", variableA); output
variableA++;
main (1) -> 100
TestFunction();
printf("main (2) -> %d\n", variableA); function -> 101
} main (2) -> 102 29
FUNCTIONS AND VARIABLES
Global Variables
Use of the ‘extern’ keyword:
Specifies that a variable is declared elsewhere in the program.
We can use that variable from that point, but it must be declared at any other point.
30
FUNCTIONS AND VARIABLES
Use
#include of the ‘extern’
<stdio.h> keyword: void TestFunction()
{
Specifies that a variable is declared elsewhere inextern
void TestFunction() the program.
int variableA;
{ printf("función->%d\n", variableA);
We can use that variable
printf("function->%d\n", from that point, but it variableA++;
variableA); must be declared at any other point.
variableA++; }
}
void main() {
void main() { extern int variableA;
printf("main (1)->%d\n", variableA); printf("main (1)->%d\n", variableA);
variableA++; variableA++;
TestFunction(); TestFunction();
printf("main (2)->%d\n", variableA); printf("main (2)->%d\n", variableA);
} }
Global Variables
Use of the ‘extern’ keyword:
Specifies that a variable is declared elsewhere in the program.
We can use that variable from that point, but it must be declared at any other point.
Variable declaration != variable definition.
The same variable can have many declaration but only one definition.
Declaration -> declares name and type.
Definition -> causes storage to be allocated.
Commonly used to declare variables in one file and use them in other file.
32
FUNCTIONS AND VARIABLES
Global Variables
Use of the ‘extern’ keyword:
Specifies that a variable is declared elsewhere in the program.
We can use that variable from that point, but it must be declared at any other point.
Variable declaration != variable definition.
The same variable can have many declaration but only one definition.
Declaration -> declares name and type.
extern int a; // Declaring a variable a without defining it
Definition -> causes storage to be allocated.
int myFunc(int a, int b); // Declaring a function
Commonly used to declare variables in one file and use them in other file.
33
FUNCTIONS AND VARIABLES
Global Variables
Use of the ‘extern’ keyword:
Specifies that a variable is declared elsewhere in the program.
We can use that variable from that point, but it must be declared at any other point.
Variable declaration != variable definition.
The same variable can have many declaration but only one definition.
Declaration -> declares name and type.
Definition -> causes storage to be allocated.
int a;
Commonly used to declare variables in one file and use them in other file.
int b = 0;
int myFunc(int a, int b) { return a + b; }
34
FUNCTIONS AND VARIABLES
Global Variables
Conflicts:
If a global variable and a local variable have the same name, all references to that
variable name inside the code block in which the local variable is declared will
refer to that local variable and have no effect on the global variable.
35
#include <stdio.h>
int var = 4;
FUNCTIONS AND VARIABLES
void localTest();
void globalTest();
void externTest();
Global Variables output
void main() { Initial value:4
Conflicts:
printf("Initial value:%d\n", var);
localTest();
printf("After localTest:%d\n\n", var); Inside localTest:3
If a global variable and a local variable have theAfter
globalTest(); same localTest:4
name, all references to that
printf("After globalTest:%d\n\n", var);
variable name inside the code block in which the
externTest(); local variable is declared will
Inside globalTest:5
}
refer to that local variable and have no effect on
printf("After externTest:%d\n", var);
the global variable.
After globalTest:5
void localTest() {
int var = 3; Inside externTest:10
printf("Inside localTest:%d\n", var);
} After externTest:10
void globalTest() {
var = 5;
printf("Inside globalTest:%d\n", var);
}
void externTest() {
extern int var;
var = 10;
printf("Inside externTest:%d\n", var);
} 36
CONTENTS
Introduction
Declaring functions
Returning values
Recursion
37
PASSING ARGUMENTS TO A FUNCTION
38
PASSING ARGUMENTS TO A FUNCTION
39
PASSING ARGUMENTS TO A FUNCTION
#include <stdio.h>
40
PASSING ARGUMENTS TO A FUNCTION
41
PASSING ARGUMENTS TO A FUNCTION
#include <stdio.h>
By reference
void main()
{
int Theb;addresses of the arguments are copied into the parameter.
a,
a = b = 2;
The address is used
printf("(main)Before: to access
%d, %d.\n",the
a, actual
b); argument used in the call of the function.
increment(a, &b);
Changes made to %d,
printf("(main)After: the parameter
%d.\n", a, affect
b); the argument.
}
These changes will be visible from outside of the function.
Example:
void increment(int x, int* y)
{ output
printf("(function) Before: %d, %d.\n", x, *y); (main)Before: 2, 2.
x = x + 1; (function) Before: 2, 2.
*y = *y + 1; (function) After: 3, 3.
(main)After: 2, 3.
printf("(function) After: %d, %d.\n", x, *y);
} 42
PASSING ARGUMENTS TO A FUNCTION
43
PASSING ARGUMENTS TO A FUNCTION
44
PASSING ARGUMENTS TO A FUNCTION
45
PASSING ARGUMENTS TO A FUNCTION
46
PASSING ARGUMENTS TO A FUNCTION
and it is an integer.
int main(int argc, char* argv[])
{
It is always at least 1, because the name of the program qualifies as the first
if (argc != 2)
argument. {
printf("You forgot to type your name.\n");
The argv parameterreturnis a pointer
1; to an array of character pointers.
}
Each element in this array points to a command line argument.
printf("Hello %s", argv[1]);
return 0;
All command line arguments are strings
}
any numbers will have to be converted by the program into the proper binary format,
manually.
47
CONTENTS
Introduction
Declaring functions
Returning values
Recursion
48
CALLING A FUNCTION: THE STACK
49
CALLING A FUNCTION: THE STACK
51
CALLING A FUNCTION: THE STACK
void main()
{
int i = 10;
functionTest(i);
printf("%d \n", i);
}
void functionTest(int j)
{
int i = 100;
j = i + 2;
printf("%d %d \n", i, j);
52
}
CALLING A FUNCTION: THE STACK
void main()
{
int i = 10;
functionTest(i);
printf("%d \n", i);
}
void functionTest(int j)
{
int i = 100;
j = i + 2;
main()
printf("%d %d \n", i, j);
i = 10 53
}
CALLING A FUNCTION: THE STACK
void main()
{
int i = 10;
functionTest(i);
printf("%d \n", i);
} functionTest()
void functionTest(int j) j = 10
{
int i = 100;
j = i + 2;
main()
printf("%d %d \n", i, j);
i = 10 54
}
CALLING A FUNCTION: THE STACK
void main()
{
int i = 10;
functionTest(i);
printf("%d \n", i);
} functionTest()
i = 100
void functionTest(int j) j = 10
{
int i = 100;
j = i + 2;
main()
printf("%d %d \n", i, j);
i = 10 55
}
CALLING A FUNCTION: THE STACK
void main()
{
int i = 10;
functionTest(i);
printf("%d \n", i);
} functionTest()
ij == 100
10
void functionTest(int j) jj == 102
10
{
int i = 100;
j = i + 2;
main()
printf("%d %d \n", i, j);
i = 10 56
}
CALLING A FUNCTION: THE STACK
void main()
{
int i = 10;
functionTest(i);
printf("%d \n", i);
} functionTest()
ij == 100
10
void functionTest(int j) i = 100
j 102
{
int i = 100;
j = i + 2;
main()
printf("%d %d \n", i, j);
i = 10 57
}
CALLING A FUNCTION: THE STACK
void main()
{
int i = 10;
functionTest(i);
printf("%d \n", i);
}
void functionTest(int j)
{
int i = 100;
j = i + 2;
main()
printf("%d %d \n", i, j);
i = 10 58
}
CALLING A FUNCTION: THE STACK
void main()
{
int i = 10;
functionTest(i);
printf("%d \n", i);
}
void functionTest(int j)
{
int i = 100;
j = i + 2;
printf("%d %d \n", i, j);
59
}
CALLING A FUNCTION: THE STACK
#include <stdio.h>
Another example Memory output
void increment(int x, int* y); Before1: 2, 2
Before2: 2, 2
void main() After2: 3, 3
{ After1: 2, 3
int a = 2, b = 2;
printf("Before1: %d, %d.\n", a, b);
increment(a, &b);
printf("After1: %d, %d.\n", a, b);
}
Introduction
Declaring functions
Returning values
Recursion
61
RECURSION
62
RECURSION
Memory input
Example.
#include <stdio.h> n = 3
Example.
void reverse(void); /* function prototype */
main()
void
n = 3
{
printf("Please enter a line of text below\n");
reverse();
}
void reverse(void)
/* read a line of characters and write it out backwards */ 3! = 6
{
char c;
if ((c = getchar()) != '\n')
reverse();
putchar(c);
return;
}
hello \n 72
RECURSION
Two possibilities:
Direct: The function invokes itself.
Indirect: The first function invokes a second function, which in turn invokes
the first function.
73
END.