Lecture 22: Reviews for Exam 2

download Lecture 22:  Reviews for Exam 2

If you can't read please download the document

description

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. - PowerPoint PPT Presentation

Transcript of Lecture 22: Reviews for Exam 2

  • Lecture 22: Reviews for Exam 2

  • FunctionsArraysPointersStringsC Files

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

  • Function Definitions return-value-type function-name( parameter-list ){definitionsstatements}Returning controlIf nothing returned

    If something returned

    Defining function with array parametersreturn;Or, until reaches right brace.return expression;The functions parameter list must specify that an array will be received.void myFunc( int ary[ ], int size ) {..}

  • Function Definitions - Example#include

    #define SIZE 5int 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 )

  • Function Calls Invoking functions (by a function call)Provide function name and arguments (data)Function returns results#include

    #define SIZE 5int 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 */

  • Function Prototypes Prototype only needed if function definition comes after use in programFormatreturn-value-type function-name( parameter-list );Parameter names are not necessarily included in the function prototype.A function prototype is used to validate functionsThe type of data returned by the functionThe number of parameters the function expected to receiveThe types of the parametersThe order in which these parameters are expected.

  • 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 );

  • Call-by-ValueCopy of argument passed to functionChanges in function do not effect originalUse when function does not need to modify argumentTo avoid accidental changesVariables of type int, float, double, char are passed to a function by value.Elements of arrays are passed to a function by value.

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

    Q: What is the output of the following program?

    #include

    int nosense(int x, int y);

    int main() {

    int a = 3;

    int b = 5;

    b = nosense(a,b);

    printf ("a + b = %d\n", a + b);

    }

    int nosense(int x, int y) {

    x = x * x;

    y = y * 2;

    return y;

    }

    A) a + b = 8

    B) a + b = 13

    C) a + b = 14

    D) a + b = 19

  • Call-by-ReferencePasses original argumentChanges made to parameter in function effect original argumentOnly used with trusted functionsArrays, strings, and pointers are passed to a function by reference.

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

    #include

    int nosense(int *x, int y);

    int main() {

    int a = 2;

    int b = 3;

    nosense(&a, b);

    printf ("a + b = %d\n", a + b);

    return 0;

    }

    int nosense(int *x, int y) {

    *x = *x * y;

    y += *x;

    return (x+y);

    }

    A) a + b = 5

    B) a + b = 9

    C) a + b = 15

    D) a + b = 11

  • 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;} 1 2 2 4 2 6 2 12 Solution: B

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

    #include#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);}

  • Scope RulesThe scope of an identifier is the portion of the program in which the identifier can be referenced.File scopeIdentifier 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 prototypesBlock scopeIdentifier declared inside a blockBlock scope begins at definition, ends at the terminating right brace ({) of the block.Used for local variables, function parametersOuter blocks hidden from inner blocks if there is a variable with the same name in the inner block

  • ArraysAn array is a data structure consisting of related data items of the same type.Stored in a group of memory locationsDefining arraysint arrayName[ 100 ];

    Examples int a[5]; float b[120], x[24];

  • Referring to Array ElementsFormatarrayName[ position number ]First element at position 0The 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.

  • Initializing the ArrayUsing a for loop to initialize the arrays elementsInitializing an array in a definition with an initializer listDefining 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 occursIf size omitted, # of initializers determine the sizeint n[ ] = {1, 2, 3, 4, 5, 6};6 initializers, therefore 6 element array.

  • 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? 2597 Solution: D

  • Practice Question #define SIZE 5

    int aray[SIZE] = {2, 3, 4, 5};

    Q. What is the value of aray[5]? 04Not sure5 Q. What is the value of aray[1]? 20Not sure3 Solution: CSolution: D

  • Two-Dimensional ArraysDefine a two-dimensional array #define ROWSIZE 3 #define COLUMNSIZE 4

    int arrayName[ ROWSIZE ][ COLUMNSIZE ];

    Refer to two-dimensional array elementsarrayName[ rowIndex ][ colIndex ]

    The accessed element of the array is on Row rowIndex and Column colIndex

    Sheet1

    2-32325

    5917-13

    10098

  • 0Initializing Two-Dimensional ArraysUsing 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}};0COLSIZEROWSIZE&a[row][col]

    Sheet1

    2-32325

    5917-13

    10098

  • PointersPointer variables contain memory addresses as their valuesDeclare 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);count0xBFFFF81815BFFFF818RAMcountPtr0xBFFF924

  • StringsA 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 stringsprintf(%s\n, str);k = 0;while ( ) {printf(%c, str[k]);k ++;}str[k] != \0

  • String Handling Functionsint 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);

  • String Handling Functionschar *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);

  • 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

    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.Passing a 2-D array to a function, what does the prototype look like?