27
Lecture 22: Reviews for Exam 2

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

Embed Size (px)

Citation preview

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

Lecture 22: Reviews for Exam 2

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

Functions

Arrays

Pointers

Strings

C Files

Page 3: Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C 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 nothing

parameter-list: comma-separated list

Specifies the parameters received by the function when it is called.

Function header

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

Function Definitions

return-value-type function-name( parameter-list ){

definitionsstatements

}

Returning controlIf 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.

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

Function Definitions - Example

#include<stdio.h>

#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 )

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

Function Calls

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

#include<stdio.h>

#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 */

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

Function Prototypes

Prototype only needed if function definition comes after use in program

Formatreturn-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 function

The number of parameters the function expected to receive

The types of the parameters

The order in which these parameters are expected.

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

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 )

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

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

Call-by-Value

Copy of argument passed to functionChanges in function do not effect originalUse when function does not need to modify argument

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

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

Call-by-Value: Practice Question

Q: What is the output of the following program? #include <stdio.h> 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

Solu

tion

: B

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

Call-by-Reference

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

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

Call-by-Reference: Practice Question

Q. What is the output of the following program?

#include <stdio.h> 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

Solu

tion

: B

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

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;}

A. 1 2B. 2 4C. 2 6D. 2 12

Solu

tion

: B

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

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); return 0;}

void chgString(char s[ ]){ char s2[ ] = "It is great!"; strcpy(s, s2);}

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

Scope RulesThe 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 scopeIdentifier declared inside a block

Block 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

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

ArraysAn array is a data structure consisting of related data items of the same type.Stored in a group of memory locationsDefining 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

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

Referring to Array ElementsFormat

arrayName[ 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.

Formally called a subscript or an index

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

Initializing the ArrayUsing a for loop to initialize the array’s elementsInitializing 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 sizeint n[ ] = {1, 2, 3, 4, 5, 6};

6 initializers, therefore 6 element array.

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

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. 2B. 5C. 9D. 7

Solu

tion

: D

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

Practice Question

#define SIZE 5

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

Q. What is the value of aray[5]?

A. 0B. 4C. Not sureD. 5

Q. What is the value of aray[1]?

A. 2B. 0C. Not sureD. 3

Solu

tion

: CS

olu

tion

: D

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

Two-Dimensional Arrays

Define a two-dimensional array #define ROWSIZE 3 #define COLUMNSIZE 4

int arrayName[ ROWSIZE ][ COLUMNSIZE ];

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

2 -3 23 25

5 9 17 -13

10 0 9 8

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

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

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}};

2 -3 23 25

5 9 17 -13

10 0 9 8

0COLSIZEROWSIZE

&a[row][col]

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

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

……

count0xBFFFF818

15

BFFFF818

RAM

countPtr0xBFFF924

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

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’

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

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

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

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

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

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”;

A. char string[25] = {‘I’, ‘ ‘, ‘l’, ‘o’, ‘v’, ‘e’, ‘ ‘, ‘E’, ‘P’, ‘S’, ‘ ‘, ‘I’, ‘I’, ‘\0’};

B. char string[25];sprintf(string, “%s”, “I love EPS II”);

Solu

tion

: C