Download presentation
Presentation is loading. Please wait.
1
Computer Science II CS132/601* Lecture #C-2
2
Advantages of using subprograms
Better cooperation among a group of programmers. Procedural abstraction in main function: a sequence of function call statements Reuse of function subprograms functions can be executed more than once in a program.
3
Function with input arguments
Input arguments: arguments used to pass information into a function subprogram Output arguments: arguments used to return results to the calling function Very important concept.
4
Function syntax Function interface comments ftype
fname(formal parameter declaration list) { local declarations executable statements }
5
Void functions with input args.
/* Display a real number in a box */ void print_rboxed(double rnum) { printf(“*************\n”); printf(“* *\n”); printf(“* %7.2f *\n”); printf(“* *\n); } E.g: actual argument(135.68), formal parameter: rnum
6
Functions with input and a single result
. function I N P U T Return . . value .
7
Functions with multiple args.
Examples: pow(x, y), scale(x, n) The order of the actual arguments used in the function calls must correspond to the order of the formal parameters listed in the function prototype.
9
Control structure Control structure: Control the flow of the program execution. It enables the programmer to combine individual instructions into a single logic unit with one entry point and one exit point. Sequence, selection and repetition. Compound statement, written as a group of statements bracketed by { and } is used to specify a sequential flow.
10
Sequence { statement1; statement2; statement3; … statementn; }
Entry point { statement1; statement2; statement3; … statementn; } statement1 statement2 statementn Exit point
11
Repetition Entry point statement1 statement2 statementn Exit point
12
Selection Entry point selection statement1 statement2 Exit points A selection control structure chooses which alternative to execute by testing the value of key variables.
13
Relational and Equality operators
14
Example Conditions: x<=0 Power < MAX_POW x>=y
x power MAX_POW y item MIN_ITEM m_o_d num SENTINEL -5 1024 1024 7 1.5 -999.0 ‘M’ 999 999 Conditions: x<=0 Power < MAX_POW x>=y Item> MIN_ITEM m_o_d == ‘M’ num != SENTINEL
15
Logical operators && (and) || (or) ! (not)
Logical expression: an expression that uses one or more of the logical operators.
16
Examples salary < MIN_SALARY || dependent > 5
temperature > 90.0 && humidity > 0.90 n >= 0 && n <= 100 n <= 0 && n <= 100 !(0 <= n && n <= 100)
17
&& || =
18
Increment and decrement operators
Increment op: ++ for (counter = 0; counter < limit; counter++) Decrement op: -- printf(“%3d”, --n); Side effect: a change in the value of a variable as a result of carrying out an operation. ++n, n++
19
Comparison of Prefix and Postfix Increments
20
Modular programming Using functions to implement a program. Each function has its own functionality, and they work together to solve the problem.
21
Functions with simple output parameters
Argument list: provide the communication links between the main functions and its function subprograms. When a function is called, memory space will be allocated for each formal parameter. How a function sends back multiple outputs to the function that calls it?
22
data, memory memory address: every byte is identified by a numeric address in the memory. once a variable is defined, one cannot predict its memory address, entirely determined by the system. example: int temp; a data value requiring multiple bytes are stored consecutively in memory cells and identified by the address of the first byte find the amount of memory (num. of bytes) assigned to a variable or a data type? sizeof(int), or sizeof x
23
pointers make memory locations of variables available to programmers!
Pointer: a memory cell whose content is the address of another memory cell.
24
advantages of pointers
Allow one to refer to a large data structure in a compact way. Each pointer value (or memory address typically fits in four bytes of memory)! Different parts of a program can share the same data: passing parameters by reference (passing address between different functions) One can reserve new memory in a running program: dynamic memory allocation Build complicated data structures by linking different data items
25
pointer value is the address of an lvalue.
lvalue: any expression that refers to an internal memory location capable of storing data. It appears on the left hand side of an assignment. Example: x=1.0;
26
declaring pointer variables
examples: int *p; char *cptr; note: pointers to different data types (base types) are different! difference? int *p1, *p2; int *p1, p2;
27
fundamental pointer operations
& address-of * value-pointed-to they are used to move back and forth between values and pointers to those values. * also called dereferencing operation. difference? int *p; *p=5;
28
initialize a pointer? int *p=array; or int *p; p=array;
29
example int x, y; int *p1, *p2; 1000 x 1004 y 1008 p1 1012 p2
30
example int x, y; int *p1, *p2; x=-42; y=163; -42 1000 x 163 1004 y
1008 p1 1012 p2
31
example int x, y; int *p1, *p2; x=-42; y=163; p1=&x; p2=&y; -42 1000 x
1004 y 1000 1008 p1 1004 1012 p2
32
example int x, y; int *p1, *p2; x=-42; y=163; p1=&x; p2=&y;
*p1=17; /* another name of for x*/ -42 1000 x 163 1004 y 1000 1008 p1 1004 1012 p2 17 163 1000 1004 1008 1012 x y p1 p2
33
example int x, y; int *p1, *p2; x=-42; y=163; p1=&x; p2=&y;
*p1=17; /* another name of for x*/ p1=p2; /* pointer assignment, now two pointers point to the same lacation*/ 17 1000 x 163 1004 y 1000 1008 p1 1004 1012 p2 17 163 1004 1000 1008 1012 x y p1 p2
34
example int x, y; int *p1, *p2; x=-42; y=163; p1=&x; p2=&y;
*p1=17; /* another name of for x*/ *p1=*p2; /*value assignment*/ 17 1000 x 163 1004 y 1000 1008 p1 1004 1012 p2 163 1000 1004 1008 1012 x y p1 p2
35
NULL pointer assign NULL constant to a pointer variable to indicate that it does not point to any valid data internally, NULL is value 0.
36
passing parameters by reference
suppose we want to set x to zero, compare the following code: /*pass by value*/ void SetToZero (int var) { var=0; } SetToZero(x); /*pass by reference*/ void SetToZero(int *ip) { *ip=0; SetToZero(&x);
37
163 1000 x x=163; SetToZero(x); void SetToZero (int var) { var=0; } 1004 stack frame 1008 1012 163 1208 var stack frame 1212
38
163 1000 x x=163; SetToZero(x); void SetToZero (int var) { var=0; } 1004 stack frame 1008 1012 1208 var stack frame 1212
39
163 1000 x x=163; SetToZero(&x); void SetToZero(int *ip) { *ip=0; } 1004 stack frame 1008 1012 1000 1208 ip stack frame 1212
40
1000 x x=163; SetToZero(&x); void SetToZero(int *ip) { *ip=0; } 1004 stack frame 1008 1012 1000 1208 ip stack frame 1212
41
passing parameters by reference
suppose we want to set x to zero, compare the following code: void SetToZero (int var) { var=0; } SetToZero(x); /* has no effect on x*/ void SetToZero(int *ip) { *ip=0; SetToZero(&x); /* x is set to zero, call by reference */ DEMO: demo02a.c stack frame stack frame SetToZero(x); var=x; var=0; stack frame stack frame SetToZero(x); ip=&x; *ip=0;
42
Effects of & Operator Declaration Data Type (x) Data Type (&x)
char x char char * int x int int * double x double double *
43
Indirection operator: unary *
When the unary * operator is applied to a reference that is of some pointer type, it has the effect of following the pointer referenced by its operand.
44
Comparison of Direct and Indirect Reference
45
Meaning of * symbol * : binary operator a * b
char *signp // pointer to Unary * means follow the pointer e.g *signp = ‘+’
46
Multiple calls to a function with input/output parameters
Use a single parameter both to bring a data value into a function and to carry a result value out of the function
49
Data Areas After temp = *smp; During Call order(&num1, &num3);
50
Formal output parameters as actual arguments
A function needs to pass its own output parameter as an argument when it calls another function
51
Function scan_fraction (incomplete)
53
Data Areas for scan_fraction and Its Caller
54
Simple (scalar) data types
A data type used to store a single value. No any programming languages can predefine all the data types needed Both C’s standard types and user-defined enumerated types are simple, or scalar, data types. (only a single value can be stored in a variable of each type).
55
Difference between numeric types
Type double can be used to represent all numbers, but we use type int due to: Operations on int are faster Storage space needed for int is smaller Operations on integers are precise, on doubles may loss accuracy (round-off error) Reason: format in system memory 0s and 1s
56
Internal Formats of Type int and Type double
57
Different range double: short int In ANSI specification: 10-37 to 1037
to (-215 to 215) int … (-231 to 231)
58
Program to Print Implementation-Specific Ranges for Positive Numeric Data
59
Integer Types in C short -32767 … 32767 unsigned short 0 … 65535
unsigned int 0 …
60
Double (floating point) types in C
long double …
61
Numerical inaccuracy Representational error (round-off error)
An error due to coding a real number as a finite number of binary digits e.g. 1/3= …….. Depends on the number of bits used in mantissa: the more bits, the smaller the error.
62
Example for (trial = 0.0; trial != 10.0; trial = trial + 0.1) { ….. }
63
Numerical inaccuracy (Cont.)
Cancellation error: an error resulting from applying an arithmetic operation to operands of vastly different magnitudes; effects of smaller operand is lost. Arithmetic underflow: an error in which a very small computational result is represented as zero Arithmetic overflow: an error that is an attempt to represent a computational result that is too large
64
Automatic conversion of data types
int k=5, m=4, n; double x=1.5, y=2.1, z; k+x z=k/m n=x*y
65
Representation and conversion of type char
Each character has its own unique numeric code, we can compare character values using ==, !=, <, >, <= and >=. ASCII (American Standard Code for Information Interchange) is used Collating sequence: a sequence of characters by character code number.
66
Program to Print Part of the Collating Sequence
67
Enumerated types A data type whose list of values is specified by the programmer in a type declaration. Enumeration constant: an identifier that is one of the values of an enumerated type Example: typedef enum {entertainment, rent, utilities, food, clothing, automobile, insurance, miscellaneous} expense_t; Delcaration: expense_t expense_kind;
68
Enumerated Type for Budget Expenses
71
Enumerated type definition
Syntax: typedef enum {identifier_list} enum_type; The first identifier is represented by 0, the second is 1, and so on. Example: typedef enum {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday} day_t; Operations: Sunday < Monday, Tuesday != Sunday C handles enumerated type values as integers
72
Array Simple data types use a single memory cell to store a variable.
Complex data types are more efficient to group data items together Array: a collection of data items of the same type.
73
Declaring and referencing arrays
An array is a collection of two or more adjacent memory cells (array elements) Array element: a data item that is part of an array Declaration: double x[8]; Subscripted variable: a variable followed by a subscript in brackets, designating an array element. E.g. x[0], x[1] Array subscript: a variable or expression enclosed in brackets after the array name, specifying which array element to access.
74
The Eight Elements of Array x
75
Statements that manipulate array
Printf(“%.lf”, x[0]); X[3]=25.0; Sum=x[0]+x[1]; Sum+=x[2]; X[3]+=1.0; X[2]=x[0]+x[1];
76
Consider the following declarations as you determine if each of assignment statements is valid. Answer True if the statement is valid, False otherwise. #define HALF_CENT 50 #define A_SIZE 26 char a_list[HALF_CENT], b_list[HALF_CENT], a_char = 'v'; int nums[A_SIZE], vals[A_SIZE], i = 1; 1. nums[0] = nums[25]; [True] 2. nums = vals + 1; [False] 3. a_list[50] = 'd'; [False] 4. b_list[30] = 0.37 * vals[1]; [False] 5. a_list = b_list; [False] 6. nums[5] = (int)a_char; [True] 7. for (i = 1; i <= A_SIZE; ++i) nums[A_SIZE - i] = i; [True]
77
What value is returned by function result?
int result(const int a[], int n) { int i, r; r = 0; for (i = 1; i < n; ++i) if (a[i] > a[r]) r = i; return (r); } a. The subscript of the largest of the first n elements of array a. b. The value of the largest of the first n elements of array a. c. The subscript of the smallest of the first n elements of array a. d. The value of the smallest of the first n elements of array a. e. The subscript of the last element greater than its predecessor within the first n elements of array a.
78
pointers and arrays 1000 list[0] 1008 list[1] 1016 list[2] 1024
double list[3]; &list[1] ? 1008 how does the system find out this address? 1000+1*8
79
pointer arithmetic 1000 1.0 list[0] 1008 1.1 list[1] 1016 1.2 list[2]
pointer arithmetic must take into account the size of the base type. double list[3]={1.0, 1.1, 1.2}; double *p; what’s in p after the following operations? p=&list[0]; p=p+2; /*recall each double value takes 8 bytes*/ p=p-1; 1000 1.0 list[0] 1008 1.1 list[1] 1016 1.2 list[2] 1024 p
80
pointer arithmetic pointer arithmetic must take into account the size of the base type. p=&list[0]; p=p+2; /*recall each double value takes 8 bytes*/ p=p-1; 1000 list[0] 1008 list[1] 1016 list[2] 1024 p
81
pointer arithmetic it makes no sense to use *, /, % in pointer arithmetic one cannot add two pointers together: p1+p2 is illegal but one can subtract one pointer from another pointer: p1-p2 is legal
82
valid pointer operations
assignment of pointers of the same type add or substract a pointer and an integer substract or compare two pointers to members of the same array assign or compare to zero
83
pointer arithmetic *p++ is equivalent to *(p++);
recall that ++ has higher precedence over *, then this statement means what? 1. dereference p; 2. increment p
84
relationship between pointers and arrays
array name is a pointer to the first elem in the array. int intList[5]; /* intList same as &intList[0] */ array name and pointer are treated the same when passing parameters in function calls. sum=sumIntegerArray(intList, 5); these two prototypes are the same int sumIntegerArray(int array[], int n); int sumIntegerArray(int *array, int n);
85
differences between pointers and arrays
declarations int array[5]; /*memory allocated for 5 integers*/ int *p; /*memory allocated for 1 pointer to integer*/
86
differences between pointers and arrays
pointer is a variable, but array name is not a variable! int intList[5]; intList=p; /*incorrect uses*/ intList++; /*incorrect uses*/
87
Using array elements as function arguments
You can use array elements as parameters for system functions. scanf(“%f”, &x[i]); printf(“%f”, x[i]-mean); You can also pass array elements as parameters in the functions defined by yourself.
88
Example void do_it(double arg_1, double *arg2_p, double *arg3_p);
do_it(p, &q, &r); do_it(x[0], &x[1], &x[2]);
89
Data Area for Calling Module and Function do_it
90
Using arrays as the arguments
We can use arrays as arguments as well. The address of the initial array element will be stored in the function’s corresponding formal parameter. Such functions can manipulate any elements in the arrays.
91
Function fill_array
92
Usage fill_array(y, 10, num) it equals to fill_array(&y[0], 10, num)
fill_array(x, 5, 1) fill_array(&x[0], 5,1)
93
Data Areas Before Return from fill_array (x, 5, 1);
94
Using *list instead of list[]
int list[] and int *list are compatible.
95
Arrays as input arguments
96
Array Input Parameter Syntax:
const element-type array-name[] or const element-type *array-name int get_min_sub(const double data[], int data_size) { int I, small_sub=0; for(i=0;i<data_size;++i) if (data[i]<data[small_sub]) small_sub=I; return(small_sub); }
97
Diagram of a Function That Computes an Array Result
98
Returning an array result
99
Function Data Areas for add_arrays(x, y, x_plus_y, 5);
100
Comments When use arrays as parameters, though the address-of operator (&) not used, the system still pass the address of the first element.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.