Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.

Similar presentations


Presentation on theme: "Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files."— Presentation transcript:

1 Lecture 22: Reviews for Exam 2

2 Functions Arrays Pointers Strings C Files

3 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

4 Function Definitions return-value-type function-name( parameter-list ) { definitions statements } Returning control If nothing returned If something returned Defining function with array parameters Function header return; Or, until reaches right brace. return expression; The function’s parameter list must specify that an array will be received. void myFunc( int ary[ ], int size ) { …….. } The size of the array is NOT required.

5 Function Definitions - Example #include #define SIZE 5 int sumValue( int x[ ], int size ); int main( void ) { int a[SIZE] = {1, 2, 3, 4, 5}; int total = 0; total = sumValue( a, SIZE ); printf(“%d\n”, total); return 0; } { int k, sum = 0; for (k = 0; k < size; k++) { sum += x[k]; } return sum; } sumValue( )int sumValue( int x[ ], int size )

6 Function Calls Invoking functions (by a function call) Provide function name and arguments (data) Function returns results #include #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; } int sumValue( int x[ ], int size ) sumValue( a, 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. /* call sumValue( ); passing array a and SIZE */

7 Function Prototypes Prototype only needed if function definition comes after use in program 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.

8 Function Prototypes - Example #include #define SIZE 5 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; } int sumValue( int x[ ], int size ) sumValue( a, 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. /* function prototype */ int sumValue( int x[ ], int size ); int sumValue( int [ ], int );

9 Call-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.

10 Call-by-Value: Practice Question Solution: B

11 Call-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.

12 Call-by-Reference: Practice Question Q. What is the output of the following program? Solution: B

13 Call-by-Reference: Practice Question Q. What is the output of the following program? #include #define SIZE 5; void func( int a[], int x ); int main( void ) { int b[SIZE] = {1, 2, 3, 4, 5}; func(b, b[1]); printf(“%d %d\n”, b[0], b[1]); return 0; } void func( int a[], int x) { int k; for (k = 0; k < SIZE; k++) a[k] *= 2; x *= 3; } A. 1 2 B. 2 4 C. 2 6 D. 2 12 Solution: B

14 Call-by-Reference: Practice Question Q. What is the output of the following program? #include #define SIZE 100 void chgString(char s[ ]); int main( void ) { char s1[SIZE] = "I love EPSII."; printf("%s\n", s1); chgString(s1); printf("%s\n", s1); return 0; } void chgString(char s[ ]) { char s2[ ] = "It is great!"; strcpy(s, s2); }

15 Scope Rules The scope of an identifier is the portion of the program in which the identifier can be referenced. File scope Identifier defined outside function, know in all functions from the point at which the identifier is declared until the end of the file. Used for global variables, function definitions, function prototypes Block scope Identifier declared inside a block Block scope begins at definition, ends at the terminating right brace ({) of the block. Used for local variables, function parameters Outer blocks “hidden” from inner blocks if there is a variable with the same name in the inner block

16 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] Specifying the type of each element Name of the array The number of the elements

17 Referring to Array Elements Format arrayName[ position number ] First element at position 0 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. Formally called a subscript or an index

18 Initializing the Array Using a for loop to initialize the array’s elements Initializing an array in a definition with an initializer list Defining an array followed by an equals sign and braces, { }, containing a comma-separated list of initializers. int n[5] = {1, 2, 3, 4, 5}; If not enough initializers, rightmost elements become 0. int n[5] = {1, 2} int n[5] = {0} --- all elements are 0. If too many initializers, a syntax error occurs If size omitted, # of initializers determine the size int n[ ] = {1, 2, 3, 4, 5, 6}; 6 initializers, therefore 6 element array.

19 Practice Question #define SIZE 5 int aray[SIZE] = {2, 3, 4}; printf(“%d\n”, aray[1] + aray[2] + aray[3]); Q. What is the output of the following code fragment? A.2 B.5 C.9 D.7 Solution: D

20 Practice Question #define SIZE 5 int aray[SIZE] = {2, 3, 4, 5}; Q. What is the value of aray[5] ? A.0 B.4 C.Not sure D.5 Q. What is the value of aray[1] ? A.2 B.0 C.Not sure D.3 Solution: C Solution: D

21 Two-Dimensional Arrays Define a two-dimensional array #define ROWSIZE 3 #define COLUMNSIZE 4 int arrayName[ ROWSIZE ][ COLUMNSIZE ]; Refer to two-dimensional array elements arrayName[ rowIndex ][ colIndex ] Specifying the type of each element Name of the array The number of the rows The number of the columns The accessed element of the array is on Row rowIndex and Column colIndex

22 0 Initializing Two-Dimensional Arrays Using nested loops #define ROWSIZE 3 #define COLSIZE 4 int a[ ROWSIZE ][ COLSIZE ]; int row, col; for (row = ; row < ; row ++) { for (col = ; col < ; col ++) { printf(“Enter the element a[%d][%d]: ”, row, col); scanf(“%d”, ); printf(“\n”); } Initializing an array in a definition with initializer lists. Similar to a single-subscripted array. Initializers grouped by row in braces int a[ 2 ] [ 3 ] = {{1, 2, 3}, {4, 5, 6}}; If not enough, unspecified elements set to zero. int a[ 2 ][ 3 ] = {{1}, {4, 5}}; int b[ 3 ][ 5 ] = {{1}, {2}}; 0 COLSIZE ROWSIZE &a[row][col]

23 Pointers Pointer variables contain memory addresses as their values Declare a pointer variable using * int *countPtr; defines a pointer to an int (countPtr is of type int *) Dereferencing a pointer int y = 5, x; int *yPtr = &y; Returns the value of the object to which its operand (i.e., a pointer) points printf(“%d”, *yPtr); x = *yPtr; * can be used for assignment *yPtr += 7; /* changes y to 12 */ printf(“%d”, *yPtr); … … … count 0xBFFFF818 15 BFFFF818 RAM countPtr 0xBFFF924

24 Strings A string is an array of characters ending in the null character (‘\0’). char str[ ] = “hello”; char str[ ] = {‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’}; char str[SIZE] = “hello”; /* make sure SIZE > length(“hello”) */ Input strings using scanf( ) char word[100]; scanf(“%s”, word); /* input: EPSII is funny */ Copies input into word[ ] Do not need & (a string evaluates the address of its first character) Output strings printf(“%s\n”, str); k = 0; while ( ) { printf(“%c”, str[k]); k ++; } str[k] != ‘\0’

25 String Handling Functions int sprintf( char *s, const char *format,... ); Equivalent to printf, except the output is stored in the array s instead of printed on the screen. Ex. char s[100]; sprintf(s, “%d + %d = %d\n”, 5, 6, 5+6); int scanf( char *s, const char *format,... ); Equivalent to scanf, except the input is read from the array s rather than from the keyboard. char *strcpy( char *s1, const char *s2 ) Copies string s2 into array s1. char *strncpy( char *s1, const char *s2, size_t n ) Copies at most n characters of string s2 into array s1. Ex. char s1[100]=“I love EPSII.”; char s2[100] = “EPSII is great.”; strcpy(s1, s2);

26 String Handling Functions char *strcat( char *s1, const char *s2 ) Appends string s2 into array s1. char *strncat( char *s1, const char *s2, size_t n ) Appends at most n characters of string s2 into array s1. Ex. char s1[100]=“I love EPSII.”; char s2[100] = “EPSII is great.”; char *strcmp( char *s1, const char *s2 ) Compares the string s1 with the string s2. The function returns 0, less than 0 or greater than 0 if s1 is equal to, less than or greater than s2, respectively. strcat(s1, s2); strncat(s1, s2, 5);

27 Practice Question Q. What is NOT the right way to create a character array and assign it the string “I love EPS II”? A. char string[25]= “I love EPS II”; B. char string[25]; strcpy(string, “I love EPS II”; C. char string[25]; string = “I love EPS II”; D. char string[25] = {‘I’, ‘ ‘, ‘l’, ‘o’, ‘v’, ‘e’, ‘ ‘, ‘E’, ‘P’, ‘S’, ‘ ‘, ‘I’, ‘I’, ‘\0’}; E. char string[25]; sprintf(string, “%s”, “I love EPS II”); Solution: C


Download ppt "Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files."

Similar presentations


Ads by Google