0% found this document useful (0 votes)
18 views74 pages

05 - Unit 5. Subprograms

Uploaded by

antogf1986
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views74 pages

05 - Unit 5. Subprograms

Uploaded by

antogf1986
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

UNIT 5 – SUBPROGRAMS: FUNCTIONS

ARTURO S. GARCÍA PROGRAMMING FUNDAMENTALS 1


UNIVERSITY OF CASTILLA-LA MANCHA
DEGREE IN COMPUTER SCIENCE AND ENGINEERING.
2022-2023 ESII ALBACETE
CONTENTS

Introduction

Declaring functions

Returning values

Functions and variables

Passing arguments to a function

Calling a function: the stack

Recursion

2
INTRODUCTION

 A subprogram is a self-contained program segment that carries out


some specific and well-defined task.
 Once the subprogram has carried out its intended action, control will
be returned to the point from which the it was accessed.
 Information can be sent to a subprogram as parameters, and they can
return (or not) information when they finish.

3
INTRODUCTION

 C allows programmers to define their own subprograms for carrying


out various individual tasks.
 This allows a large program to be broken down into a number of
smaller, self-contained components, each of which has some unique,
identifiable purpose.
 Unit 1: structured programming: divide & conquer and top-down design.
 A program can be modularized through the use of subprograms.

4
INTRODUCTION

 Some languages differentiate between functions and procedures.


 Function: subprogram that returns a value.
 Procedure: subprogram that does not return any value.
 C only uses functions.
 Datatype: void.
 Every C program consists of one or more functions.
 One of these functions must be called main.
 Execution of the program will always begin by carrying out the instructions
in main.
5
INTRODUCTION

 Advantages of using functions:


 Avoids the need for redundant (repeated) programming of the same instructions.
 Increases readability.
 Divides a complex problem into simpler ones.
 Reduces chances of errors (copy&paste)
 Makes programs easier to maintain and modify.
 Reuse of the code: Enables the creation of customized libraries of frequently used
functions.
 Allows the division of the programming work among several people.

6
CONTENTS

Introduction

Declaring functions

Returning values

Functions and variables

Passing arguments to a function

Calling a function: the stack

Recursion

7
DECLARING FUNCTIONS

 General form of a function:


ret_type name(list_of_arguments)
{
body of the function
}

 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

 General form of a function:


ret_type name(list_of_arguments)
{
body of the function
}

 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;
}

float squareOfTheDifference(float a, float b)


{
float dif;
dif = a – b;
return dif * dif;
}

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>

float squareOfTheDifference(float a, float b);


 Prototypes
void main()
 Depending on{ the compiler, functions need to be declared before they are
used. float n1, n2;
float result;
 Function prototypes allow the definition of a function without implementing
scanf("%f %f", &n1, &n2);
it. result = squareOfTheDifference(n1, n2);
printf("%f\n", result);
 The implementation
}
comes later in the code.
 Function prototypes are usually written at the beginning of a program,
float squareOfTheDifference(float a, float b)
ahead of any programmer-defined
{ functions (including main).
float dif;
 The prototype and
difthe
= aactual
- b; declaration of the function must coincide.
return dif * dif;
}
13
CONTENTS

Introduction

Declaring functions

Returning values

Functions and variables

Passing arguments to a function

Calling a function: the stack

Recursion

14
RETURNING VALUES

 Syntax: return expression;

 Return has two important uses:


 It causes an immediate exit from the function.
 It causes program execution to return to the calling code.
 It can be used to return a value.

 The execution of the program returns to the same instruction from


which the function was called.
 The next one will be the instruction following the function call.

 ONLY one value can be returned!


15
RETURNING VALUES

 We can have several return statements in a function.


 Return different values depending on a condition.
 We can use return to exit the function without returning anything.
 Only if it is a void-type function: return;

 Otherwise, the return statement must be accompanied with a value of the


type specified in the function description.
 The calling code is free to ignore the returned value…
 If a return type is specified, all the possible execution paths must
return something.
16
#include <stdio.h>
RETURNING VALUES
int isEven(int num)
 We can have several return statements in a function.
{
if (num % 2 == 0)
 Return different values depending
return 1; on a condition.
else
 We can use return to exit the function without returning anything.
}
return 0;

 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);

return something. printf("%d is odd.", number);


} 17
RETURNING VALUES
#include <stdio.h>

void printPositive(int num)


 We can have several return statements in a function.
{
if (num >= 0)
 Return different{ values depending on a condition.
printf("%d is a positive number.\n", num);
 We can use return to exit the function without returning anything.
}
return;

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!");

 We can use return


} to exit the function without returning anything.
 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 isiffree to ignore the returned value…
(isEven(number))
printf("%d is even.", number);
 If a return type is specified, all the possible execution paths must
else
return something. printf("%d is odd.", number);
}
19
CONTENTS

Introduction

Declaring functions

Returning values

Functions and variables

Passing arguments to a function

Calling a function: the stack

Recursion

20
FUNCTIONS AND VARIABLES

 Three types of variables depending on where they are declared and


their scope:
 Local variables: declared inside a function or a block of code.
 Formal parameters: declared in the definition of a function.
 Global variables: declared outside of any function.

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>

void TestFunction() { void TestFunction() {


printf("%d \n", variableA); int variableA = 10;
} }

void main() { void main() {


int variableA = 10; TestFunction();
TestFunction(); printf("%d \n", variableA);
} }

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);
} }

function -> 5 function -> ??


output main -> 10 output main -> 10 25
FUNCTIONS AND VARIABLES

 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

 Formal Parameters output


#include <stdio.h> 1024
 Variables declared in the definition of a function.
long power(int base, int exponent)
 They behave{ like local variables inside the function.
long result = 1;
 Assignments to any valid expression can be done.
int i = 0;
for (i = 1; i <= exponent; i++)
 Their scope is limited to the function.
result = result * base;
return result;
}

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;

 They will hold their value throughout the program's execution.


void TestFunction()
{
 Create global variables by declaring them outside of any function.
printf("function -> %d\n", variableA);
variableA++;
}

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

 Global Variables #include <stdio.h>

 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);
} }

int variableA = 100; int variableA = 100; 31


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.
 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

Functions and variables

Passing arguments to a function

Calling a function: the stack

Recursion

37
PASSING ARGUMENTS TO A FUNCTION

 There are two ways to pass arguments to a subprogram:


 By value
 By reference

38
PASSING ARGUMENTS TO A FUNCTION

 There are two ways to pass arguments to a subprogram:


 By value
 This method copies the value of an argument into the formal parameter of the
subprogram.
 Changes made to the parameter have no effect on the argument.

39
PASSING ARGUMENTS TO A FUNCTION
#include <stdio.h>

 There are two waysvA,toint


int addAndReset(int pass
vB) arguments to a subprogram:
{
 By value
int result = vA + vB;
vA = 0;
 This
vB method
= 0; copies the value of an argument into the formal parameter of the
subprogram.
printf("Inside: %d, %d.\n", vA, vB);
return result;
} Changes made to the parameter have no effect on the argument.
 Example:
void main()
{ output
int varA = 4; Inside: 0, 0.
int varB = 6; Result 10.
printf("Result %d. \n", addAndReset(varA,varB)); Outside: 4, 6.
printf("Outside: %d, %d. \n", varA, varB);
}

40
PASSING ARGUMENTS TO A FUNCTION

 There are two ways to pass arguments to a subprogram:


 By reference
 The addresses of the arguments are copied into the parameter.
 The address is used to access the actual argument used in the call of the function.
 Changes made to the parameter affect the argument.
 These changes will be visible from outside of the function.

41
PASSING ARGUMENTS TO A FUNCTION
#include <stdio.h>

There are two ways to pass arguments to a subprogram:


 increment(int x, int* y);
void

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

 There are two ways to pass arguments to a subprogram:


 By reference
 Exercise:
 Write a function to interchange (swap) the value of two variables.
 Example:

printf("i and j before swapping: %d %d\n", i, j); i and j before swapping: 10 20


// function call ... i and j after swapping: 20 10
printf("i and j after swapping: %d %d\n", i, j);

43
PASSING ARGUMENTS TO A FUNCTION

 Arguments to main(): argc and argv


 Sometimes it is useful to pass information into a program when you run it.
 Information can be passed via command line arguments to a main() function.
 A command line argument is the information that follows the program's
name on the command line of the operating system.
 Two special built-in arguments, argc and argv, are used to receive
command line arguments.

44
PASSING ARGUMENTS TO A FUNCTION

 Arguments to main(): argc and argv


 The argc parameter holds the number of arguments on the command line
and it is an integer.
 It is always at least 1, because the name of the program qualifies as the first
argument.

45
PASSING ARGUMENTS TO A FUNCTION

 Arguments to main(): argc and argv


 The argc parameter holds the number of arguments on the command line
and it is an integer.
 It is always at least 1, because the name of the program qualifies as the first
argument.
 The argv parameter is a pointer to an array of character pointers.
 Each element in this array points to a command line argument.
 All command line arguments are strings
 any numbers will have to be converted by the program into the proper binary format,
manually.

46
PASSING ARGUMENTS TO A FUNCTION

 Arguments to main(): argc and argv


 The argc parameter holds the number of arguments on the command line
#include <stdio.h>

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

Functions and variables

Passing arguments to a function

Calling a function: the stack

Recursion

48
CALLING A FUNCTION: THE STACK

 All the information related to a program is stored in memory during


its execution.
 The code and data are stored in different areas.
 The data is stored in a memory area called stack.

49
CALLING A FUNCTION: THE STACK

 Stack: region of the computer's memory that stores temporary


variables created by each function.
 Each time a function is called, a memory area is reserved in the stack in
which all the information is stored: parameters, local data, result, return
address...
 Every time a function declares a new variable, it is pushed onto the stack.
 When the function end, this memory area is freed and all the variables
reserved disappear from the memory
 Local scope of function variables.
 Sometimes the system runs out of memory, causing what is known as a
stack overflow.
50
CALLING A FUNCTION: THE STACK

 Memory map of a C program


 Stack: local variable storage (automatic, continuous
Stack memory).

 Heap: dynamic storage (large pool of memory, not


Heap
allocated in contiguous order).

Static  Static: global variable storage, permanent for the


entire run of the program.
Program code

51
CALLING A FUNCTION: THE STACK

 Example Memory output


#include <stdio.h>

void functionTest(int j);

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

 Example Memory output


#include <stdio.h>

void functionTest(int j);

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

 Example Memory output


#include <stdio.h>

void functionTest(int j);

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

 Example Memory output


#include <stdio.h>

void functionTest(int j);

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

 Example Memory output


#include <stdio.h>

void functionTest(int j);

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

 Example Memory output


#include <stdio.h> 100 102

void functionTest(int j);

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

 Example Memory output


#include <stdio.h> 100 102
10
void functionTest(int j);

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

 Example Memory output


#include <stdio.h> 100 102
10
void functionTest(int j);

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);
}

void increment(int x, int* y)


{
printf("Before2: %d, %d.\n", x, *y);
x = x + 1;
*y = *y + 1;
printf("After2: %d, %d.\n", x, *y);
60
}
CONTENTS

Introduction

Declaring functions

Returning values

Functions and variables

Passing arguments to a function

Calling a function: the stack

Recursion

61
RECURSION

 Recursion is a process by which a function calls itself repeatedly, until


some specified condition has been satisfied.
 The process is used for repetitive computations in which each action is
stated in terms of a previous result.
 In order to solve a problem recursively, two conditions must be
satisfied:
 1) the problem must be written in a recursive form,
 2) the problem statement must include a stopping condition.

62
RECURSION
Memory input
 Example.
#include <stdio.h> n = 3

long Factorial numbers:


 factorial(int n)
{
n!=== 1)1 * 2 * 3 * 4 … * n
 (n
if
return 1;
 n is a positive integer.
else
return n * factorial(n - 1);
 This problem can be specified in a recursive way:
}
 n! = n * (n-1)!
void main()
 Stopping condition:
{
int n;  1! = 1;
printf(“n = ");
scanf("%d", &n);
printf(“%d! = %ld\n", n, factorial(n));
}
63
RECURSION
Memory input
 Example.
#include <stdio.h> n = 3

long Factorial numbers:


 factorial(int n)
{
n!=== 1)1 * 2 * 3 * 4 … * n
 (n
if
return 1;
 n is a positive integer.
else
return n * factorial(n - 1);
 This problem can be specified in a recursive way:
}
 n! = n * (n-1)!
void main()
 Stopping condition:
{
int n;  1! = 1;
printf(“n = ");
scanf("%d", &n);
printf(“%d! = %ld\n", n, factorial(n)); main()
} ????
n = 3
64
RECURSION
Memory input
 Example.
#include <stdio.h> n = 3

long Factorial numbers:


 factorial(int n)
{
n!=== 1)1 * 2 * 3 * 4 … * n
 (n
if
return 1;
 n is a positive integer.
else
return n * factorial(n - 1);
 This problem can be specified in a recursive way:
}
 n! = n * (n-1)!
void main()
 Stopping condition:
{
int n;  1! = 1;
printf(“n = "); factorial()
n = 3 return =
scanf("%d", &n);
printf(“%d! = %ld\n", n, factorial(n)); main()
} ????
n = 3
65
RECURSION
Memory input
 Example.
#include <stdio.h> n = 3

long Factorial numbers:


 factorial(int n)
{
n!=== 1)1 * 2 * 3 * 4 … * n
 (n
if
return 1;
 n is a positive integer.
else
return n * factorial(n - 1);
 This problem can be specified in a recursive way:
}
 n! = n * (n-1)!
void main()
 Stopping condition: factorial()
{ n = 2 return = 2 * ?
int n;  1! = 1;
printf(“n = "); factorial()
n = 3 return = 3 * ?
scanf("%d", &n);
printf(“%d! = %ld\n", n, factorial(n)); main()
} ????
n = 3
66
RECURSION
Memory input
 Example.
#include <stdio.h> n = 3

long Factorial numbers:


 factorial(int n)
{
n!=== 1)1 * 2 * 3 * 4 … * n
 (n
if
return 1;
 n is a positive integer.
else
return n * factorial(n - 1);
 This problem can be specified in a recursive way:
} factorial()
 n! = n * (n-1)! n = 1 return = 1
void main()
 Stopping condition: factorial()
{ n = 2 return = 2 * ?
int n;  1! = 1;
printf(“n = "); factorial()
n = 3 return = 3 * ?
scanf("%d", &n);
printf(“%d! = %ld\n", n, factorial(n)); main()
} ????
n = 3
67
RECURSION
Memory input
 Example.
#include <stdio.h> n = 3

long Factorial numbers:


 factorial(int n)
{
n!=== 1)1 * 2 * 3 * 4 … * n
 (n
if
return 1;
 n is a positive integer.
else
return n * factorial(n - 1);
 This problem can be specified in a recursive way:
} factorial()
 n! = n * (n-1)! n = 1 return = 1
void main()
 Stopping condition: factorial()
{ n = 2 return = 2 * ?
int n;  1! = 1;
printf(“n = "); factorial()
n = 3 return = 3 * ?
scanf("%d", &n);
printf(“%d! = %ld\n", n, factorial(n)); main()
} ????
n = 3
68
RECURSION
Memory input
 Example.
#include <stdio.h> n = 3

long Factorial numbers:


 factorial(int n)
{
n!=== 1)1 * 2 * 3 * 4 … * n
 (n
if
return 1;
 n is a positive integer.
else
return n * factorial(n - 1);
 This problem can be specified in a recursive way:
}
 n! = n * (n-1)!
void main()
 Stopping condition:
factorial()
{ n = 2 return = 2 * 1
?
int n;  1! = 1;
printf(“n = "); factorial()
n = 3 return = 3 * ?
scanf("%d", &n);
printf(“%d! = %ld\n", n, factorial(n)); main()
} ????
n = 3
69
RECURSION
Memory input
 Example.
#include <stdio.h> n = 3

long Factorial numbers:


 factorial(int n)
{
n!=== 1)1 * 2 * 3 * 4 … * n
 (n
if
return 1;
 n is a positive integer.
else
return n * factorial(n - 1);
 This problem can be specified in a recursive way:
}
 n! = n * (n-1)!
void main()
 Stopping condition:
factorial()
{ n = 2 return = 2 * 1
int n;  1! = 1;
printf(“n = "); factorial()
n = 3 return = 3 * 2
?
scanf("%d", &n);
printf(“%d! = %ld\n", n, factorial(n)); main()
} ????
n = 3
70
RECURSION
Memory input
 Example.
#include <stdio.h> n = 3

long Factorial numbers:


 factorial(int n)
{
n!=== 1)1 * 2 * 3 * 4 … * n
 (n
if
return 1;
 n is a positive integer.
else output
return n * factorial(n - 1);
 This problem can be specified in a recursive way: 3! = 6
}
 n! = n * (n-1)!
void main()
 Stopping condition:
{
int n;  1! = 1;
printf(“n = "); factorial()
n = 3 return = 3 * 2
scanf("%d", &n);
printf(“%d! = %ld\n", n, factorial(n)); main()
} ????
n = 3
71
Memory
RECURSION
#include <stdio.h>

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.

You might also like