Presentation is loading. Please wait.

Presentation is loading. Please wait.

FUNCTIONS.

Similar presentations


Presentation on theme: "FUNCTIONS."— Presentation transcript:

1 FUNCTIONS

2 What is a function? 1. A piece of code that performs an operation that can be used by the main program or by other functions 2. A sophisticated if –else statement that always goes into the else part and never into the if part Just some stuff the compiler uses and the user never has to use or see 4. An out of this world thrill ride at the Walt Disney World Resort in Orlando, FL!!!

3 Purpose of functions Avoid re-inventing the wheel
Using existing functions as building-blocks to create new programs Make programs easier to understand and to write Sometimes a program uses a section of code over and over again, using a function will avoid having to rewrite code segments

4 Function Definitions return-value-type function-name( parameter-list ) { definitions statements } function-name: any valid identifier - using a meaningful name. return-value-type: data type of the result. void - indicates that the function returns nothing parameter-list: comma-separated list Specifies the parameters received by the function when it is called. Function header

5 Function Prototypes Format
return-value-type function-name( parameter-list ); Parameter names are not necessarily included in the function prototype. A function prototype is used to validate functions The type of data returned by the function The number of parameters the function expected to receive The types of the parameters The order in which these parameters are expected.

6 Function Calls Invoking functions (by a function call)
Provide function name and arguments (data) Function returns results #include<stdio.h> #define SIZE 5 int sumValue( int x[ ], int size ); int main( void ) { int a[SIZE] = {1, 2, 3, 4, 5}; int total = 0; total = printf(“%d\n”, total); return 0; } int k, sum = 0; for (k = 0; k < size; k++) { sum += x[k]; return sum; sumValue( a, SIZE ); /* call sumValue( ); passing array a and SIZE */ What is the total? Passing an int to a floating point number, the value is not changed. Passing a floating point number to an int, the fractional part of the value is truncated. Should not pass an int to a pointer to int. The function prototype, function header and function calls should all agree in the number, type, and order of arguments and parameters, and in the type of return value. int sumValue( int x[ ], int size )

7 Functions Some notes: The function myFunction that returns an integer and takes in a double array called square and an integer called arraylength has the following prototype: int myFunction (double square[], int arraylength); 2. When this function is called from main() (or from another function), the call statement does not include the ‘[]’ for the array nor does it include the data types (i.e. double and int), i.e.: returnvalue = myFunction(square, arraylength); 3. The function definition has the following syntax, in this case returns as int: int myFunction (double square[], int arraylength) { perform actions; return somevalue; }

8 ARRAYS

9 Arrays An array is a data structure consisting of related data items of the same type. Stored in a group of memory locations Defining arrays int arrayName[ 100 ]; Examples int a[5]; float b[120], x[24]; a[0] 5 memory 10 15 3 23 a[1] a[2] a[3] a[4] Name of the array Specifying the type of each element The number of the elements

10 Referring to Array Elements
Formally called a subscript or an index Format arrayName[ position number ] First element at position 0 Last element at position size – 1 The i-th element of array a is referred to as a[i-1] A subscript must be an integer or an integer expression. Avoid to referring to an element outside the array bounds. Array elements are like normal variables. Passing an array element to a function by value. Passing a whole array to a function passes by reference.

11 1. num=2.00 num=2.00 num=2.50 num=2.25 num=4.00 2. num=2.00 num=1.00
#include <stdio.h> int main() { float num[5]; int i; for (i=0;i<5;i++) num[i] = 0.; } num[0] = 2.; num[4] = 4.; for(i=1;i<4;i++) num[i] = (num[i+1]+num[i-1])/2.; for(i=0;i<5;i++) printf("num=%.2f\n", num[i]); 1. num=2.00 num=2.00 num=2.50 num=2.25 num=4.00 2. num=2.00 num=1.00 num=0.50 num=2.25 num=4.00 3. num=2.00 num=1.00 num=1.50 num=2.25 num=0.00 4. num=0.00 num=1.00 num=0.50 num=2.25 num=4.00

12 Passing arrays to functions
Some notes: Whole arrays are passed by reference – which means that when they are changed in the function, that change is also seen in main() – or in the function from which it was called Related to #1 above, the address of the first element of an array is passed to a function 3. Array elements are passed by value 4. Typically the size of the array (unless it is a character array with a terminating character, i.e. string) is passed to the function because functions do not know what the size of an array is

13 What will this print out?
#include <stdio.h> void change(int array[], int val); int main(void) { int val = 3; int array[1] = {3}; change(array, val); printf(“array=%d, val=%d”,array[0],val); } void change(int array[], int val) int i; array[0] = array[0]*2; val = val * 2; 1. array=6, val=6 2. array=6, val=3 3. array=3, val=3 4. array=3, val=6

14 In the previous example, array was passed by ____1______,
while val was are passed by ___2_____? 1. reference, value 2. value, reference 4. Oh shoot, don’t know, I’d better ask Garvin’s other half as she is the one who knows everything! 3. Yo mamma, yo daddy

15 What will this print out?
#include <stdio.h> void change(int array, int val); int main(void) { int val = 3; int array[1] = {3}; change(array[0], val); printf(“array=%d, val=%d”,array[0],val); } void change(int not_an_array, int val) not_an_array = not_an_array*2; val = val * 2; 1. array=6, val=6 2. array=6, val=3 3. array=3, val=3 4. array=3, val=6 Notice that the function no longer takes in a whole array, but an array element – which is passed by value

16 What will this print out?
#include <stdio.h> int change(int array[], int val); int main(void) { int val = 3; int array[1] = {3}; val = change(array, val); printf("array=%d, val=%d",array[0],val); } int change(int array2[], int val) array2[0] = array2[0]*2; val = val * 2; return val; 1. array=6, val=6 2. array=6, val=3 3. array=3, val=3 4. array=3, val=6

17 Multi-Dimensional Arrays
Arrays that have more than one index(subscript): Basic integer: int a; -- Only has one value associated with it at one time -- Unless specified otherwise, a basic variable is passed to a function by value 1D array: int a[SIZE] -- Has a series of values associated with it: a[0], a[1], a[2], ….a[SIZE-1] 2D array: int a[ROWSIZE][COLSIZE] a[0][0], a[0][1], a[0][2], …a[0][COLSIZE-1], a[1][0],… Multi-D array: int a[SIZE][SIZE][SIZE]… Arrays are passed by reference, array elements are passed by value

18 Referring to Two-Dimensional Array Elements
Format arrayName[ rowIndex ][ colIndex ] Both row and column indices start from 0, and must be an integer or an integer expression. The accessed element of the array is on Row rowIndex and Column colIndex The names of the elements in the i-th row all have a first suscript/index of i. The names of the elements in the j-th column all have a second suscript/index of j.

19 Passing Two-Dimensional Arrays to Functions
Defining the function: The function’s parameter list must specify that a two-dimensional array will be received. #define ROWSIZE 10 #define COLSIZE 10 void oneFunc( int ary[ ] [ COLSIZE ] , int rowSize, int colSize ) Calling the function To pass an array argument to a function, specify the name of the array without any brackets int anArray[ ROWSIZE ][ COLSIZE ] = {{0}}; oneFunc( anArray, ROWSIZE, COLSIZE ); Array size usually passed to function Specifies the number of columns of the array parameter, which is required. The number of rows of the array parameter is NOT required. The header of the function Normally, also pass the numbers of rows and columns of the array argument.

20 STRINGS: A character array with a terminating null character ‘\0’
Various ways of defining a character array: char chararray[]=“biscuits”; char chararray[] = {‘b’,’i’,’s’,’c’,’u’,’i’,’t’,’s’,’\0’}; char chararray[80];

21 Some more string stuff:
Strings are character arrays (example): #include <stdio.h> #include <string.h> int main() { char sentence[80]; /* large array length */ int i; sentence[0] = 'B'; sentence[1] = 'y'; sentence[2] = 'e'; sentence[3] = '\0'; printf("%s", sentence); /* prints Bye */ for (i = 0; i < strlen(sentence); i++) printf("%c", sentence[i]); /* prints Bye */ } Caution when using scanf with strings: scanf(“%s”, string) /* no & is needed w/ %s*/ scanf(“%c”, &char) /* & is needed with %c */

22 POINTERS, PASS BY REFERENCE and PASS BY VALUE

23 Pointer Variables Contain memory addresses as their values
Normal variables contain a specific value (directly reference a value) Pointers contain address of a variable that has a specific value (indirectly reference a value) Referencing a value through a pointer is called indirection (or dereferencing)

24 Call(Pass)-by-Value Copy of argument passed to function
Changes in function do not effect original Use when function does not need to modify argument To avoid accidental changes Variables of type int, float, double, char are passed to a function by value. Elements of arrays are passed to a function by value.

25 Let’s review pass by value:
#include <stdio.h> void doSomething(int a, int b); int main() { int a = 1, b =0; doSomething(a,b); printf(“a=%d, b=%d ", a, b); } void doSomething(int a, int b) a = 7; b = 8; Is this going to print: 1. a=7, b=8 2. a=1, b=0

26 Illustrate what is going on with a “memory model”:
#include <stdio.h> void doSomething(int a, int b); int main() { int a = 1, b =0; doSomething(a,b); printf(“a=%d, b=%d ", a, b); } void doSomething(int a, int b) a = 7; b = 8; Variable Address Value in memory a b 500 501 1 When passed to function doSomething, the values are passed, not memory address: Variable Address Value in memory a b 550 551 1 7 8 Different address The modification was only for memory addresses 550 and 551, but when main prints a and b, it prints values at 500 and 501

27 What if we wanted main to print out the modified values of a and b?
Need to know each memory address! Need to use pointers!

28 What is the output now?: #include <stdio.h>
void doSomething(int *a, int *b); int main() { int a = 1, b =0; doSomething(&a,&b); printf(“a=%d, b=%d ", a, b); } void doSomething(int *a, int *b) *a = 7; *b = 8; Is this going to print: 1. a=7, b=8 2. a=1, b=0

29 Illustrate what is going on with a “memory model”:
#include <stdio.h> void doSomething(int *a, int *b); int main() { int a = 1, b =0; doSomething(&a,&b); printf(“a=%d, b=%d ", a, b); } void doSomething(int *a, int *b) *a = 7; *b = 8; Variable Address Value in memory a b 500 501 1 When passed to function doSomething, the ‘&’ means addresses are passed as values: Variable Address Value in memory a b 550 551 500 501 Original address stored as a value Different address a and b are the values of the addresses that were passed into the function, Using *a and *b allows you to modify the original values of a and b at location 500 and 501 (this process is called dereferencing).

30 Call(pass)-by-Reference
Passes original argument Changes made to parameter in function effect original argument Only used with trusted functions Arrays, strings, and pointers are passed to a function by reference.

31 A little more on pointers
Declaring a pointer needs a *: int * xPtr; This means xPtr should store an address If xPtr gets changed the address gets changed However, if *xPtr gets changed, that means xPtr is now “pointing” to that value Passing the address (i.e. pass by reference) of a regular variable needs an & in front of it (like scanf). int variable = 7; /* stores a value */ printf(“%p”,&variable); /* prints out address */

32 Quick example that may clear up some confusion:
int variable = 10; int *varPtr; varPtr = &variable; /* varPtr pointed to the variable address */ variable =100; printf(“%d, %d”, *varPtr, variable); variable = 200; *varPtr = 150; Answer: 100, 100 150, 150

33 (FILE I/O or FILE INPUT/OUTPUT)
C File Processing (FILE I/O or FILE INPUT/OUTPUT)

34 Why Using Files? Storage of data in variables and arrays is temporary (memory) Data lost when a program terminates. Files are used for permanent retention of data Stored on secondary storage devices Disks Optical disks (CDs, DVDs) USB memory key

35 Opening a File Define a FILE pointer called rfPtr; FILE *rfPtr;
The fopen function links a FILE pointer to the file to read: rfPtr = fopen(“sData.txt”, “r”); Or write: rfPtr = fopen(“sData.txt”, “w”); fopen Takes two arguments Filename -- file to open (“sData.txt”) File open mode -- “r” or “w” – there are others as well If open fails, NULL returned (i.e. there is nothing there)

36 Reading a file and writing to a file
Once a file is open, you can read or write to that file: To read a file: fscanf(rfPtr, “%f”, &variable); Like scanf, except reads from file instead of screen To write to a file fprintf(rfPtr, “%f”, variable); Like printf except prints to file instead of screen Check to see if end of file is reached: feof(rfPtr) Closing the file fclose(rfPtr);

37 What does this code do? #include <stdio.h> int main(void) {
FILE *fp; int i, n=10; fp = fopen("data1", "w"); for (i=0;i<n;i++) fprintf(fp,“%d\n”, i+1); } fclose(fp); return 0; 1. This prints to file data1 2. This prints to the screen 3. This prints to file fp 4. This reads from file data1

38 What does this code print out to output.dat when
the contents of data1 is: #include <stdio.h> int main(void) { FILE *fr, *fp; int i=0; fr = fopen("data1", “r"); fp = fopen(“output.dat”, “w”); fscanf(fr, “%d”, &i); while (!feof(fr)) fprintf(fp,“%d\n”, i+1); fscanf(fr,“%d”, &i); } fclose(fr); fclose(fp); return 0; 1. 1 2 3 4 5 6 2. 1 2 3 4 5 6 3. 0 1 2 3 4 5 4. 0 1 2 3 4 5


Download ppt "FUNCTIONS."

Similar presentations


Ads by Google