35
Functions Functions Lecture 4 – Lecture 4 – Section 2: 9/21/05 Section 2: 9/21/05 Section 4: 9/22/05 Section 4: 9/22/05

Functions Lecture 4 – Section 2: 9/21/05 Section 4: 9/22/05

  • Upload
    nydia

  • View
    41

  • Download
    0

Embed Size (px)

DESCRIPTION

Beginning C for Engineers Fall 2005. Functions Lecture 4 – Section 2: 9/21/05 Section 4: 9/22/05. Homework, etc. Read Chapter 5 HW4 The project will be posted next week. Details to follow…. Functions. Recall that a C program is a collection of functions. - PowerPoint PPT Presentation

Citation preview

Page 1: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

FunctionsFunctionsLecture 4 – Lecture 4 –

Section 2: 9/21/05 Section 2: 9/21/05

Section 4: 9/22/05Section 4: 9/22/05

Page 2: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

Homework, etc.Homework, etc.

Read Chapter 5 Read Chapter 5 HW4HW4 The The projectproject will be posted next will be posted next

week. Details to follow…week. Details to follow…

Page 3: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

FunctionsFunctions

Recall that a C program is a Recall that a C program is a collection of functions.collection of functions.

every C program must have a every C program must have a function called function called mainmain

program execution always begins program execution always begins with function mainwith function main

any other functions are any other functions are subprograms and must be calledsubprograms and must be called

Page 4: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

More About FunctionsMore About Functions it is not considered good practice for it is not considered good practice for

the body block of function main to be the body block of function main to be long long

function calls are used to do tasksfunction calls are used to do tasks

every C function has a return type every C function has a return type (main returns int)(main returns int)

if the return type is not void, the if the return type is not void, the function returns a value to the calling function returns a value to the calling block block

Page 5: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

Where are functions?Where are functions?

located in librarieslocated in libraries Ex: The Ex: The square root functionsquare root function is in the is in the

math.h library - need to #include <math.h> math.h library - need to #include <math.h> to use it.to use it.

discriminant = sqrt ( b * b – 4 * a * c);discriminant = sqrt ( b * b – 4 * a * c);

OROR

written by programmerswritten by programmers

Page 6: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

HEADER FUNCTIONHEADER FUNCTION EXAMPLE EXAMPLE RESULTRESULT FILE FILE OF CALL OF CALL

<math.h> sqrt(float x) s = sqrt(100.0); s = 10.0

sqrt(int x) t = sqrt(2); t = 1.41421

sin(float x) a = sin(3.0); a = 0.14112

log(float x) c = log(2.0); c = 0.30102

<stdio.h> printf(…) printf(“Hello, World”); Hello, World scanf(…) scanf(“%d”, &number); number = input

<stdlib.h> abs(int i) a = abs(-6); a = 6

Page 7: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

Two Kinds of FunctionsTwo Kinds of Functions

Always returns a single value to its caller and is called from within an expression.

Never returns a value to its caller, and is called as a separate statement.

Value-Returning VoidValue-Returning Void

7

Page 8: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

int num1;

int num2;

int highest;

printf(“Enter two numbers: ”);

scanf(“%d%d”, &num1, &num2);

highest = findHighestNum( num1, num2 );

printf(“Printing something to the screen…”);

mysteryFunction( num1, num2 );

void function

example

value-returning function

example

Page 9: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

Any user-defined Any user-defined function consists of 3 function consists of 3

parts: parts: Function Function declarationdeclaration (a.k.a. prototype) (a.k.a. prototype)

Tells the compiler you will be defining this function Tells the compiler you will be defining this function later. The declaration must come before main.later. The declaration must come before main.

Same as the header but has a semicolon (;) after itSame as the header but has a semicolon (;) after it Function Function definitiondefinition

Heading = return type, function name, parameter Heading = return type, function name, parameter listlist

Body = actual codeBody = actual code Function Function callcall

Using the functionUsing the function

Page 10: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

What is in a heading? What is in a heading?

int main ( ){

return 0;}

10

type of returned value

name of function

says no parameters

Page 11: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

Every C function has 2 Every C function has 2 partsparts

int main ( )

{stmt_1;… stmt_n;

return 0;}

11

heading

body block

Page 12: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

Function CallsFunction Calls

1.1. one function calls another by using the one function calls another by using the name of the called function together name of the called function together with ( ) containing an argument listwith ( ) containing an argument list

2.2. a function call temporarily transfers a function call temporarily transfers control from the calling function to the control from the calling function to the called functioncalled function

3.3. when the function’s code has finished when the function’s code has finished executing, control is transferred back executing, control is transferred back to the calling blockto the calling block

Page 13: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

Trace of a Function CallTrace of a Function Call

int main ( ) { int num1, num2, highest; printf(“Enter two numbers: ”); scanf(“%d%d”, &num1, &num2); highest = findHighestNum(num1, num2); printf(“\nThe highest number is %d.\n”, highest); return 0;}

Page 14: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

Functions that return Functions that return valuesvalues

Sometimes a function computes a value Sometimes a function computes a value needed by the rest of the program needed by the rest of the program

Functions must be able to return computed Functions must be able to return computed values before they terminate.values before they terminate. the sqrt function does thisthe sqrt function does this

If a function’s return type is anything other If a function’s return type is anything other than void, then we usually use the function than void, then we usually use the function call in an expressioncall in an expression Examples: Examples: x = y + sqrt(20);

c = max(a, b);

Page 15: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

Program with Two Functions

main function

square function

Page 16: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

Function DefinitionFunction Definition

int Square ( int n ) header {

int sq = n * n; bodyreturn sq;

}

Return Function Parameter ParameterType Name Type Name

Page 17: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

Using the Square Using the Square functionfunction

#include <stdio.h>

int Square (int n); /* declare function */

int main( ){ int x, sq; printf("Enter a number: “); scanf(“%d”, &x); sq = Square( x ) ; /* function call */ printf(“The square of %d is %d\n”, x, sq); printf(“Goodbye\n”); return 0 ;}

Page 18: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

Rest of the programRest of the program

/* Define function *//* Define function */int Square ( int n ) int Square ( int n )

{{ int s;int s; s = n * n;s = n * n;

return s;return s;}}

Page 19: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

Output of the ProgramOutput of the Program

Enter a number: 15Enter a number: 15

The square of 15 is 225The square of 15 is 225

GoodbyeGoodbye

Page 20: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

Functions that return Functions that return valuesvalues

If a function returns a value, the last statement If a function returns a value, the last statement executed must be a return statement.executed must be a return statement. Syntax: return <expression>;Syntax: return <expression>; After a return statement is executed no other After a return statement is executed no other

statements in the body of the function are executedstatements in the body of the function are executedEquivalent to:Equivalent to:

int max (int x, int y){

int myMax; if (x > y) myMax = x; else myMax = y;

return myMax;}

int max (int x, int y){ if (x > y) return x; return y;}

Page 21: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

To call the max functionTo call the max function

int a, b, c;int a, b, c;

printf(“Enter two values:”);printf(“Enter two values:”);

scanf(“%d %d”, &a, &b);scanf(“%d %d”, &a, &b);

c = max(a, b);c = max(a, b);

printf(“The max is %d”, c);printf(“The max is %d”, c);

Page 22: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

Trace of a Function CallTrace of a Function Callint main ( ) { int num1, num2, highest; printf(“Enter two numbers: ”); scanf(“%d%d”, &num1, &num2); highest = findHighestNum(num1, num2); printf(“\nThe highest number is %d.\n”, highest); return 0;}

int findHighestNum( int num1, int num2) { if(num1 > num2)

return num1; else

return num2;}

Page 23: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

void functionsvoid functions

Functions which do not return a Functions which do not return a value are called void functions. Use value are called void functions. Use voidvoid as the return type. as the return type.

void functions are usually used to go void functions are usually used to go off and “do something,” but they do off and “do something,” but they do NOT return a value.NOT return a value.

The most common use of a void The most common use of a void function is to print something.function is to print something.

Page 24: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

void FunctionName ( Argument List );

The argument list is a way for functions to The argument list is a way for functions to communicate with each other by passing communicate with each other by passing information.information.

The argument list can contain 0, 1, or more The argument list can contain 0, 1, or more arguments, separated by commas, depending arguments, separated by commas, depending

on the function.on the function.

Syntax To Call a Syntax To Call a voidvoid FunctionFunction

Page 25: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

Example of a void Example of a void functionfunction

/* Definition *//* Definition */

void printDay(int num)void printDay(int num)

{{

if (num == 0)if (num == 0)

printf(“Sunday”);printf(“Sunday”);

else if (num == 1)else if (num == 1)

printf(“Monday”);printf(“Monday”);

else if (num == 2)else if (num == 2)

printf(“Tuesday”);printf(“Tuesday”);

……

else if (num == 6)else if (num == 6)

printf(“Saturday”);printf(“Saturday”);

else else

printf(“Invalid day”);printf(“Invalid day”);

}}

#include <stdio.h>

/* declaration */

void printDay(int num);

int main( ){

int day;printf(“Enter a number between 0 and 6”);scanf(“%d”, &day);/* Call */printDay(day);return 0;

}

Page 26: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

Example of a void Example of a void functionfunction

/* Definition *//* Definition */void printDay(int num)void printDay(int num){{

switch(num) {switch(num) {case 0:case 0:

printf(“Sunday”);printf(“Sunday”);break;break;

case 1:case 1:printf(“Monday”);printf(“Monday”);break;break;

……case 7:case 7:

printf(“Sunday”);printf(“Sunday”);break;break;

default: default: printf(“Invalid printf(“Invalid

day”);day”);}}

}}

#include <stdio.h>

/* declaration */

void printDay(int num);

int main( ){

int day;printf(“Enter a number between 0 and 6”);scanf(“%d”, &day);/* Call */printDay(day);return 0;

}

Page 27: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

Parameter ListParameter List

is the means used for a function is the means used for a function to share information with the to share information with the block containing the call block containing the call

use commas to separate multiple use commas to separate multiple parametersparameters

each parameter needs a type each parameter needs a type and nameand name

Page 28: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

Classified by LocationClassified by Location

Always appear in a function call within the calling block.

Always appear in the function heading, or function prototype.

Arguments Arguments Parameters Parametersa.k.a. “Actual Parameters” a.k.a. “Formal Parameters”a.k.a. “Actual Parameters” a.k.a. “Formal Parameters”

Page 29: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

Example – What’s the Example – What’s the output?output?

#include <stdio.h>#include <stdio.h> void fun (int b, int c, int a);void fun (int b, int c, int a);

int main()int main(){{

int a = 1, b = 3, c = 5;int a = 1, b = 3, c = 5; fun(a, b, c);fun(a, b, c);

return 0; return 0; ArgumentsArguments}} ParametersParameters

void fun (int x, int y, int z)void fun (int x, int y, int z){{

printf(" %d %d %d”, x, y, z);printf(" %d %d %d”, x, y, z);}}

Output

1 3 5

Page 30: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

Example – What’s the Example – What’s the output?output?

#include <stdio.h>#include <stdio.h> void fun (int b, int c, int a);void fun (int b, int c, int a);

int main()int main(){{

int a = 1, b = 3, c = 5;int a = 1, b = 3, c = 5; fun(a, b, c);fun(a, b, c);

return 0; return 0; ArgumentsArguments}} ParametersParameters

void fun (int a, int b, int c)void fun (int a, int b, int c){{

printf(" %d %d %d”, a, b, c);printf(" %d %d %d”, a, b, c);}}

Output

1 3 5

As long as the variable names are consistent throughout the function you can name them anything. They are local to the function and will not change the variables outside the function, even if they have the same names.

Page 31: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

Variable RulesVariable Rules C uses C uses pass by valuepass by value to pass values to to pass values to

functions. This means that when a functions. This means that when a function is called, the values in the function is called, the values in the arguments (in the function call) are arguments (in the function call) are copied to the values in the parameters (in copied to the values in the parameters (in the function definition) the function definition)

Any variable declared inside a function Any variable declared inside a function can only be used in that function. These can only be used in that function. These are called are called local variableslocal variables, I.e. they are , I.e. they are local to the function.local to the function. Parameters are also treated as local variablesParameters are also treated as local variables

Page 32: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

Global variablesGlobal variablesAny variable declared at the beginning of the program Any variable declared at the beginning of the program outside of all functions is called a outside of all functions is called a global variableglobal variable. It can . It can be “seen” and changed by be “seen” and changed by anyany function. function.

#include <stdio.h>int x;void fun(int n);int main( ){

int a = 5;x = 10;printf(“%d %d\n”, a, x);fun(a);printf(“%d %d\n”, a, x);return 0;

}

void fun(int n){

x = 20;n = 30;

}

5 10

5 20

Output

Page 33: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

Boolean functionsBoolean functionsRecall that boolean values are either 0 or 1. Therefore a Recall that boolean values are either 0 or 1. Therefore a

boolean function is one that returns either 0 or 1.boolean function is one that returns either 0 or 1.

/* Return 1 if n is prime, 0 if n is not prime *//* Return 1 if n is prime, 0 if n is not prime */

int isPrime(int n)int isPrime(int n)

{{

……

}}

/* Call - Prints out i if it is prime *//* Call - Prints out i if it is prime */

if (isPrime(i))if (isPrime(i))

printf(“%d”, i);printf(“%d”, i);

Page 34: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

Things to NoteThings to Note In a function In a function callcall, you do not include the data , you do not include the data

type of the variable.type of the variable.Right:Right: c = min(a, b);c = min(a, b);Wrong:Wrong: c = min (int a, int b);c = min (int a, int b); If a function returns a value, you must call it If a function returns a value, you must call it

in an assignment statement or in a condition in an assignment statement or in a condition in order to use the return value.in order to use the return value.

Right:Right: c = min(a, b);c = min(a, b);if (isPrime(n))if (isPrime(n))

Wrong:Wrong: min(a, b);min(a, b);isPrime(n);isPrime(n);

Page 35: Functions Lecture 4 –  Section 2: 9/21/05  Section 4: 9/22/05

The LabThe Lab

You can take the rest of class time to work on the You can take the rest of class time to work on the lab. (lab. (Do not use the math.h library for these Do not use the math.h library for these exercisesexercises).).

Note: For HW4, if you would like you may use Note: For HW4, if you would like you may use some of the math functions (in the math.h some of the math functions (in the math.h library) mentioned in this lecture or in Chapter library) mentioned in this lecture or in Chapter 5. You will then need to compile your program 5. You will then need to compile your program differently:differently:

gcc –lm exercise4.cgcc –lm exercise4.c

where –lm stands for (“where –lm stands for (“LL”ink to “”ink to “MM”ath library)”ath library)