Download presentation
Presentation is loading. Please wait.
1
Lecture 7: Modular Programming (functions)
B Burlingame 11 October 2017
2
"Igor Nikolskiy says: March 19, 2015 at 4:22 pm
"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."
3
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
4
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
5
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);
6
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
7
Functions - Mathematical View
X Function Returned value
8
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.
9
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
10
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
11
Function - sum() int sum_int(int x, int y) { int result = 0.0;
result = x + y; return result; }
12
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
13
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.
14
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
15
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]); 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
16
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.
17
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.
18
References Modular Programming in C math.h
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.