1 / 38

FUNCTIONS

FUNCTIONS. 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

fnathan
Télécharger la présentation

FUNCTIONS

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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 header 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.

  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 */ 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: • intmyFunction (double square[], intarraylength); • 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: • intmyFunction (double square[], intarraylength) • { • perform actions; • return somevalue; • }

  8. ARRAYS

  9. memory … Name of the array a[0] 5 a[1] 10 a[2] 15 a[3] 3 Specifying the type of each element The number of the elements a[4] 23 … 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];

  10. Formally called a subscript or an index Referring to Array Elements • 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. #include <stdio.h> int main() { float num[5]; inti; 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[], intval); int main(void) { intval = 3; int array[1] = {3}; change(array, val); printf(“array=%d, val=%d”,array[0],val); } void change(int array[], intval) { inti; 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, intval); int main(void) { intval = 3; int array[1] = {3}; change(array[0], val); printf(“array=%d, val=%d”,array[0],val); } void change(intnot_an_array, intval) { 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[], intval); int main(void) { intval = 3; int array[1] = {3}; val = change(array, val); printf("array=%d, val=%d",array[0],val); } int change(int array2[], intval) { 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] • -- Has a series of values associated with it: • 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. 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. 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

  19. Specifies the number of columns of the array parameter, which is required. The header of the function Normally, also pass the numbers of rows and columns of the array argument. The number of rows of the array parameter is NOT required. 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

  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 */ inti; 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, charare 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; } Address Value in memory Variable 1 0 a b 500 501 When passed to function doSomething, the values are passed, not memory address: Address Value in memory Variable 7 8 1 0 a b 550 551 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; } Address Value in memory Variable 1 0 a b 500 501 When passed to function doSomething, the ‘&’ means addresses are passed as values: Address Value in memory Variable 500 501 a b 550 551 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; • printf(“%d, %d”, *varPtr, variable); • Answer: 100, 100 • 150, 150

  33. 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 fopenfunction 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: 0 1 2 3 4 5 1. 1 2 3 4 5 6 6 #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; } 2. 1 2 3 4 5 6 4. 0 1 2 3 4 5 5 3. 0 1 2 3 4 5

More Related