+ All Categories
Home > Documents > Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type...

Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type...

Date post: 13-Dec-2015
Category:
Upload: joseph-casey
View: 214 times
Download: 0 times
Share this document with a friend
66
Functions in C Comp 1402/1002
Transcript
Page 1: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Functions in C

Comp 1402/1002

Page 2: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

A Quick Note on Data Types

In C :Two options

One specific data type is provided

And another is expected:

1. The type is converted automatically

2. Compiler insists - you provide right type

Page 3: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Automatic Conversion

Page 4: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Forced Conversion (Casting)

• To go down the promotion hierarchy:

int x;

double y = 5.0;

x = (int) y;

y = (double) x;

Page 5: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Developing Large Programs

• Difficult to manage large code• Teams of people may be involved• Easy to forget what the project is all about• People may leave the company

Result: Code should be – well organized– well commented and documented– Organized in a modular form (small coherent parts)

Page 6: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Top Down Design

• Begin with the main problem/idea• Divide it into smaller problem/ideas • Further divide each small problem/idea into smaller

more manageable parts.

The process is termed: Divide and Conquer

When to stop?– When the sub-problem/idea is understood and manageable– Coding rule of thumb – a module is 5-30 lines (one page)

Page 7: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Top-Down Module Example

Page 8: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Functions as Modules of Code

Functions are the basic modules in C

• Every program has a main function

• The main function uses other functions

• Each function may use other functions

• Functions help organize and develop code

Page 9: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Functions : Organized Development

1. Allow organized development

2. Develop and test small pieces of code

3. Functions assignable to team members

4. Permit code reusability

Page 10: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Function and Organization

Page 11: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

What is a Function ?

• A function is a module (piece of code) aimed at accomplishing a single task– Note: the scope of the task or its objective may

large (recall breakdown of a problem/ideas)

Page 12: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

What is a Function ?

Page 13: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Functions : Calling and Data

• Calling function passes zero or more

parameters to called function

• Called function “returns” only ONE item

main passes parameters to function1

function1 passes parameters to functiona

Page 14: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Predefined/coded functionsLibrary

We have already used a few:printf ( ) scanf( )

• Somebody has already written these. – Note that we need not know how they work.

• We do need to know what the functions do and how to use them – documentation

Page 15: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Libraries of Code

• Often languages come with libraries of code

• Provided “free of charge”– Beware of Copyright issues...

• Use library code whenever possible– software is expensive (design, coding, testing, documentation,

etc).

Page 16: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Using a Standard C Library

Page 17: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Three Important C Libraries

stdio - Standard IO library – File manipulation, input, output– Definitions and manipulations of stdin stdout

and stderr.

math – Math Library– Defines most mathematical functions needed.

stdlib – Standard library– Memory and miscellaneous (some math here).

Page 18: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

math & stdlib

Math

#include<math.h>

sometimes requires –lm as compiler option

Stdlib

#include<stdlib.h>

Page 19: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Some Standard Library Functions

Name Parameter Returns Examplesqrt double double sqrt(25.0)

pow double double pow(2.0,3.0)

abs int int abs(-10)

fabs double double fabs(6.8)

ceil double double ceil(1.7)

cos double double cos(3.2)

sin double double sin(3.2)

log double double log(127.5)

Page 20: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Examples : ceil() and floor()

Page 21: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Examples : rand()

Page 22: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Function : Random Numbers

Get next “pseudo-random” numberint x = rand( );/* returns value in 0 to RAND_MAX */

Note• rand() always generates the same sequence of random

numbers

• If one wants a different sequence must initialize the random functions.

Initialize a new seed for the random number generator:unsigned int seed = 2990;srand(seed);

Page 23: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Nesting Function Calls

int i=10;

double y;

y = cos( pow( (double) i, 2)));

Convert i to a double (unnecessary)

Compute i squared

Compute cosine of i square

Page 24: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

User Defined Functions

Three places where a function name is used:

1. Declaration (Prototype)

2. Call (Invocation)

3. Definition (Specification)

Page 25: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Declarations (Prototypes)

• Inform the calling program of the function

• Otherwise the compiler uses implicit declaration – you may get a warning “implicit declaration”

return_type function_name (parameter list);

Example:

int main(void);

Void is a special reserved word meaning “nothing”- no parameter list

Page 26: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Example of Fn. Declarations

double area(double length, double width);

double perimeter(int radius);

Identical to:

double area(double, double);

double perimeter(int)

Page 27: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Function Declarations, Calls & Definitions

#include <stdio.h>void greeting (void); /* Function Prototype*/

int main(void){ greeting( ); /* Function Call*/ return 0;}

/* Function Definition*/

void greeting(void){ printf ("\n Hello World \n");}

Page 28: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Declarations, Calls & Definitions

Page 29: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Example: A function to calculate hypotenuse.#include <stdio.h>

#include <math.h>

/* Function Prototype */

double hypot (double x , double y); int main () {

double side1, side2;

printf(“Enter 2 sides of Right triangle\n”,);

scanf(“%lf%lf”, &side1, &side2);

printf(“The hypotenuse is: %f\n“, hypot(side1,side2));

return 0;

}

Example of Fn. Declarations

Page 30: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Function Definition

return_type function_name (parameter list){local variables

code statements/expressions

return expression}

Page 31: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Function Definition

Example: The Actual function to hypotenuse.

/*Function Hypotenuse *//*Input: Two sides of a Right triangle *//*Output: The Hypotenuse */

double hypot(double x , double y){double hypotenuse = sqrt( x*x + y*y);

return (hypotenuse);}

Page 32: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Function Definition

Example: The Actual function to hypotenuse.

/*Function Hypotenuse */

/*Input: Two sides of a Right triangle */

/*Output: The Hypotenuse */

double hypot(double x , double y)

{

return (sqrt( x*x + y*y));

}

Page 33: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Using the function’s declaration the compiler compares the declaration to each occurrence of the function in the program.

a. Number of parameters must be the same b. Type of parameters must be the same

hypotenuse = hypot(side1,side2);

double hypot(double x , double y)

Page 34: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

The return statement

A return statement should be used even if there is nothing to return.

void myfunction(…….)

/*ends with the statement */

return;

Page 35: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Implicit Declaration

• If a function definition is not available then– C creates an implicit function definition– function parameters and return value are an int.

Page 36: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Example: A function to calculate hypotenuse.#include <stdio.h>#include <math.h>

int main () {double side1, side2;printf(“Enter 2 sides of Right triangle\n”,);scanf(“%lf%lf”, &side1, &side2);printf(“The hypotenuse is: %f\n“,

hypot(side1,side2));return 0;

}

C implicit declaration has the form ofint hypot (int x , int y);

Example of Fn. Declarations

Page 37: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Limitation: C-No Polymorphism!

C is unlike C++ and JAVA

Can only declare/define a function name once per program

No overloading - parameters and return type are irrelevant

double hypot(int x, int y);double hypot(double x, double y);

Name functions carefully (e.g. fabs, abs, labs)

Page 38: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Header Files

.h files usually contain function and constant declarations

• Single “include” gives many declarations

• Important if functions are in another file

Page 39: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Functions : Definition

Page 40: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Function : Return Type

Page 41: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Function : Calling (Invoking)

Page 42: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Function : Calling (Invoking)

Page 43: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Functions : Parameters

Parameters are always passed by value

Can be viewed as passed in two ways:

1. Pass by value ……send a copy of the value

2. Pass by reference (address)…send a copy of the address of the variable

Page 44: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Parameters : Pass by Value

Copy the value:

From the caller

Into the formal parameter of the called

This is a one-way communication …..

hypotenuse = hypot(side1,side2);

double hypot(double x , double y)

Page 45: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

hypoteneuse = hypot(side1,side2);

double hypot(double x , double y)

x is a copy of side1y is a copy of side 2

So the function can change x or yand side1 and side2 are unaffected.

Page 46: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Function Param.:Pass by Value

Page 47: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Function Parameters

• Copy of the value is placed on the stack

• Transfer of control goes to the function

• Function can pick the parameters off the stack

• Original variables are untouched by function...

Page 48: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Function : Pass by Address

Instead of copying a value:

Copy the memory address!!!

Then work with that address.

Variables containing addresses are: pointers...

Page 49: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

FunctionPars:

Pass by Address

Page 50: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Address and Dereference

& is the address operatorint a = 5;

&a /* is the address to an int */

/* type is (int *) */

* Is the dereference operatorint *x; /* x is a pointer to an int */

x = &a; /* use the address of variable a */

*x = 12; /* contents of x is set to 12 */

Page 51: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Address and Dereference• What’s wrong with the following code?#include <stdio.h>

void swap(int ,int ); /* swapping */

int main(void) /*calls swap function*/

{

int x; int y;

printf("\n enter x and y: ");

scanf(“%d%d”,&x,&y);

swap(x,y);

printf("new x: %d new y: %d\n",x , y);

return 0;

}

Page 52: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Address and Dereference

• Here’s the function swap...void swap (int a, int b)

{

int temp;

temp = a;

a = b;

b = temp;

}

Answer: It does not swap the values because of pass by value.

Solution: Use a different dangerous passing mechanism.

Don’t pass the values but pass the addresses.

Page 53: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Address and Dereference• Why is this dangerous… Modify Calling Variables#include <stdio.h>void swap (int *, int *); int main( void ) /*calls swap*/{int x; int y;printf("\n enter x and y: ");scanf(“%d%d”, &x, &y); swap ( &x, &y);printf("new x: %d new y: %d\n", x, y);return 0;

}

Page 54: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Address and Dereference• Here is the real swap… It works !!

void swap (int *a, int *b)

{

int temp;

temp = *a;

*a = *b;

*b = temp;

}

Page 55: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Call by value is useful

• Call by value is useful

double fact(int n) {double total = 1;while (n >=1) {

total *=n;n--;

}return (total);

}

double fact(int n) {double total = 1;for(;n >=1;n--) {

total *=n;}return(total);

}

Page 56: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Call by value is useful

#include <stdio.h>

double fact(int n);

int main(void) {

int n = 10;

printf(“factorial(%d)=%f \n”, n, fact(n));

}

Page 57: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Another function

We want a function to print a square?

XXXXXXXXXXXXXX XXXXXXXXXXX XXX XXXXXXXXXXX XXX XXXXXXXXXXX XXX XXXXXXXXXXXXXXXXXX

Page 58: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

How do we do it?Nested loops………….loops inside loops

int i,j;char point ='X';int size=4;for (i=1; i<= size; i++) {

for (j=1; j<= size ;j++) {printf("%c", point);

} printf("\n");}

Page 59: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Now we have to make it a function

drawsquare size

nothing returned

Page 60: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

/* a function that draws a square of size "howbig" */

void drawsquare (int howbig){ int i; int j;

printf("\n\n");char point ='X';for (i=1;i<= howbig;i++) {

for (j=1;j<= howbig;j++) {printf("%c", point);

} printf("\n");}printf("\n\n");return;

}

Page 61: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

void drawsquare (int size); /*function prototype */

int main(void){int sizeofsquare;printf("type an integer size of the square\n");

scanf("%d", &sizeofsquare);drawsquare(sizeofsquare);return 0;

}

Page 62: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Scope and Duration

Global Scope

Anything defined is visible from its definition to the end of the program.

Local Scope

Good from their definition to the end of their block (normally a function)

Page 63: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Scope and Duration

Global Variables

• Placed outside the functions that use them

• Available to all functions

• Global variables should be AVOIDED...

Page 64: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Local Variables

• Scope is extent of their block

• Placed on the stack

• Destroyed on exit from function

Page 65: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.
Page 66: Functions in C Comp 1402/1002. A Quick Note on Data Types In C :Two options One specific data type is provided And another is expected: 1.The type is.

Static Variable

Variables which are declared static are visible only within their code segment (file or local block)

Local variable is modified with static then:

• Variable exists from program beginning to end

• Only available in the function or file

• Initialized with 0

• Functions can only be declared static – visibility is only within the file


Recommended