Lecture 7: Modular Programming (functions)

Slides:



Advertisements
Similar presentations
Spring Semester 2013 Lecture 5
Advertisements

BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
1 ICS103 Programming in C Lecture 5: Introduction to Functions.
CS 201 Functions Debzani Deb.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
FunctionsFunctions Systems Programming. Systems Programming: Functions 2 Functions   Simple Function Example   Function Prototype and Declaration.
CS 201 Functions Debzani Deb.
FunctionsFunctions Systems Programming Concepts. Functions   Simple Function Example   Function Prototype and Declaration   Math Library Functions.
Lecture 5: Modular Programming (functions – part 1 BJ Furman 27FEB2012.
Chapter 4:Functions| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2005 Slide 1 Functions Lecture 4 by Jumail Bin.
Functions Lecture 4 – Section 2: 9/21/05 Section 4: 9/22/05.
Beginning C++ Through Game Programming, Second Edition by Michael Dawson.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
1. Function prototype Function prototype is a declaration; indicates the function exists Should have function name, return type and parameter Placed before.
Week 6: Functions - Part 2 BJ Furman 01OCT2012. The Plan for Today Comments on midterm exam (next week in lab!) Review of functions Scope of identifiers.
UniMAP SemI-09/10EKT120: Computer Programming1 Week 5 – Functions (1)
Lecture 10: Modular Programming (functions) B Burlingame 13 April 2015.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
Functions  A Function is a self contained block of one or more statements or a sub program which is designed for a particular task is called functions.
FUNCTIONS. Midterm questions (1-10) review 1. Every line in a C program should end with a semicolon. 2. In C language lowercase letters are significant.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Programming Fundamentals Enumerations and Functions.
APS105 Functions (and Pointers) 1. Modularity –Break a program into manageable parts (modules) –Modules interoperate with each other Benefits of modularity:
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
Lecture 7: Variable Scope B Burlingame March 16, 2016.
Lecture 11: Pointers B Burlingame 13 Apr Announcements Rest of semester  Homework Remaining homework can be done in pairs, turn in one paper with.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Lecture 7: Modular Programming (functions) B Burlingame 05 October, 2016.
Functions + Overloading + Scope
EKT120: Computer Programming
User-Written Functions
Chapter 6 - Functions modular programming general function format
Chapter 6: User-Defined Functions I
EGR 2261 Unit 10 Two-dimensional Arrays
Lesson #6 Modular Programming and Functions.
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Lesson #6 Modular Programming and Functions.
Lecture 8: Variable Scope & Working with Files
Lecture 9: Pointers B Burlingame 25 October 2017.
Programming Fundamentals Lecture #7 Functions
Programmazione I a.a. 2017/2018.
Chapter 5 - Functions Outline 5.1 Introduction
Functions.
User-Defined Functions
Chapter 5 - Functions Outline 5.1 Introduction
Lesson #6 Modular Programming and Functions.
Functions Inputs Output
Functions Declarations CSCI 230
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Chapter 4 void Functions
Functions.
A function with one argument
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Bryan Burlingame 13 February 2019
Chapter 6: User-Defined Functions I
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Lesson #6 Modular Programming and Functions.
In C Programming Language
Introduction to Problem Solving and Programming
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 1 of 2 Topics Definition of a Data Structure
CPS125.
Functions that return a value
Presentation transcript:

Lecture 7: Modular Programming (functions) B Burlingame 11 October 2017

"Igor Nikolskiy says: March 19, 2015 at 4:22 pm https://thescienceweb.wordpress.com/2015/03/19/all-other-languages-tired-of-pythons-shit/ "Igor Nikolskiy says: March 19, 2015 at 4:22 pm I don’t think C gets enough credit. Sure, C doesn’t love you. C isn’t about love–C is about thrills. C hangs around in the bad part of town. C knows all the gang signs. C has a motorcycle, and wears the leathers everywhere, and never wears a helmet, because that would mess up C’s punked-out hair. C likes to give cops the finger and grin and speed away. Mention that you’d like something, and C will pretend to ignore you; the next day, C will bring you one, no questions asked, and toss it to you with a you-know-you-want-me smirk that makes your heart race. Where did C get it? “It fell off a truck,” C says, putting away the boltcutters. You start to feel like C doesn’t know the meaning of “private” or “protected”: what C wants, C takes. This excites you. C knows how to get you anything but safety. C will give you anything but commitment In the end, you’ll leave C, not because you want something better, but because you can’t handle the intensity. C says “I’m gonna live fast, die young, and leave a good-looking corpse,” but you know that C can never die, not so long as C is still the fastest thing on the road."

Announcements Homework #4 due in two weeks Read Midterm – Next week Previously announced homework was delayed due to technical issues Read Chapter 8 Midterm – Next week Open book Open notes Covers through the previous lecture

Learning Objectives Explain the concept of modular program design Explain the concept of a function in C Explain why functions are important in programming Explain the structure of a function Return data type Parameters Apply the concept of a function to a practical problem

Modular Programming Break a large problem into smaller pieces Smaller pieces sometimes called ‘modules’ or ‘subroutines’ or ‘procedures’ or functions Why? Helps manage complexity Smaller blocks of code Easier to read Encourages re-use of code Within a particular program or across different programs Allows independent development of code Provides a layer of ‘abstraction’ Imagine trying to develop a huge program like the Windows or Mac OS with hundreds of thousands (or millions of lines of code). No way to do it all in one big program file. Is the work of hundreds of computer programmers, each working on smaller pieces of the problem that are then brought together. By ‘abstraction’, I mean a way to simplify or separate the details of how a process works to an essential set of features that allow the process to be used. Example: a stick figure compared to a Leonardo da Vinci drawing or a photograph of a man. In programming a function allows you to not need to know the details of the function in order to be able to use it. Ex. sqrt() a = sqrt(9.0);

Functions The ‘building blocks’ of a C program You’ve used predefined functions already: main() printf(), scanf(), pow() User-defined functions Your own code In combination with predefined functions

Functions - Mathematical View X Function Returned value

Functions - Definition Structure Function 'header' Return data type (if any) Name Descriptive Arguments (or parameter list) Notice: data type and name Statements Variable declaration Operations Return value (if any) type function_name (type arg1, type arg2 ) { statements; } A function that calculates the product of two numbers double product(double x, double y) { double result; result = x * y; return result; } The function definition declares the return data type, its name, and the data types of its parameters. Any parameter names included in the list are actually ignored by the compiler. The names are included to help document the function. Contrast this with the function prototype.

Functions - Example printf("var1 = %.2f\n" Function prototype Like a variable declaration Tells compiler that the function will be defined later Helps detect program errors Note semicolon!! Function definition See previous slide Note, NO semicolon Function return return statement terminates execution of the current function Control returns to the calling function if return expression; then value of expression is returned as the value of the function call Only one value can be returned this way Function call main() is the 'calling function' product() is the 'called function' Control transferred to the function code Code in function definition is executed #include <stdio.h> /* function prototype */ double product(double x, double y); int main() { double var1 = 3.0, var2 = 5.0; double ans = 0.0; ans = product(var1, var2); printf("var1 = %.2f\n" "var2 = %.2f\n",var1,var2); printf("var1*var2 = %g\n", ans); } /* function definition */ double product(double x, double y) double result = 0.0; result = x * y; return result; Show structure from the template: miles_to_kilometers.c The function prototype declares the return data type, the function's name, and the data types of its parameters. Any parameter names included in the list are actually ignored by the compiler. The names are included to help document the function. Function prototype helps reduce program errors, because by using it, the compiler can then detect the wrong number or the wrong type of data items that are passed to the function

Function - Practice 1 Write a function named 'sum' 2 min. on your own Steps Function header return data type function name argument list with data types Statements in function definition variable declaration operations return value Write a function named 'sum' sums two integers returns the sum 2 min. on your own Share with neighbor

Function - sum() int sum_int(int x, int y) { int result = 0.0; result = x + y; return result; }

Using Functions – an Example #include <stdio.h> float sum( float a, float b ); // Note that one can use a function // which returns a float in any place int main( void ) // where one can use a float { float a = 34, b = 67; float c = sum(a, b); // ex: in an initialization/assignment float d = sum( sum(a, b), c ); // ex: within another function call float e = sum(a, b) + sum(c, d); // ex: in an expression printf("The sum of %f and %f is %f\n", a, c, sum(a, c) ); printf("The sum of %f, %f, and %f is %f\n", a, b, c, d); return 0; } float sum( float x, float y ) return (x + y); // note the return expression

Passing Arguments into Functions (By Value) #include <stdio.h> double product(double x, double y); int main() { int a = 10; double var1 = 3.0, var2 = 5.0; double ans = 0.0; ans = product(var1, var2); printf("var1 = %.2f\n" "var2 = %.2f\n",var1,var2); printf("var1*var2 = %g\n", ans); return 0; } /* function definition */ double product(double A, double B) double result = 0.0; result = A * B; return result; How are the arguments passed into functions? 'Pass by value‘ function arguments are expressions In the function call: Expressions are evaluated and copies of their values are put into temporary memory locations The names of the corresponding parameters in the function definition are made to be the names of the copies The values of the expressions in the function call are not changed In the example copies of var1 and var2 are passed to the function. The identifiers (names) A and B are identifiers for the copies of var1 and var2.

Recall: what is an array? int nums [10]; 10 element array of integers Element no. 3 is accessed by: nums [2] because indexing begins at 0

Passing an Array to a Function #include <stdio.h> void PrintArray(int elements, char array[]); int main() { /* initialize the array */ char test[]={'M','E','3','0'}; /* get the size of the array */ int num_elem=sizeof(test)/sizeof(char); /* pass array to function */ PrintArray(num_elem, test); return 0; } /* PrintArray() function definition */ void PrintArray(int num_elem, char array[]) int i=0; for(i=0; i < num_elem; i++) printf("test[%d]==%c",i, array[i]); printf(" @ 0x%p\n", &array[i]); Prototype and function header need: data type array name [ ] Function call with actual name of the array Note: in the function prototype and function header char *array would also work (i.e. arrays are always passed by reference) See print_array.c

Scope of Identifiers Scope of a declaration of an identifier The region of the program that the declaration is active (i.e., can access the variable, function, label, etc.) Five types of scope: Program (global scope) File Function prototype Function Block (“between the { } scope”) Scope refers to the region in the program where the identifier can be referenced.

Scope of Identifiers - Block Scope Block (local) scope A block is a series of statements enclosed in braces { } The identifier scope is active from the point of declaration to the end of the block ( } ) Nested blocks can both declare the same variable name and not interfere #include <stdio.h> double product(double x, double y); int main() { int a = 10; double var1 = 3.0, var2 = 5.0; double ans = 0; ans = product(var1, var2); printf("var1 = %.2f\n" "var2 = %.2f\n",var1,var2); printf("var1*var2 = %g\n", ans); } /* function definition */ double product(double x, double y) double result = 0.0; result = x * y; return result; Show how this works in ChIDE using var_scope_block.c Show also scope_nested_blocks.c Note: a variable declared in a block that also contains a block (nested block) is active within the contained block, but not vice-versa.

References Modular Programming in C http://www.icosaedro.it/c-modules.html math.h http://www.opengroup.org/onlinepubs/007908799/xsh/math.h.html http://www.cprogramming.com/tutorial/style.html