1 / 27

Lecture 22: Reviews for Exam 2

Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files. Function header. Function Definitions. return-value-type function-name( parameter-list ) { definitions statements } function-name : any valid identifier - using a meaningful name.

barth
Télécharger la présentation

Lecture 22: Reviews for Exam 2

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. Lecture 22: Reviews for Exam 2

  2. Functions Arrays Pointers Strings C Files

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

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

  5. Function Definitions - Example #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 = sumValue( a, SIZE ); 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( )

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

  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<stdio.h> #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; } 1 2 2 4 2 6 2 12 Solution: B

  14. Call-by-Reference: Practice Question Q. What is the output of the following program? #include<stdio.h> #include<string.h> #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); return0; } 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. 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];

  17. Formally called a subscript or an index 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.

  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 intn[ ] = {1, 2, 3, 4, 5, 6}; • 6 initializers, therefore 6 element array.

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

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

  21. Name of the array The number of the rows The number of the columns Specifying the type of each element 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 ] The accessed element of the array is on Row rowIndex and Column colIndex

  22. 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 ROWSIZE COLSIZE 0 &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); RAM … count 0xBFFFF818 15 … countPtr 0xBFFF924 BFFFF818 …

  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, constchar *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, constchar *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, constchar *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”? char string[25]= “I love EPS II”; char string[25]; strcpy(string, “I love EPS II”; char string[25]; string = “I love EPS II”; char string[25] = {‘I’, ‘ ‘, ‘l’, ‘o’, ‘v’, ‘e’, ‘ ‘, ‘E’, ‘P’, ‘S’, ‘ ‘, ‘I’, ‘I’, ‘\0’}; char string[25]; sprintf(string, “%s”, “I love EPS II”); Solution: C

More Related