Lecture 04 FUNCTIONS AND ARRAYS

Similar documents
Lecture 04 FUNCTIONS AND ARRAYS

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

C Functions. 5.2 Program Modules in C

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables

C: How to Program. Week /Apr/23

C: How to Program. Week /Apr/16

CSE123. Program Design and Modular Programming Functions 1-1

Function Call Stack and Activation Records

C Arrays Pearson Education, Inc. All rights reserved.

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

C++ PROGRAMMING SKILLS Part 4: Arrays

Outline Introduction Arrays Declaring Arrays Examples Using Arrays Passing Arrays to Functions Sorting Arrays

C Functions Pearson Education, Inc. All rights reserved.

Functions. Systems Programming Concepts

Array. Arrays. Declaring Arrays. Using Arrays

Chapter 3 - Functions

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program)

Chapter 6. Arrays. Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

C Functions. CS 2060 Week 4. Prof. Jonathan Ventura

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types

Chapter 5 - Functions

Chapter 5 C Functions

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

Functions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa

CSE101-Lec#17. Arrays. (Arrays and Functions) Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

Arrays. Systems Programming Concepts

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

Chapter 3 - Functions

Programming for Engineers Functions

C++ How to Program, 9/e by Pearson Education, Inc. All Rights Reserved.

Introduction to C Final Review Chapters 1-6 & 13

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

Chapter 3 - Functions

C How to Program, 7/e by Pearson Education, Inc. All Rights Reserved.

Content. In this chapter, you will learn:

Functions and Recursion

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

Lecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch

Programming for Engineers Arrays

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from

Chapter 7 Array. Array. C++, How to Program

Programming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming.

CS101 Introduction to computing Function, Scope Rules and Storage class

Programming Assignment #4 Arrays and Pointers

6.5 Function Prototypes and Argument Coercion

Outline Arrays Examples of array usage Passing arrays to functions 2D arrays Strings Searching arrays Next Time. C Arrays.

C Functions. Object created and destroyed within its block auto: default for local variables

Arrays. Week 4. Assylbek Jumagaliyev

C++ Programming Lecture 11 Functions Part I

Lab Instructor : Jean Lai

ONE DIMENSIONAL ARRAYS

Fundamentals of Programming Session 13

C Programming for Engineers Functions

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

Objectives of This Chapter

Matlab? Chapter 3-4 Matlab and IPT Basics. Working Environment. Matlab Demo. Array. Data Type. MATLAB Desktop:

Unit 7. Functions. Need of User Defined Functions

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

Arrays and Applications

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays)

Chapter 4 Functions By C.K. Liang

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

IS 0020 Program Design and Software Tools

Computer Science & Engineering 150A Problem Solving Using Computers

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0)

CSE 2421: Systems I Low-Level Programming and Computer Organization. Functions. Presentation C. Predefined Functions

BBS 514 YAPISAL PROGRAMLAMA (STRUCTURED PROGRAMMING)

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 3. Existing Information. Notes. Notes. Notes. Lecture 03 - Functions

Functions in C C Programming and Software Tools

Chapter 7 Functions. Now consider a more advanced example:

Functions. Introduction :

Pace University. Fundamental Concepts of CS121 1

Functions. Lecture 6 COP 3014 Spring February 11, 2018

Pointers. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations

C Pointers. sizeof Returns size of operand in bytes For arrays: size of 1 element * number of elements if sizeof( int ) equals 4 bytes, then

CME 112- Programming Languages II. Week 1 Introduction, Scope Rules and Generating Random Numbers

Lecture 9 - C Functions

Principles of Programming. Chapter 6: Arrays

Dynamic memory allocation

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science

C Pointers Pearson Education, Inc. All rights reserved.

Chapter 3. Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus. Existing Information.

A First Book of ANSI C Fourth Edition. Chapter 8 Arrays

Computer Science & Engineering 150A Problem Solving Using Computers

Introduction to Computers II Lecture 4. Dr Ali Ziya Alkar Dr Mehmet Demirer

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

C Arrays. O b j e c t i v e s In this chapter, you ll:

Methods (Deitel chapter 6)

Functions and Recursion

Two Dimensional Array - An array with a multiple indexs.

Transcription:

Lecture 04 FUNCTIONS AND ARRAYS 1

Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions to reduce code duplication and increase program modularity. Easy to: Design Implement Test Maintain Reuse 2

Function of Functions Decomposition and abstraction through functions Break up into modules Suppress detail Create new primitive 3

Functions, Informally A function is like a subprogram, a small program inside of a program. The basic idea we write a sequence of statements and then give that sequence a name. We can then execute this sequence at any time by referring to the name. 4

Functions, Informally The part of the program that creates a function is called a function definition. When the function is used in a program, we say the definition is called or invoked. 5

Functions Modules in C Program Modules in C Programs written by combining user-defined functions with library functions C standard library has a wide variety of functions Makes programmer's job easier - avoid reinventing the wheel

Program Modules in C Function calls Invoking functions Provide function name and arguments (data) Function performs operations or manipulations Function returns results Boss asks worker to complete task Worker gets information, does task, returns result Information hiding: boss does not know details 7

Parameters and arguments Inside the function, the values that are passed get assigned to variable called parameters Void sing(person) The values that control how the function does its job called arguments (real values) Sing( Bob ) 8

Math Library Functions Math library functions perform common mathematical calculations #include <math.h> Format for calling functions FunctionName (argument); If multiple arguments, use comma-separated list printf( "%.2f", sqrt( 900.0 ) ); Calls function sqrt, which returns the square root of its argument All math functions return data type double Arguments may be constants, variables, or expressions 9

Functions Functions Modularize a program All variables declared inside functions are local variables Known only in function defined Parameters Communicate information between functions Local variables 10

Benefits Divide and conquer Functions Manageable program development Software reusability Use existing functions as building blocks for new programs Abstraction - hide internal details (library functions) Avoids code repetition 11

Function Definitions Function definition format return-value-type function-name( parameter-list ) { declarations and statements } Function-name: any valid identifier Return-value-type: data type of the result (default int) void - function returns nothing Parameter-list: comma separated list, declares parameters (default int) 12

Function Definitions (II) return-value-type function-name( parameter-list ) { declarations and statements } Declarations and statements: function body (block) Variables can be declared inside blocks (can be nested) Function can not be defined inside another function Returning control If nothing returned return; or, until reaches right brace If something returned return expression; 13

Examples 14

Function prototype Function name Function Prototypes Parameters - what the function takes in Return type - data type function returns (default int) Used to validate functions Prototype only needed if function definition comes after use in program int maximum( int, int, int ); Takes in 3 ints Returns an int Promotion rules and conversions Converting to lower types can lead to errors 15

Header files Header Files contain function prototypes for library functions <stdlib.h>, <math.h>, etc Load with #include <filename> #include <math.h> Custom header files Create file with functions Save as filename.h Load in other files with #include "filename.h" Reuse functions 16

Calling Functions: Call by Value Used when invoking functions 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 Avoids accidental changes 17

Call by reference (*) Call by Reference Passes original argument Changes in function effect original Only used with trusted functions 18

Storage Classes Storage class specifies Storage duration - how long an object exists in memory Scope - where object can be referenced in program Linkage - what files an identifier is known 19

Automatic storage Storage Classes Object created and destroyed within its block auto: default for local variables auto double x, y; register: tries to put variable into high-speed registers Can only be used for automatic variables register int counter = 1; 20

Static storage Storage Classes Variables exist for entire program execution Default value of zero static: local variables defined in functions. Keep value after function ends Only known in their own function (for different calls of functions) Static functionname makes it invisible outside the file extern: default for global variables and functions. Known in any function A declaration not a definition 21

Scope Rules File scope Identifier defined outside function, known in all functions Global variables, function definitions, function prototypes Function scope Can only be referenced inside a function body Only labels (start: case:, etc.) 22

Block scope Scope Rules Identifier declared inside a block Block scope begins at declaration, ends at right brace Variables, function parameters (local variables of function) Outer blocks "hidden" from inner blocks if same variable name Function prototype scope Identifiers in parameter list Names in function prototype optional, and can be used anywhere 23

Outline 1. Function prototypes 1.1 Initialize global variable 1.2 Initialize local variable 1.3 Initialize local variable in block 2. Call functions 3. Output results

Outline 3.1 Function definitions

Outline Program Output

Recursive functions Recursion Function that calls itself Can only solve a base case Divides up problem into What it can do What it cannot do - resembles original problem Launches a new copy of itself (recursion step) Eventually base case gets solved Gets plugged in, works its way up and solves whole problem 27

Example: factorial: 5! = 5 * 4 * 3 * 2 * 1 Notice that 5! = 5 * 4! 4! = 4 * 3!... Recursion Can compute factorials recursively Solve base case (1! = 0! = 1) then plug in 2! = 2 * 1! = 2 * 1 = 2; 3! = 3 * 2! = 3 * 2 = 6; 28

The Fibonacci Sequence Fibonacci series: 0, 1, 1, 2, 3, 5, 8... Each number sum of the previous two fib(n) = fib(n-1) + fib(n-2) - recursive formula long fibonacci(long n) { if (n==0 n==1) //base case return n; else return fibonacci(n-1) + fibonacci(n-2); } 29

The Fibonacci Sequence f( 3 ) return f( 2 ) + f( 1 ) return f( 1 ) + f( 0 ) return 1 return 1 return 0 30

Outline 1. Function prototype 1.1 Initialize variables 2. Input an integer 2.1 Call function fibonacci 2.2 Output results. 3. Define fibonacci recursively Program Output

Outline Program Output

Random Number Generation rand function Load <stdlib.h> Returns "random" number between 0 and RAND_MAX (at least 32767) i = rand(); Pseudorandom Preset sequence of "random" numbers Same sequence for every function call 33

Random Number Generation Scaling To get a random number between 1 and n 1 + ( rand() % n ) rand % n returns a number between 0 and n-1 Add 1 to make random number between 1 and n 1 + ( rand() % 6) // number between 1 and 6 34

Random Number Generation srand function <stdlib.h> Takes an integer seed - jumps to location in "random" sequence srand( seed ); srand( time( NULL ) ); //load <time.h> time( NULL )- time program was compiled in seconds "randomizes" the seed 35

1 /* Fig. 5.9: fig05_09.c 2 Randomizing die-rolling program */ 3 #include <stdlib.h> 4 #include <stdio.h> 5 6 int main() 7 { 8 int i; 9 unsigned seed; 10 11 printf( "Enter seed: " ); 12 scanf( "%u", &seed ); 13 srand( seed ); 14 15 for ( i = 1; i <= 10; i++ ) { 16 printf( "%10d", 1 + ( rand() % 6 ) ); 17 18 if ( i % 5 == 0 ) 19 printf( "\n" ); 20 } 21 22 return 0; 23 } Outline 1. Initialize seed 2. Input value for seed 2.1 Use srand to change random sequence 2.2 Define Loop 3. Generate and output random numbers

Outline Program Output

Example: A Game of Chance Craps simulator Rules Roll two dice 7 or 11 on first throw, player wins 2, 3, or 12 on first throw, player loses 4, 5, 6, 8, 9, 10 - value becomes player's "point" Player must roll his point before rolling 7 to win 38

Outline 1. rolldice prototype 1.1 Initialize variables 1.2 Seed srand 2. Define switch statement for win/loss/continue 2.1 Loop

Outline 2.2 Print win/loss Player rolled 6 + 5 = 11 Player wins Program Output

Outline Program Output

Array Arrays Group of consecutive memory locations Same name and type To refer to an element, specify Array name Position number Format: arrayname[position number] First element at position 0 n element array named c: c[0], c[1]...c[n-1] Name of array (Note that all elements of this array have the same name, c) c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] - 456 0 7 154 2 3-890 6 2-31 645 3 7 8 Position number of the element within array c 42

Arrays Array elements are like normal variables c[0] = 3; printf( "%d", c[0] ); Perform operations in subscript. If x = 3, c[5-2] == c[3] == c[x] 43

Declaring Arrays When declaring arrays, specify Name Type of array Number of elements arraytype arrayname[ numberofelements ]; int c[ 10 ]; float myarray[ 3284 ]; Declaring multiple arrays of same type Format similar to regular variables int b[ 100 ], x[ 27 ]; 44

Examples Using Arrays Initializers int n[5] = {1, 2, 3, 4, 5 }; If not enough initializers, rightmost elements become 0 If too many, syntax error int n[5] = {0} All elements 0 C arrays have no bounds checking If size omitted, initializers determine it int n[] = { 1, 2, 3, 4, 5 }; 5 initializers, therefore 5 element array 45

Outline 1. Initialize array 2. Loop 3. Print

Outline Program Output

Examples Character arrays String "hello" is really a static array of characters Character arrays can be initialized using string literals char string1[] = "first"; null character '\0' terminates strings string1 actually has 6 elements char string1[] = { 'f', 'i', 'r', 's', 't', '\0' }; 48

Examples Character arrays (continued) Access individual characters string1[ 3 ] is character 's' Array name is address of array, so & not needed for scanf scanf( "%s", string2 ) ; Reads characters until whitespace encountered Can write beyond end of array, be careful 49

1 /* Fig. 6.10: fig06_10.c 2 Treating character arrays as strings */ 3 #include <stdio.h> 4 5 int main() 6 { 7 char string1[ 20 ], string2[] = "string" literal"; 8 int i; 9 10 printf(" Enter a string: "); 11 scanf( "%s", string1 ); 12 printf( "string1 is: %s\nstring2: is %s\n" 13 "string1 with spaces between characters 14 is:\n", string1, string2 ); 15 16 for ( i = 0; string1[ i ]!= '\0'; i++ ) 17 printf( "%c ", string1[ i ] ); 18 19 printf( "\n" ); 20 return 0; 21 } Enter a string: Hello there string1 is: Hello string2 is: string string1 with spaces between characters is: Outline 1. Initialize strings 2. Print strings 2.1 Define loop 2.2 Print characters individually 2.3 Input string 3. Print string Program Output

Passing Arrays to Functions Passing arrays Specify array name without brackets int myarray[ 24 ]; myfunction( myarray, 24 ); Array size usually passed to function Arrays passed call-by-reference Name of array is address of first element Function knows where the array is stored Modifies original memory locations 51

Passing Arrays to Functions Passing array elements Passed by call-by-value Pass subscripted name (i.e., myarray[3]) to function Function prototype void modifyarray( int b[], int arraysize ); Parameter names optional in prototype int b[] could be simply int [] int arraysize could be simply int 52

Outline 1. Function definitions 2. Pass array to a function 2.1 Pass array element to a function 3. Print Entire arrays passed call-byreference, and can be modified Array elements passed call-byvalue, and cannot be modified

33 34 void modifyarray( int b[], int size ) 35 { 36 int j; 37 38 for ( j = 0; j <= size - 1; j++ ) 39 b[ j ] *= 2; 40 } 41 42 void modifyelement( int e ) 43 { 44 printf( "Value in modifyelement is %d\n", e *= 45 } 2 ); Effects of passing entire array call by reference: The values of the original array are: 0 1 2 3 4 The values of the modified array are: 0 2 4 6 8 Effects of passing array element call by value: The value of a[3] is 6 Value in modifyelement is 12 The value of a[3] is 6 Outline 3.1 Function definitions Program Output

Case Study: Computing Mean, Median and Mode Using Arrays Mean - average Median - number in middle of sorted list 1, 2, 3, 4, 5 3 is the median Mode - number that occurs most often 1, 1, 1, 2, 3, 3, 4, 5 1 is the mode 55

Outline 1. Function prototypes 1.1 Initialize array 2. Call functions mean, median, and mode

Outline 3. Define function mean 3.1 Define function median 3.1.1 Sort Array 3.1.2 Print middle element

Outline Notice how the subscript in frequency[] is the value of an element in response[] (answer[]) 3.2 Define function mode 3.2.1 Increase frequency[] depending on response[] Print stars depending on value of frequency[]

Outline 3.3 Define bubblesort 3.3 Define printarray Bubble sort: if elements out of order, swap them.

Outline Program Output

Outline Program Output

Searching Arrays: Linear Search and Binary Search Search an array for a key value Linear search Simple Compare each element of array with key value Useful for small and unsorted arrays 62

Searching Arrays: Linear Search and Binary Search (II) Binary search For sorted arrays Compares middle element with key If equal, match found If key < middle, looks in first half of array If key > middle, looks in last half 5 Repeat Very fast; at most n steps, where 2 > number of elements 30 element array takes at most 5 steps 2 > 30 n 63

Multiple-Subscripted Arrays Multiple subscripted arrays Tables with rows and columns (m by n array) Like matrices: specify row, then column 64

Multiple-Subscripted Arrays Initialization int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; Initializers grouped by row in braces If not enough, unspecified elements set to zero int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; Referencing elements Specify row, then column printf( "%d", b[ 0 ][ 1 ] ); 1 2 3 4 1 0 3 4 65

Typical Errors for Assignment 2-1 Access OJ input in a wrong way Write source codes without a proper style Potential problems in initializing an array 66

Access OJ input in a wrong way 67

Write source codes without a proper style 68

Potential problems in initializing an array Supported by C99 ( variable length array) Our OJ system 69

70