Computer Science II CS132/601* Lecture #C-2.

Slides:



Advertisements
Similar presentations
Lectures 10 & 11.
Advertisements

1 Chapter Thirteen Pointers. 2 Pointers A pointer is a sign used to point out the direction.
Programming and Data Structure
Chapter 6 Modular Programming J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University.
Primitive Data Types There are a number of common objects we encounter and are treated specially by almost any programming language These are called basic.
IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
Enumerated Types 4 Besides the built-in types, ANSI C allows the definition of user-defined enumerated types –To define a user-define type, you must give.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Introduction.
Pointers Pointer - A pointer is a derived data type; that is it is a data type built from one of the standard types. Its value is any of the addresses.
1 CSC 1401 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Introduction.
CS 201 Functions Debzani Deb.
Data types and variables
Chapter 2 Data Types, Declarations, and Displays
Pointers Applications
Representation and Conversion of Numeric Types 4 We have seen multiple data types that C provides for numbers: int and double 4 What differences are there.
Chapter 7 Simple Data Types and Function Calls Alkar / Demirer.
Chapter 7 Simple Date Types Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )
UniMAP Sem2-08/09 DKT121: Fundamental of Computer Programming1 Introduction to C – Part 2.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
Chapter 7 Simple Date Types J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
UniMAP Sem1-07/08EKT120: Computer Programming1 Week2.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Pointers.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
Review 1 List Data Structure List operations List Implementation Array Linked List.
Pointers *, &, array similarities, functions, sizeof.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 1.
1 ICS103 Programming in C Lecture 8: Functions I.
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
UNIMAP Sem2-07/08EKT120: Computer Programming1 Week 2 – Introduction to Programming.
Unit 6 Data Types and Arrays. Key Concepts Explicit and automatic conversion ASCII Enumerated types Function parameters Arrays Loops and arrays Passing.
Problem Solving and Program Design in C Chap. 6 Pointers and Modular Programming Chow-Sing Lin.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
CSCI 125 & 161 / ENGR 144 Lecture 16 Martin van Bommel.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
ECE 103 Engineering Programming Chapter 4 Operators Herbert G. Mayer, PSU Status 6/10/2016 Initial content copied verbatim from ECE 103 material developed.
Java Programming: Guided Learning with Early Objects Chapter 1 Basic Elements of Java.
BASIC ELEMENTS OF A COMPUTER PROGRAM
Tokens in C Keywords Identifiers Constants
Chapter 6 Modular Programming Dr. J.-Y. Pan Dept. Comm. Eng.
Basic Elements of C++.
Revision Lecture
Variable Declaration, Data types, Expressions
Values – also known as scalars (eg. int, double, char, float)
Pointer.
Java Programming: From Problem Analysis to Program Design, 4e
Arrays and Records.
Fundamental Data Types
DATA HANDLING.
Basic Elements of C++ Chapter 2.
Object Oriented Programming COP3330 / CGS5409
C Structures, Unions, Bit Manipulations and Enumerations
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
Introduction to Abstract Data Types
Simple Data Types and Function Calls
Chapter 7 Additional Control Structures
C Operators, Operands, Expressions & Statements
Pointers and Dynamic Variables
Lectures on Numerical Methods
Chapter 7 Simple Date Types Dr. Jiung-yao Huang Dept. Comm. Eng.
Fundamental Data Types
What have we learned about when we learned about function parameters?
CS 240 – Lecture 7 Boolean Operations, Increment and Decrement Operators, Constant Types, enum Types, Precedence.
OPERATORS in C Programming
DATA TYPES There are four basic data types associated with variables:
OPERATORS in C Programming
Lecture 7: Types (Revised based on the Tucker’s slides) 10/4/2019
Presentation transcript:

Computer Science II CS132/601* Lecture #C-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.

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.

Function syntax Function interface comments ftype fname(formal parameter declaration list) { local declarations executable statements }

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

Functions with input and a single result . function I N P U T Return . . value .

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.

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.

Sequence { statement1; statement2; statement3; … statementn; } Entry point { statement1; statement2; statement3; … statementn; } statement1 statement2 statementn Exit point

Repetition Entry point statement1 statement2 statementn Exit point

Selection Entry point selection statement1 statement2 Exit points A selection control structure chooses which alternative to execute by testing the value of key variables.

Relational and Equality operators

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

Logical operators && (and) || (or) ! (not) Logical expression: an expression that uses one or more of the logical operators.

Examples salary < MIN_SALARY || dependent > 5 temperature > 90.0 && humidity > 0.90 n >= 0 && n <= 100 n <= 0 && n <= 100 !(0 <= n && n <= 100)

&& || =

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++

Comparison of Prefix and Postfix Increments

Modular programming Using functions to implement a program. Each function has its own functionality, and they work together to solve the problem.

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?

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

pointers make memory locations of variables available to programmers! Pointer: a memory cell whose content is the address of another memory cell.

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

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;

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;

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;

initialize a pointer? int *p=array; or int *p; p=array;

example int x, y; int *p1, *p2; 1000 x 1004 y 1008 p1 1012 p2

example int x, y; int *p1, *p2; x=-42; y=163; -42 1000 x 163 1004 y 1008 p1 1012 p2

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

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

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

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

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.

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

163 1000 x x=163; SetToZero(x); void SetToZero (int var) { var=0; } 1004 stack frame 1008 1012 163 1208 var stack frame 1212

163 1000 x x=163; SetToZero(x); void SetToZero (int var) { var=0; } 1004 stack frame 1008 1012 1208 var stack frame 1212

163 1000 x x=163; SetToZero(&x); void SetToZero(int *ip) { *ip=0; } 1004 stack frame 1008 1012 1000 1208 ip stack frame 1212

1000 x x=163; SetToZero(&x); void SetToZero(int *ip) { *ip=0; } 1004 stack frame 1008 1012 1000 1208 ip stack frame 1212

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;

Effects of & Operator Declaration Data Type (x) Data Type (&x) char x char char * int x int int * double x double double *

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.

Comparison of Direct and Indirect Reference

Meaning of * symbol * : binary operator a * b char *signp // pointer to Unary * means follow the pointer e.g *signp = ‘+’

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

Data Areas After temp = *smp; During Call order(&num1, &num3);

Formal output parameters as actual arguments A function needs to pass its own output parameter as an argument when it calls another function

Function scan_fraction (incomplete)

Data Areas for scan_fraction and Its Caller

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

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

Internal Formats of Type int and Type double

Different range double: short int In ANSI specification: 10-37 to 1037 -32767 to 32767 (-215 to 215) int --2147483647 … 2147483647 (-231 to 231)

Program to Print Implementation-Specific Ranges for Positive Numeric Data

Integer Types in C short -32767 … 32767 unsigned short 0 … 65535 unsigned int 0 … 4294967295

Double (floating point) types in C long double 10-4931 … 104932

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=0.333333333…….. Depends on the number of bits used in mantissa: the more bits, the smaller the error.

Example for (trial = 0.0; trial != 10.0; trial = trial + 0.1) { ….. }

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

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

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.

Program to Print Part of the Collating Sequence

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;

Enumerated Type for Budget Expenses

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

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.

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.

The Eight Elements of Array x

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

Consider the following declarations as you determine if each of assignment statements 1 - 7 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]

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.

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

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

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

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

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

pointer arithmetic *p++ is equivalent to *(p++); recall that ++ has higher precedence over *, then this statement means what? 1. dereference p; 2. increment p

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

differences between pointers and arrays declarations int array[5]; /*memory allocated for 5 integers*/ int *p; /*memory allocated for 1 pointer to integer*/

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

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.

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

Data Area for Calling Module and Function do_it

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.

Function fill_array

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)

Data Areas Before Return from fill_array (x, 5, 1);

Using *list instead of list[] int list[] and int *list are compatible.

Arrays as input arguments

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

Diagram of a Function That Computes an Array Result

Returning an array result

Function Data Areas for add_arrays(x, y, x_plus_y, 5);

Comments When use arrays as parameters, though the address-of operator (&) not used, the system still pass the address of the first element.