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

Download Report

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

Lecture 22: Reviews for
Exam 2
Functions
Arrays
Pointers
Strings
C Files
Function Definitions
return-value-type function-name( parameter-list )
{
definitions
statements
}
Function header
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 Definitions
return-value-type function-name( parameter-list )
{
definitions
statements
}
Function header
Returning control
If nothing returned
return;
Or, until reaches right brace.
If something returned return expression;
Defining function with array parameters
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.
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 sumValue(
sumValue(
int x[ ], int size )
{
int k, sum = 0;
for (k = 0; k < size; k++) {
sum += x[k];
}
return sum;
}
)
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 = sumValue( a, SIZE ); /* call sumValue( ); passing array a and SIZE */
printf(“%d\n”, total);
return 0;
}
int sumValue( int x[ ], int size )
{
int k, sum = 0;
for (k = 0; k < size; k++) {
sum += x[k];
}
return sum;
}
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 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.
Function Prototypes - Example
#include<stdio.h>
#define SIZE 5
int sumValue( int x[ ], int size ); /* function prototype */
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 sumValue( int x[ ], int size )
{
int k, sum = 0;
for (k = 0; k < size; k++) {
sum += x[k];
}
return sum;
}
int sumValue( int [ ], int );
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-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.
Call-by-Value: Practice Question
Q: What is the output of the foll owing 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;
}
Solution: B
A) a + b = 8
B) a + b = 13
C) a + b = 14
D) a + b = 19
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.
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
Solution: B
}
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.
B.
C.
D.
1
2
2
2
2
4
6
12
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);
}
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
Arrays
An array is a data structure consisting of related data
items of the same type.
memory
Stored in a group of memory locations
Defining arrays Name of the array
int arrayName[ 100 ];
Specifying the type of each element
Examples
int a[5];
float b[120], x[24];
The number of the elements
a[0]
a[1]
10
a[2]
15
a[3]
a[4]
3
5
23
Referring to Array Elements
Formally called a subscript
Format
or an index
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.
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.
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]);
A.
B.
C.
D.
2
5
9
7
Solution: D
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
A.
B.
C.
D.
Q. What is the value of aray[1]?
2
0
Not sure
3
Solution: D
A.
B.
C.
D.
Two-Dimensional Arrays
Define a two-dimensional array
#define ROWSIZE 3
#define COLUMNSIZE 4
Name of the array
2
-3 23 25
5
9
10
0
17 -13
9
int arrayName[ ROWSIZE ][ COLUMNSIZE ];
Specifying the type of each element
The number of the rows
The number of the columns
Refer to two-dimensional array elements
arrayName[ rowIndex ][ colIndex ]
The accessed element of the array is on Row rowIndex and Column colIndex
8
Initializing Two-Dimensional Arrays
Using nested loops
#define ROWSIZE 3
#define COLSIZE 4
int a[ ROWSIZE ][ COLSIZE ];
int row, col;
2
-3 23 25
5
9
10
0
17 -13
9
for (row = 0 ; row < ROWSIZE ; row ++) {
for (col = 0 ; col < COLSIZE ; col ++) {
printf(“Enter the element a[%d][%d]: ”, row, col);
scanf(“%d”, &a[row][col]);
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}};
8
Pointers
Pointer variables contain memory addresses as their
values
RAM
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;
count
0xBFFFF818
countPtr
0xBFFF924
15
BFFFF818
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);
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 ( str[k] != ‘\0’ ) {
printf(“%c”, str[k]);
k ++;
}
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);
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.”;
strcat(s1, s2);
strncat(s1,
s2, 5);
• 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.
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