0% found this document useful (0 votes)
32 views

Computer Programming I: Functions Year 2020-2021

This document discusses functions in C programming. It covers declaring and defining functions, parameter passing by value and reference, and using functions to break problems down into smaller subproblems. The goals are to use functions to build C programs, declare variables with different scopes (global, local, static), and receive command line arguments. It provides examples of function declarations, definitions, and calls. Functions allow for modularity, code reuse, and problem decomposition in C programming.

Uploaded by

Pedro Rodriguez
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Computer Programming I: Functions Year 2020-2021

This document discusses functions in C programming. It covers declaring and defining functions, parameter passing by value and reference, and using functions to break problems down into smaller subproblems. The goals are to use functions to build C programs, declare variables with different scopes (global, local, static), and receive command line arguments. It provides examples of function declarations, definitions, and calls. Functions allow for modularity, code reuse, and problem decomposition in C programming.

Uploaded by

Pedro Rodriguez
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 84

Computer Programming I

Bachelor in Telecommunication Technologies Engineering

Lecture 5
Functions
Year 2020-2021
Goals
• Declare and define functions in C
• Define the scope of a variable
– Declare global, local and static variables
• Distinguish parameter passing to functions by value from
parameter passing by reference
• Build C programs making use of our own functions
• Create C programs that receive command line
arguments:
– argc
– argv[]

Computer Programming I Lecture 5 2


Contents
1. Description
2. Functions with no parameters
a) Inter function communication: local, global and static variables
3. Functions with parameters by value
4. Functions with parameters by reference
a) Command line arguments
5. Recursive Functions
6. Exercises
Computer Programming I Lecture 5 3
Concept of problem reduction
• Top-down design
• Split the problem into smaller subproblems
– Solve the subproblems separately
• Split the subproblems into simpler subproblems
– Keep doing this until the subproblems are trivial

• Solving (programming) trivial subproblems


– Allows to solve more complex subproblems
• And so on, until the original problem is solved

Computer Programming I Lecture 5 4


Concept of problem reduction
• Examples:
– Arithmetic operations: multiplication, division, square
root, etc.
– Mathematical problems resolution: derivatives, integrals,
etc.
– Civil engineering: road construction.
– Software engineering.

Computer Programming I Lecture 5 5


Introduction
Function: independent source code segment able to perform a specific task

problem solution program

problem
subproblem program
function

solution
subproblem function

Computer Programming I Lecture 5 6


Advantages of using functions
• Makes the development and maintenance of programs
easier
– Makes writing and reading programs easier
– Allows for co-working
– Help define responsibilities
• Code reusability
– Allows for the code of a function to be written just once and be
used as many times as needed
• Encapsulation
– How a task has been developed can be ignored. Knowing what it
does is enough
Computer Programming I Lecture 5 7
Function declaration

return_type name (par_type_1, …, par_type_n) ;

Data type that the Function Function’s Mandatory


function returns identifier parameters list semicolon

• Is is also known as prototype


Computer Programming I Lecture 5 8
Function definition No
header semicolon

return_type name (par_type_1 name_par_1,…)


{

[ Variables declaration ]

Function body

Computer Programming I Lecture 5 9


Function definition No
header semicolon

void name (par_type_1 name_par_1,…)

The function [ Variables declaration ]


doesn’t return any
value
Function body

Computer Programming I Lecture 5 10


Function definition No
header semicolon

return_type name (void)


{
The function
[ Variables declaration ]
doesn’t receive any
parameter
Function body

Computer Programming I Lecture 5 11


Function calls
void main (void) {
int op1, op2; int sum (int op1, int op2) {
int result; return (op1+op2);
}
result = sum (op1,op2);
printf ("%d\n", result);

result = sumAbs (op1,op2);


printf ("%d\n", result); int sumAbs (int op1, int op2){
} if (isPositive (op1,op2))
return (op1+op2);
else return (-1*(op2+op1));
}

int isPositive (int op1, int op2) {


if (op1+op2>0) return 1;
else return 0;
}

Computer Programming I Lecture 5 12


Function calls
• Whenever we call a function, 2 consequences can
arise:
• The production of some effect on data or on any
device.
– Examples: printf (), scanf(), …
• The return of a value.
– Examples: sqrt(), toupper(), …
• Both consequences can arise in the same call
– Examples: printf (), scanf(), …
Computer Programming I Lecture 5 13
Function calls
void main (void) {
int op1, op2;
int result; int sum (int op1, int op2) {
return (op1+op2);
result = sum(op1,op2); }
printf ("%d\n", result);

result = sumAbs(op1,op2);
printf ("%d\n", result);
} int sumAbs (int op1, int op2){
if (isPositive (op1,op2))
return (op1+op2);
else return (-1*(op2+op1));
}

Computer Programming I Lecture 5 14


Function calls
void main (void) {
int op1, op2;
sum (op1,op2);
}

void sum (int op1, int op2) {


printf("The sum of the two numbers is: %d\n", op1+op2);
return;
}

Computer Programming I Lecture 5 15


Typical structure of a C program
• Function #1 Declaration
• Function #2 Declaration
• Function #3 Declaration
• …
• Main Program (main() function )
• Function #1 Definition
• Function #2 Definition
• Function #3 Definition
• …
Computer Programming I Lecture 5 16
Typical structure of a C program
#include <stdio.h>

void pause (void); // prototype

int main () {
int counter = 0;
printf ("COUNTER VALUE INSIDE THE while:\n");
while (counter < 10) {
if (counter == 5) pause ();
printf ("%d\n", ++counter);
}
pause ();
printf ("COUNTER VALUE: %d\n", counter);
return 0;
}

void pause (void) {


printf ("\nPRESS ENTER TO CONTINUE: ");
while (fgetc (stdin) != '\n');
}
Computer Programming I Lecture 5 17
Functions that return a value
#include <stdio.h>

finish (void); // prototype


If the return value type is not
main () {
int fin = 0;
specified, it is taken as int by
while (fin == 0) { default.
fin = finish ();
}
return 0;
But a warning is issued!
}

finish (void) {
char c;
printf ("Enter a character: ");
scanf (" %c", &c);
return (c == 'n');
}
Computer Programming I Lecture 5 18
Contents
1. Description
2. Functions with no parameters
a) Inter function communication: local, global and static variables
3. Functions with parameters by value
4. Functions with parameters by reference
a) Command line arguments
5. Recursive Functions
6. Exercises
Computer Programming I Lecture 5 19
Functions with no parameters
• These functions include no declaration of either:
– input data ⇒ void parameters
– output data ⇒ void result
• So, they do not communicate each other
void main ( void ) {

}

void sayHello ( void ) {


printf ("Hello\n");
}

Computer Programming I Lecture 5 20


Functions with no parameters
#include <stdio.h>

void pause (void); // prototype

int main () {
int counter = 0;
printf ("COUNTER VALUE INSIDE THE while:\n");
while (counter < 10) {
if (counter == 5 ) pause ();
printf ("%d\n", ++counter);
}
pause ();
printf ("COUNTER VALUE: %d\n", counter);
return 0;
}

void pause (void) {


printf ("\nPRESS ENTER TO CONTINUE: ");
while (fgetc (stdin) != '\n');
}
Computer Programming I Lecture 5 21
Inter function communication
• However, functions usually need to interchange
information with each other

• Both function-to-function or function-to-main


program communication can be conducted by means
of:
– Global variables
– Parameter passing by value
– Parameter passing by reference

Computer Programming I Lecture 5 22


Communication by means of variables
• scope of a variable: program section where the variable
can be used.
• In C, we can distinguish between 3 kinds of variables
according to their scope:
– Local variables: are defined inside a function and their scope is
the function itself.
• Block local variables.
– Static variables: keep in existence during the lifetime of the
program, maintaining their value.
– Global variables: are defined before the start of the main
program and their scope is the whole program.
Computer Programming I Lecture 5 23
Communication by means of variables
Kind Reserved word Where is it scope Lifetime Keep its
declared? value?
Local None or auto Inside the Only inside the While the function No
function function where it is is running
declared
Static static Inside the Only inside the The whole lifetime Yes
function function where it is of the program
declared
Global None Outside any The whole program The whole lifetime Yes
function of the program

Computer Programming I Lecture 5 24


Inter function communication
Local variables
#include <stdio.h>
#include <stdlib.h>

int cube (int num); // CUBE function prototype

int main (void) {


int cubed; // main() LOCAL variable
int i; // main() LOCAL variable
for (i=1; i<10; i++){
cubed = cube (i);
printf ("%d cubed is: %d\n", i, cubed);
}
return 0;
}

int cube (int num) {


int numCalls = 0; // cube() LOCAL variable
numCalls++;
printf ("Number of calls to cube function: %d\n", numCalls);
return (num*num*num);
}

Computer Programming I Lecture 5 25


Inter function communication
Local variables
#include <stdio.h>
#include <stdlib.h>

int cube (int num); // CUBE function prototype

int main (void) {


int cubed; // main() LOCAL variable
int i; // main() LOCAL variable
for (i=1; i<10; i++){
cubed = cube (i); Number of calls to cube function: 1
printf ("%d cubed is: %d\n", i, cubed);
} 1 cubed is: 1
}
return 0;
Number of calls to cube function: 1
int cube (int num) {
2 cubed is: 8
int numCalls = 0; // cube() LOCAL variable Number of calls to cube function: 1
numCalls++;
printf ("Number of calls to cube function: %d\n", numCalls); 3 cubed is: 27
}
return (num*num*num);
Number of calls to cube function: 1
4 cubed is: 64

Computer Programming I Lecture 5 26
Inter function communication
Local variables
#include <stdio.h>
#include <stdlib.h>

int cube (int num); // CUBE function prototype

int main (void) {


int cubed; // main() LOCAL variable
int i; // main() LOCAL variable
for (i=1; i<10; i++){
Compilation ERROR
cubed = cube (i);
printf ("%d cubed is: %d\n", i, cubed);
printf ("Number of calls to cube function: %d\n", numCalls);
}
return 0;
}

int cube (int num) {


int numCalls = 0; // cube() LOCAL variable
numCalls++;
return (num*num*num);
}

Computer Programming I Lecture 5 27


Inter function communication
Static variables
#include <stdio.h>
#include <stdlib.h>

int cube (int num); // CUBE function prototype

int main (void) {


int cubed; // main() LOCAL variable
int i; // main() LOCAL variable
for (i=1; i<10; i++){
cubed = cube (i);
printf ("%d cubed is: %d\n", i, cubed);
}
return 0;
}

int cube (int num) {


static int numCalls = 0; // cube() STATIC variable
numCalls++;
printf ("Number of calls to cube function: %d\n", numCalls);
return (num*num*num);
}

Computer Programming I Lecture 5 28


Inter function communication
Static variables
#include <stdio.h>
#include <stdlib.h>

int cube (int num); // CUBE function prototype

int main (void) {


int cubed; // main() LOCAL variable
int i; // main() LOCAL variable
for (i=1; i<10; i++){
cubed = cube (i); Number of calls to cube function: 1
printf ("%d cubed is: %d\n", i, cubed);
} 1 cubed is: 1
}
return 0;
Number of calls to cube function: 2
int cube (int num) {
2 cubed is: 8
static int numCalls = 0; // cube() STATIC variable Number of calls to cube function: 3
numCalls++;
printf ("Number of calls to cube function: %d\n", numCalls); 3 cubed is: 27
}
return (num*num*num);
Number of calls to cube function: 4
4 cubed is: 64

Computer Programming I Lecture 5 29
Inter function communication
Static variables
#include <stdio.h>
#include <stdlib.h>

int cube (int num); // CUBE function prototype

int main (void) {


int cubed; // main() LOCAL variable
int i; // main() LOCAL variable
for (i=1; i<10; i++){
Compilation ERROR
cubed = cube (i);
printf ("%d cubed is: %d\n", i, cubed);
printf ("Number of calls to cube function: %d\n", numCalls);
}
return 0;
}

int cube (int num) {


static int numCalls = 0; // cube() STATIC variable
numCalls++;
return (num*num*num);
}

Computer Programming I Lecture 5 30


Inter function communication
Global variables
#include <stdio.h>
#include <stdlib.h>

int i; // GLOBAL variable


int numCalls = 0; // GLOBAL variable
int cube (int num); // CUBE function prototype

int main (void) {


int cubed; // LOCAL variable
for (i=1; i<10; i++){
cubed = cube (i);
printf ("%d cubed is: %d\n", i, cubed);
}
return 0;
}

int cube (int num) {


numCalls++;
printf ("Number of calls to cube function: %d\n", numCalls);
return (num*num*num);
}
Computer Programming I Lecture 5 31
Inter function communication
Global variables
#include <stdio.h>
#include <stdlib.h>

int i; // GLOBAL variable


int numCalls = 0;
int cube (int num);
// GLOBAL variable
// CUBE function prototype
Number of calls to cube function: 1
1 cubed is: 1
int main (void) {
int cubed; // main() LOCAL variable
Number of calls to cube function: 2
for (i=1; i<10; i++){ 2 cubed is: 8
cubed = cube (i);
printf ("%d cubed is: %d\n", i, cubed);
Number of calls to cube function: 3
} 3 cubed is: 27
return 0; Number of calls to cube function: 4
}
4 cubed is: 64
int cube (int num) { …
numCalls++;
printf ("Number of calls to cube function: %d\n", numCalls);
return (num*num*num);
}
Computer Programming I Lecture 5 32
Inter function communication
Global variables
#include <stdio.h>
#include <stdlib.h>

int i; // GLOBAL variable


int numCalls = 0; // GLOBAL variable
int cube (int num); // CUBE function prototype

int main (void) {


int cubed; // main() LOCAL variable
for (i=1; i<10; i++){
cubed = cube (i);
printf ("Number of calls to cube function: %d\n", numCalls);
printf ("%d cubed is: %d\n", i, cubed);
}
return 0;
}

int cube (int num) {


numCalls++;
return (num*num*num);
}
Computer Programming I Lecture 5 33
Inter function communication
Number of calls to cube function: 1
Global variables 1 cubed is: 1
#include <stdio.h> Number of calls to cube function: 2
#include <stdlib.h>
2 cubed is: 8
int i; // GLOBAL variable Number of calls to cube function: 3
int numCalls = 0; // GLOBAL variable
int cube (int num); // CUBE function prototype 3 cubed is: 27
Number of calls to cube function: 4
int main (void) {
int cubed; // main() LOCAL variable 4 cubed is: 64
for (i=1; i<10; i++){ …
cubed = cube (i);
printf ("Number of calls to cube function: %d\n", numCalls);
printf ("%d cubed is: %d\n", i, cubed);
}
return 0;
}

int cube (int num) {


numCalls++;
return (num*num*num);
}
Computer Programming I Lecture 5 34
Variable names conflicts
• Local variables have higher priority than global variables
with the same name.
• If a global and a function’s local variable have the same
name, then inside that function, that name makes
reference to the local variable.
• Likewise, if a variable declared in an internal block and
another one declared in an external block have the same
name, then, inside the internal block, that name makes
reference to the internal variable.
Computer Programming I Lecture 5 35
Inter function communication
Global variables / local variables
#include <stdio.h>
#include <stdlib.h>

int i; // GLOBAL variable


int numCalls = 0; // GLOBAL variable
int cube (void); // CUBE function prototype

int main (void) {


int cubed; // main() LOCAL variable
for (i=1; i<10; i++){
cubed = cube ();
printf ("Number of calls to cube function: %d\n", numCalls);
printf("%d cubed is: %d\n", i, cubed);
}
return 0;
}

int cube (void) {


int i = 2; // cube() LOCAL variable
numCalls++;
return (i * i * i);
}

Computer Programming I Lecture 5 36


Inter function communication
Global variables / local variables
#include <stdio.h>
#include <stdlib.h>

int i; // GLOBAL variable


int numCalls = 0; // GLOBAL variable
int cube (void); // CUBE function prototype

int main (void) {


int cubed; // main() LOCAL variable
for (i=1; i<10; i++){ Number of calls to cube function: 1
1 cubed is: 8
cubed = cube ();
printf ("Number of calls to cube function: %d\n", numCalls);
printf("%d cubed is: %d\n", i, cubed); Number of calls to cube function: 2
}
return 0; 2 cubed is: 8
}
Number of calls to cube function: 3
int cube (void) { 3 cubed is: 8
int i = 2; // cube() LOCAL variable
numCalls++;
Number of calls to cube function: 4
return (i * i * i); 4 cubed is: 8
}

Computer Programming I Lecture 5 37
Caution with global variables!
• The use of global variables is prone to errors.
• Main problem: side effects
– As any function can change the value of a global variable, the possible
effects of a change of value can affect a much bigger portion of the
program than if the variable was local.
– The program can undergo unwanted alterations of the variable
contents.
• Global variables make programs more complex.
– And much less readable.
• Threaten the modularity requirements.
– Can make program useful just for a specific set of cases

Computer Programming I Lecture 5 38


Contents
1. Description
2. Functions with no parameters
a) Inter function communication: local, global and static variables
3. Functions with parameters by value
4. Functions with parameters by reference
a) Command line arguments
5. Recursive Functions
6. Exercises
Computer Programming I Lecture 5 39
Parameter passing by value
• The invoked function receives the values for its
parameters in local variables (of the invoked function
itself) and not in the original ones (of the caller function).
• The contents of the original variables are copied to the
local ones.
• The invoked function cannot modify the contents of the
original variables.
• This is the default way for parameter passing to a
function.
Computer Programming I Lecture 5 40
Parameter passing by value
• It is not even necessary that what is passed as a
parameter by the caller function to be a variable:
– It can be a variable
– It can be a constant value
– It can be an expression as complex as needed
– As long as it can be evaluated to a value of the same type as the
variable in the invoked function
• The variable in the invoked function is known as: formal
parameter
• The value that is passed by the caller function is known
as: actual parameter
Computer Programming I Lecture 5 41
Parameter passing by value
• The formal parameter is a local variable of the function,
initialized to the value of the actual parameter

Formal parameter

Actual parameter

Computer Programming I Lecture 5 42


Parameter passing by value
• When we pass a parameter by value, the formal parameter is
initialized to the value that is passed when calling the function
– Any modification that the function performs on the formal parameter
will not be visible from outside the function

Computer Programming I Lecture 5 43


Parameter passing by value
• What’s the difference between x, y and z?
• All of them act as local variables of function(), but each time function() is executed:

x) is created, and initialized to the value 10


y) is created, but not initialized
z) is created, and initialized to the value
passed by main():
1) value = 25
2) value = the value of i
• Afterwards, inside function(), all of them can
be read and modified
• But their changes will not be reflected
outside function()
Computer Programming I Lecture 5 44
Parameter passing by value
#include <stdio.h> i $$
#include <stdlib.h>
j $$
int opValue (int a, int b); // prototype

int main (void) {


int i, j;

i = 3;
j = 5;
printf ("opValue result: %d\n", opValue (i, j));
printf ("First operand: %d\nSecond operand: %d\n", i, j);
return 0;
}

int opValue (int a, int b) {


a = a + a;
b = b + a;
return b;
}
Computer Programming I Lecture 5 45
Parameter passing by value
#include <stdio.h> i 3
#include <stdlib.h>
j 5
int opValue (int a, int b); // prototype

int main (void) {


int i, j;
i = 3;
j = 5;

printf ("opValue result: %d\n", opValue (i, j));


printf ("First operand: %d\nSecond operand: %d\n", i, j);
return 0;
}

int opValue (int a, int b) {


a = a + a;
b = b + a;
return b;
}
Computer Programming I Lecture 5 46
Parameter passing by value
#include <stdio.h> i 3
#include <stdlib.h>
j 5
int opValue (int a, int b); // prototype

int main (void) {


int i, j;
3 5
i = 3;
j = 5;
printf ("opValue result: %d\n", opValue (i, j));

printf ("First operand: %d\nSecond operand: %d\n", i, j);


return 0;
}

int opValue (int a, int b) {


a = a + a;
b = b + a;
return b;
}
Computer Programming I Lecture 5 47
Parameter passing by value
#include <stdio.h> i 3
#include <stdlib.h>
j 5
int opValue (int a, int b); // prototype

int main (void) {


int i, j;
i = 3;
j = 5; a 3
printf ("opValue result: %d\n", opValue (i, j));
printf ("First operand: %d\nSecond operand: %d\n", i, j); b 5
return 0;
}

int opValue (int a, int b) {

a = a + a;
b = b + a;
return b;
}
Computer Programming I Lecture 5 48
Parameter passing by value
#include <stdio.h> i 3
#include <stdlib.h>
j 5
int opValue (int a, int b); // prototype

int main (void) {


int i, j;
i = 3;
j = 5; a 63
printf ("opValue result: %d\n", opValue (i, j));
printf ("First operand: %d\nSecond operand: %d\n", i, j); b 5
return 0;
}

int opValue (int a, int b) {


a = a + a;

b = b + a;
return b;
}
Computer Programming I Lecture 5 49
Parameter passing by value
#include <stdio.h> i 3
#include <stdlib.h>
j 5
int opValue (int a, int b); // prototype

int main (void) {


int i, j;
i = 3;
j = 5; a 6
printf ("opValue result: %d\n", opValue (i, j));
printf ("First operand: %d\nSecond operand: %d\n", i, j);
return 0;
b 11
5
}

int opValue (int a, int b) {


a = a + a;
b = b + a;

return b;
}
Computer Programming I Lecture 5 50
Parameter passing by value
#include <stdio.h> i 3
#include <stdlib.h>
j 5
int opValue (int a, int b); // prototype

int main (void) {


int i, j;
i = 3;
j = 5; a 6
printf ("opValue result: %d\n", opValue (i, j));
printf ("First operand: %d\nSecond operand: %d\n", i, j); b 11
return 0;
}

int opValue (int a, int b) {


a = a + a;
b = b + a;
return b;
}
Computer Programming I Lecture 5 51
Parameter passing by value
#include <stdio.h> i 3
#include <stdlib.h>
j 5
int opValue (int a, int b); // prototype

int main (void) {


int i, j;
i = 3;
j = 5; a 6
printf ("opValue result: %d\n", opValue (i, j));

printf ("First operand: %d\nSecond operand: %d\n", i, j);


b 11
return 0;
}

int opValue (int a, int b) {


opValue result: 11
a = a + a;
b = b + a;
return b;
}
Computer Programming I Lecture 5 52
Parameter passing by value
#include <stdio.h> i 3
#include <stdlib.h>
j 5
int opValue (int a, int b); // prototype

int main (void) {


int i, j;
i = 3;
j = 5; a 6
printf ("opValue result: %d\n", opValue (i, j));
printf ("First operand: %d\nSecond operand: %d\n", i, j); b 11
return 0;
}

int opValue (int a, int b) { First operand: 3


a = a + a;
b = b + a; Second operand: 5
return b;
}
Computer Programming I Lecture 5 53
Contents
1. Description
2. Functions with no parameters
a) Inter function communication: local, global and static variables
3. Functions with parameters by value
4. Functions with parameters by reference
a) Command line arguments
5. Recursive Functions
6. Exercises
Computer Programming I Lecture 5 54
Parameter passing by reference
• It is based on the use of pointers. The parameters passed
are pointers.
• Parameter passing is still carried out by copying the
contents of the original variables (of the caller function)
to the local variables (of the invoked function).
• However, the copied values are memory addresses, that
is, the contents of the pointers.

Computer Programming I Lecture 5 55


Parameter passing by reference
• Now it is necessary that what is passed as a parameter by the
caller function is (the address of) a variable:
• The variable in the invoked function is known as: formal
parameter
• The value that is passed (that is, the address that is passed) by
the caller function is known as: actual parameter
• Here, the formal parameter is also a local variable in the
function, initialized to the value of the actual parameter
– But, now, the actual parameter contains the address of a variable in
the caller function

Computer Programming I Lecture 5 56


Parameter passing by reference
• When we pass a parameter by reference, the formal
parameter is initialized to the address of the variable that is
passed when calling the function
– The function can modify the variable whose address has been passed

Computer Programming I Lecture 5 57


Parameter passing by reference
#include <stdio.h> i $$
#include <stdlib.h>
j $$
int opReference (int *c, int *d); // prototype

int main (void) {


int i,j;

i = 3;
j = 5;
printf ("opReference result: %d\n", opReference(&i,&j));
printf ("First operand: %d\nSecond operand %d\n",i, j);
return 0;
}

int opReference (int *c, int *d) {


*c = *c + *c;
*d = *d + *c;
return *d;
}
Computer Programming I Lecture 5 58
Parameter passing by reference
#include <stdio.h> i 3
#include <stdlib.h>
j 5
int opReference (int *c, int *d); // prototype

int main (void) {


int i,j;
i = 3;
j = 5;

printf ("opReference result: %d\n", opReference(&i,&j));


printf ("First operand: %d\nSecond operand %d\n",i, j);
return 0;
}

int opReference (int *c, int *d) {


*c = *c + *c;
*d = *d + *c;
return *d;
}
Computer Programming I Lecture 5 59
Parameter passing by reference
#include <stdio.h> i 3
#include <stdlib.h>
j 5
int opReference (int *c, int *d); // prototype
j’s address
int main (void) { i’s address
int i,j;
i = 3;
j = 5;
printf ("opReference result: %d\n", opReference(&i,&j));

printf ("First operand: %d\nSecond operand %d\n",i, j);


return 0;
}

int opReference (int *c, int *d) {


*c = *c + *c;
*d = *d + *c;
return *d;
}
Computer Programming I Lecture 5 60
Parameter passing by reference
#include <stdio.h> i 3
#include <stdlib.h>
j 5
int opReference (int *c, int *d); // prototype

int main (void) {


int i,j;
i = 3;
j = 5; c &i
printf ("opReference result: %d\n", opReference(&i,&j));
printf ("First operand: %d\nSecond operand %d\n",i, j); d &j
return 0;
}

int opReference (int *c, int *d) {

*c = *c + *c;
*d = *d + *c;
return *d;
}
Computer Programming I Lecture 5 61
Parameter passing by reference
#include <stdio.h> i 36
#include <stdlib.h>
j 5
int opReference (int *c, int *d); // prototype

int main (void) {


int i,j;
i = 3;
j = 5; c &i
printf ("opReference result: %d\n", opReference(&i,&j));
printf ("First operand: %d\nSecond operand %d\n",i, j); d &j
return 0;
}

int opReference (int *c, int *d) {


*c = *c + *c;

*d = *d + *c;
return *d;
}
Computer Programming I Lecture 5 62
Parameter passing by reference
#include <stdio.h> i 6
#include <stdlib.h>
j 11
5
int opReference (int *c, int *d); // prototype

int main (void) {


int i,j;
i = 3;
j = 5; c &i
printf ("opReference result: %d\n", opReference(&i,&j));
printf ("First operand: %d\nSecond operand %d\n",i, j); d &j
return 0;
}

int opReference (int *c, int *d) {


*c = *c + *c;
*d = *d + *c;

return *d;
}
Computer Programming I Lecture 5 63
Parameter passing by reference
#include <stdio.h> i 6
#include <stdlib.h>
j 11
int opReference (int *c, int *d); // prototype

int main (void) {


int i,j;
i = 3;
j = 5; c &i
printf ("opReference result: %d\n", opReference(&i,&j));
printf ("First operand: %d\nSecond operand %d\n",i, j); d &j
return 0;
}

int opReference (int *c, int *d) {


*c = *c + *c;
*d = *d + *c;
return *d;

}
Computer Programming I Lecture 5 64
Parameter passing by reference
#include <stdio.h> i 6
#include <stdlib.h>
j 11
int opReference (int *c, int *d); // prototype

int main (void) {


int i,j;
i = 3;
j = 5; c &i
printf ("opReference result: %d\n", opReference(&i,&j));
d &j
printf ("First operand: %d\nSecond operand %d\n",i, j);
return 0;
}

int opReference (int *c, int *d) {


*c = *c + *c;
*d = *d + *c;
return *d; opReference result: 11
}
Computer Programming I Lecture 5 65
Parameter passing by reference
#include <stdio.h> i 6
#include <stdlib.h>
j 11
int opReference (int *c, int *d); // prototype

int main (void) {


int i,j;
i = 3;
j = 5; c &i
printf ("opReference result: %d\n", opReference(&i,&j));
printf ("First operand: %d\nSecond operand %d\n",i, j); d &j
return 0;
}

int opReference (int *c, int *d) {


*c = *c + *c;
*d = *d + *c;
First operand: 6
}
return *d; Second operand: 11
Computer Programming I Lecture 5 66
Beware the precedence!
• * has the same precedence as ++ and --
– but they are evaluated from right to left
• *p++ is evaluated as if it was: *(p++)
– takes the value of pointer p
– uses it to get the value of the variable it points to
– fterwards, increments pointer p
• If that’s not what we want, we must use parentheses:
• (*p)++
– takes the value of pointer p
– uses it to get the value of the variable it points to
– afterwards, increments that variable
• However, ++*p is evaluated as if it was: ++(*p)
Computer Programming I Lecture 4 67
Array type parameter passing
type name[N];
• When a function has an array type parameter:
• The function declaration can take 2 forms:
function (type param[]);
function (type *param);
• In both cases, the function call is carried out by:
function (name);
– The passed value is the address of the array’s first element.
– A copy of the array’s elements is NOT passed.
– Remember that name is equivalent to &(name[0])

Computer Programming I Lecture 5 68


Example: passing by value
#include <stdio.h>

void fn (int); // prototype

int main() {
int i = 0;
fn (i);
printf ("PASSING BY VALUE: The value of i is %d\n", i);
return 0;
}

void fn (int j) {
printf ("The value of j is %d\n", j);
j = 10;
}

Computer Programming I Lecture 5 69


Example: passing by reference
#include <stdio.h>

void fn (int *); // prototype

int main() {
int i = 0;
fn (&i);
printf ("PASSING BY REFERENCE: The value of i is %d\n", i);
return 0;
}

void fn (int *j) {


printf ("The value of j is %d\n", *j);
*j = 10;
}

Computer Programming I Lecture 5 70


Example: array as a parameter
#include <stdio.h>

void fn (int, int *); // prototype

int main(){
int array[10];
int pos = 4;
fn (pos, array);
printf ("The position %d is %d\n", pos, array[pos]);
return 0;
}

void fn (int pos2, int *pArray) {


printf ("The position %d is %d\n", pos2, pArray[pos2]);
pArray[pos2] = 10;
}
Computer Programming I Lecture 5 71
Example: string as a parameter
#include <stdio.h>

void printChars (const char *); // prototype

int main () {
char sentence[] = "Hello World";
printChars (sentence);
return 0;
}

void printChars (const char *ptrStr) {


// Careful! empty initialization expression in this for
for ( ; *ptrStr != '\0'; ptrStr++)
printf ("%c", *ptrStr);
printf ("\n");
}
Computer Programming I Lecture 5 72
Command line arguments
• The parameters received by the main() function :
int main (int argc, char *argv[]) {…}
• argc: number of arguments received by the main
program from the command line
– includes the program name => always will be >= 1
• argv: list of argument values received by the main
program (it is an array of strings)
– argv[0] is the program name (mandatory argument)
– argv[1] .. argv[n] : optional arguments
Computer Programming I Lecture 5 73
Command line arguments
#include <stdio.h>

// print_args: displays the number of arguments


// received from the command line, as well as
// the list of the received argument values.

int main (int argc, char *argv[]) {


int i;

printf ("The number of arguments is: %d\n", argc);


printf ("The program name is: %s\n", argv[0]);
for (i = 1; i < argc; i++) {
printf ("Argument number %d is: %s\n", i, argv[i]);
}
return 0;
}
Computer Programming I Lecture 5 74
Command line arguments
• If we save the program as: print_args.c
• And compile it: gcc –Wall print_args.c –o print_args
INPUT:
$ ./print_args "one argument, several words" 8

OUTPUT:
The number of arguments is: 2 8
The program name is: ./print_args 8
Argument number 1 is: one argument, several words 8

Computer Programming I Lecture 5 75


Command line arguments
INPUT:
$ ./print_args several words, several arguments 8

OUTPUT:
The number of arguments is: 5 8
The program name is: ./print_args 8
Argument number 1 is: several 8
Argument number 2 is: words, 8
Argument number 3 is: several 8
Argument number 4 is: arguments 8
Computer Programming I Lecture 5 76
Contents
1. Description
2. Functions with no parameters
a) Inter function communication: local, global and static variables
3. Functions with parameters by value
4. Functions with parameters by reference
a) Command line arguments
5. Recursive Functions
6. Exercises
Computer Programming I Lecture 5 77
Recursive Functions
• An object is recursive when it is defined as a function of
itself:
𝑁! = 𝑁 × 𝑁 − 1 ! ,𝑁 > 0
𝑎! = 𝑎 ×𝑎!"# ,𝑏 > 0
& &"#
- 𝑎$ = 𝑎& + - 𝑎$
$%# $%#

• Recursive function: one that invokes itself


Computer Programming I Lecture 5 78
Recursive Functions
• Each invocation runs a new copy of the function
• Each copy is an independent function:
– Its local variables and its parameters are different
• Fundamental elements:
– The relation between each step and the following one
– The termination condition: otherwise => infinite recursion

1 , 𝑖𝑓 𝑁 ≤ 1
𝑁! = /
𝑁× 𝑁−1 ! , 𝑖𝑓 𝑁 > 1

Computer Programming I Lecture 5 79


Recursive Functions. Factorial
#include <stdio.h>

unsigned int factorial (unsigned int num) {


if (num > 1)
return (num * factorial (num - 1));
else
return 1;
}

int main (void) {


unsigned int number, result;

printf ("Enter a number: ");


scanf ("%u", number);

result = factorial (number);


printf ("%u factorial is %u\n", number, result);
return 0;
}
Computer Programming I Lecture 5 80
Contents
1. Description
2. Functions with no parameters
a) Inter function communication: local, global and static variables
3. Functions with parameters by value
4. Functions with parameters by reference
a) Command line arguments
5. Recursive Functions
6. Exercises
Computer Programming I Lecture 5 81
Exercises
• Build the flow chart and implement, using C language, the
following functions:
– strlen()
– strchr()
– strcpy()
– strcat()
– strncpy()
– strncat()
– isdigit()
– isalfa()
• Justify the parameters choice and if the parameters passing
must be done by value or by reference
Computer Programming I Lecture 5 82
strlen() / strcpy() / isalpha()
unsigned int strlen (const char *cad) {
unsigned int count = 0; In fact, size_t,
while (cad[i] != '\0’) count++;
return count; instead of unsigned int
}

char *strcpy (char *destination, const char *origin) {


int i = 0;
while (origin[i] != '\0') {
destination[i] = origin[i];
i++;
}
destination[i] = '\0';
return destination;
}

int isalpha (char car) {


if (((car >= 'a') && (car <= 'z')) || ((car >= 'A') && (car <= 'Z')))
return 1;
else return 0;
}

Computer Programming I Lecture 5 83


References
• Brian W. Kernighan & Dennis M. Ritchie, The C
Programming Language, 1995, Prentice Hall.
• Learn C Programming,
https://www.tutorialspoint.com/cprogramming/
• Osvaldo Cairó Battistutti, Fundamentos de Programación.
Piensa en C, 1996, Pearson Educación.
• Learn C Programming,
https://www.programiz.com/c-programming
• James L. Antonakos, Kenneth C. Mansfield Jr.,
Programación Estructurada en C, 2004, Prentice Hall.
Computer Programming I Lecture 5 84

You might also like