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

Lecture 08

Uploaded by

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

Lecture 08

Uploaded by

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

Introduction to Computing

Lecture 08:
Functions (Part I)

Assist.Prof.Dr. Nükhet ÖZBEK


Ege University
Department of Electrical & Electronics Engineering
nukhet.ozbek@ege.edu.tr
Topics

• Uses of functions
• Functions
• Parameters
• Return values
Uses of functions

• Top-Down design or divide-and-conquer


– It is easier to solve multiple smaller problems
instead of one big problem
Top-down design
• Suppose, we want to list parts of an automobile
– Automobile self starter
– Bench seat
– Brakes
– Bumper
– Buzzer
– Car battery
– Car doors
– Stop lamp
– Clutch
– Dashboard
– Exhaust pipe
– Fuel pump
– Grille
– Headlight
– Muffler
– Odometer
– …
Top-down design
• It is easier to first divide the problem into
sub problems:
– Chassis
– Motor parts
– Electronic parts
–…
• and then, list the parts under sub
categories
Uses of functions

• Top-Down design or divide-and-conquer


– It is easier to solve multiple smaller problems
instead of one big problem
– It is easier to debug sub problems
• In case of an error, it is easy to isolate the
problem to a specific section of code (a specific
function)
Uses of functions

• Top-Down design or divide-and-conquer


– It is easier to solve multiple smaller problems
instead of one big problem
– It is easier to debug sub problems
– A team of programmers can work on different
sub problems and join sub problems later to
form the solution
Uses of functions

• Top-Down design or divide-and-conquer


– It is easier to solve multiple smaller problems
instead of one big problem
– It is easier to debug sub problems
– A team of programmers can work on different
sub problems and join sub problems later to
form the solution
• Code reuse
Code reuse

• Suppose we want to find ab and cd


power1 = 1;
for (count = b ; count > 0 ; count--)
power1 *= a;
power2 = 1;
for (count = d ; count > 0 ; count--)
power2 *= c;
Code reuse
• Suppose we want to find ab and cd
power1 = power(a,b);
power2 = power(c,d);
• No need to write the same code each time if we
use functions
• We can also use this function in another
program, either simply by copy-paste or adding
it to a user defined library as we will see later
User-Defined Functions

• Can create your own functions, similar to


printf() or sqrt()
• Implements the subroutine/ procedure/
module/ function definitions of an
algorithm
Writing User-defined Functions
• Need to specify:
– the name of the function
– its parameters (input arguments)
– what it returns (output arguments)
– block of statements to be carried out when
the function is called
• The block of statements is called the
“function body”
Writing User-defined Functions

type-specifier function_name(parameter list)


{
body of function
}
• type-specifier is the type of value the function
returns using the return statement
– Can be any valid type
– If no type specified, assumes int
– Can be void -> does not return anything
Example: hello1.c

Prints a simple greeting.

procedure sayHello
{
output “Hello World!”
}

Main Program
{

do procedure sayHello

}
Example: hello1.c #include <stdio.h>

/*
Prints a simple greeting. * Print a simple greeting.
*/

void sayHello ( void )


procedure sayHello {
{
printf(“Hello World!\n”);
output “Hello World!”
} }

/*
* Call a function which prints a
* simple greeting.
*/

int main()
Main Program
{ {

do procedure sayHello sayHello();

return 0;
} }
Example: hello1.c #include <stdio.h>

/*
* Print a simple greeting.
*/

void sayHello ( void )


Function {
definition }
printf(“Hello World!\n”);

/*
* Call a function which prints a
* simple greeting.
*/

int main()
{

Function call sayHello();

return 0;
}
Example: hello1.c #include <stdio.h>

/*
Function * Print a simple greeting.
*/
name
void sayHello ( void )
{
Function body printf(“Hello World!\n”);
}

/*
* Call a function which prints a
* simple greeting.
*/

int main()
{

sayHello();

return 0;
}
Example: hello1.c #include <stdio.h>

/*
Return type * Print a simple greeting.
*/

void sayHello ( void )


{
printf(“Hello World!\n”);
}

/*
Formal * Call a function which prints a
* simple greeting.
Parameter List */

int main()
{

sayHello();

return 0;
}
Parameters
• Information passed to a function
• “Formal” parameters are local variables
declared in the function declaration
• “Actual” parameters are variables or
values passed to the function when it is
called
Example:
badsort.c

/* Print two numbers in order. */

void badSort ( int a, int b )


{

if ( a > b )
{
printf("%d %d\n", b, a);
Parameters (aka
} Arguments)
else
{
printf("%d %d\n", a, b);
}
}
Example: badsort2.c

/* Print two numbers in order. */

void badSort ( a, b )
int a; Old style.
int b;
{

if ( a > b )
{
printf("%d %d\n", b, a);
}
else
{
printf("%d %d\n", a, b);
}
}
Example:
badsort.c

/* Print two numbers in order. */

void badSort ( int a, int b )


{

if ( a > b )
{
printf("%d %d\n", b, a);
}
else
{
printf("%d %d\n", a, b);
}
}
Example:
badsort.c Formal
parameters
/* Print two numbers in order. */

void badSort ( int a, int b )


{ Actual
if ( a > b ) parameters
{
printf("%d %d\n", b, a);
}
else int main()
{ {
printf("%d %d\n", a, b); int x = 3, y = 5;
}
} badSort ( 10, 9 );
badSort ( y, x + 4 );
return 0;
}
Parameters (cont.)

• Parameters are passed by copying the


value of the actual parameters to the
formal parameters
• Changes to formal parameters do not
affect the value of the actual parameters
• This type of function call is called call-by-
value
Example: badswap.c
int main()
/* Swap the values of two variables. */ {
int a = 3, b = 5;
void badSwap ( int a, int b )
{ printf("%d %d\n", a, b);
int temp; badSwap ( a, b );
printf("%d %d\n", a, b);
temp = a;
a = b; return 0;
b = temp; }

printf("%d %d\n", a, b);


}
Example: badswap.c
int main()
/* Swap the values of two variables. */ {
int a = 3, b = 5;
void badSwap ( int a, int b )
{ printf("%d %d\n", a, b);
int temp; badSwap ( a, b );
printf("%d %d\n", a, b);
temp = a;
a = b; return 0;
b = temp; }

printf("%d %d\n", a, b);


}

Output: 3 5
Example: badswap.c
int main()
/* Swap the values of two variables. */ {
int a = 3, b = 5;
void badSwap ( int a, int b )
{ printf("%d %d\n", a, b);
int temp; badSwap ( a, b );
printf("%d %d\n", a, b);
temp = a;
a = b; return 0;
b = temp; }

printf("%d %d\n", a, b);


}

Output: 3 5
5 3
Example: badswap.c
int main()
/* Swap the values of two variables. */ {
int a = 3, b = 5;
void badSwap ( int a, int b )
{ printf("%d %d\n", a, b);
int temp; badSwap ( a, b );
printf("%d %d\n", a, b);
temp = a;
a = b; return 0;
b = temp; }

printf("%d %d\n", a, b);


}

Output: 3 5
5 3
3 5
Example: badswap.c
int main()
/* Swap the values of two variables. */ {
int a = 3, b = 5;
void badSwap ( int a, int b )
{ printf("%d %d\n", a, b);
int temp; badSwap ( a, b );
printf("%d %d\n", a, b);
temp = a;
a = b; return 0;
b = temp; }

printf("%d %d\n", a, b);


}

Called function’s Calling function’s


environment: environment:
a: 5 a: 3
b: 3 b: 5
Parameters (cont.)
• If a function does not take parameters,
declare its formal argument list void or
do not write anything.
void sayHello ( void )
{
Declaration: printf(“Hello World!\n”);
}

void sayHello ()
{
Also valid: printf(“Hello World!\n”);
}

Function call: sayHello();


Parameters (cont.)

• The number of actual arguments used in a


call to a function must be the same as the
number of formal parameters listed in the
function definition
• The order of arguments in the lists
determines correspondence. The first
actual argument corresponds to the first
formal parameter, and so on.
Parameters (cont.)

• Each actual argument must be of a data


type that can be assigned to the
corresponding formal parameter
Functions – “Do”s and “Don’t”s
• DO use a function name that describes the
purpose of the function
• DON'T pass values to a function that it doesn't
need
• DON'T try to pass fewer (or more) arguments
to a function than there are parameters. In C
programs, the number of arguments passed
must match the number of parameters
Return from a Function

• When the last statement is executed


void sayHello ( void )
{
printf(“Hello World!\n”);
}

• When a return statement is encountered


int max (int a, int b)
{
if(a>b) return a; Notice there can be
return b;
} multiple return
statements
Return Values

• Values are returned by copying a value


specified after the return keyword
• All functions, except those of type void,
return a value
Example:
maxmin.c
Return type /* Returns the larger of two numbers. */

int max (int a, int b)


{
int result;

if (a > b)
{
result = a;
}
else
{
result = b;
}

return result;
}
Example:
maxmin.c
/* Returns the larger of two numbers. */

int max (int a, int b)


{
int result;
For example:
if (a > b)
{
result = a; The value of the
}
else
expression
{
result = b; max(7,5)
}

return result;
is the integer 7.
}
Example:
maxmin.c
This style okay. /* Returns the larger of two numbers. */

int
max (int a, int b)
{
int result;

if (a > b)
{
result = a;
}
else
{
result = b;
}

return result;
}
Example:
maxmin.c

/* Returns the larger of two numbers. */


Version 2:
int max (int a, int b)
{
if (a > b)
{
return a;
}
else
{
return b;
}
}
Example:
maxmin.c

/* Returns the larger of two numbers. */


Version 3:
int max (int a, int b)
{
if (a > b)
{
b = a;
}

return b;
}

Note:
Changing the value of b does not
affect the actual parameter in the
function call.
Example:
maxmin.c
#include <stdio.h>
/* Returns the smaller of two numbers. */
/* Returns the larger of two numbers. */
int min (int a, int b)
int max (int a, int b) {
{ if (a < b)
if (a > b) {
{ return a;
return a; }
} else
else {
{ return b;
return b; }
} }
}

int main()
{
int maxOfMins = max(min(1,2), min(3,4));
Or you can write
printf("%d\n",
printf("%d\n", maxOfMins);
max(min(1,2), min(3,4)));

return 0;
}
Return Values (cont.)

• If a function does not return a value,


declare its return type as void

Declaration: void sayHello ( void )


{
printf(“Hello World!\n”);
}

Function call: sayHello();


Return Values (cont.)

• As long as a function is not declared as


void, it can be used as an operand in any
valid C expression
– x = power(y);
– if(max(x,y) > 100) printf(“greater”);
Return Values (cont.)
• However, a function can not be the target
of an assignment
– swap(x,y) = 100; /* incorrect statement */
• A function declared as void can not be
used in any expression
void f();
...
t = f(); /* incorrect */
Return Values (cont.)

• If you do not assign the return value of


a function it is lost
int multiply(int a, int b);
int main()
{
x = multiply(5,4);
printf(“%d”, multiply(2,3));
multiply(8,3); /* lost */
}
Functions – “Do”s and “Don’t”s
• DON'T try to return a value that has a type
different from the function's type
• DON'T let functions get too long. If a function
starts getting long, try to break it into separate,
smaller tasks
• DO limit each function to a single task
• DON'T have multiple return statements if they
aren't needed. You should try to have one return
when possible; however, sometimes having
multiple return statements is easier and clearer

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy