Functions Inputs Output

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Spring Semester 2013 Lecture 5
Wednesday, 10/9/02, Slide #1 CS 106 Intro to CS 1 Wednesday, 10/9/02  QUESTIONS ??  Today:  Discuss HW #02  Discuss test question types  Review 
1 Modularity In “C”. 2 General Syntax data_type function_Name (parameter list) { … return expression; // return output } Body of the function is a compound.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
CS 201 Functions Debzani Deb.
Chapter 6: User-Defined Functions I
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
Computer Science 1620 Reference Parameters. Parameters – Pass by Value recall that the parameter of a function is assigned the value of its corresponding.
Introduction to Methods
Chapter 6: Functions.
Functions in C. Function Terminology Identifier scope Function declaration, definition, and use Parameters and arguments Parameter order, number, and.
Chapter 4:Functions| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2005 Slide 1 Functions Lecture 4 by Jumail Bin.
Beginning C++ Through Game Programming, Second Edition by Michael Dawson.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Chapter 6: User-Defined Functions
Oct 15, 2007Sprenkle - CS1111 Objectives Creating your own functions.
CPS120: Introduction to Computer Science Decision Making in Programs.
142 F -1 Functions chapter 3 of the text int main(void) { double x,y,z; … x = cube(y/3.0); … printf(“%f cubed is %f”,x,cube(x)); … return 0; } double cube(double.
CPS120: Introduction to Computer Science Functions.
Functions Top-down design Breaking a complex problem into smaller parts that we can understand is a common practice. The process of subdividing a problem.
CPS120: Introduction to Computer Science Lecture 14 Functions.
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
Computer Programming Rattapoom Waranusast Department of Electrical and Computer Engineering Faculty of Engineering, Naresuan University.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Programming Fundamentals Enumerations and Functions.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
Gator Engineering Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 9 Functions.
Functions Students should understand the concept and basic mechanics of the function call/return pattern from CS 1114/2114, but some will not. A function.
User-Written Functions
Chapter 6: User-Defined Functions I
Learning to Program D is for Digital.
C Functions Pepper.
Method Parameters and Overloading
Programming Fundamentals Lecture #7 Functions
Programmazione I a.a. 2017/2018.
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Stack Data Structure, Reverse Polish Notation, Homework 7
User-Defined Functions
Loops The loop blocks you've used in Scratch can all be recreated in C! Loops allow for the repetition of code until a condition is met. There are three.
Loops The loop blocks you've used in Scratch can all be recreated in C! Loops allow for the repetition of code until a condition is met. There are three.
Functions Chapter 9 Copyright © 2008 W. W. Norton & Company. 1
Functions I Creating a programming with small logical units of code.
Functions Chapter 3 of the text Motivation:
Chapter 4 void Functions
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
6 Chapter Functions.
Functions.
Functions Chapter 9 Copyright © 2008 W. W. Norton & Company.
Functions Pass By Value Pass by Reference
Chapter 6: User-Defined Functions I
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Functions I Creating a programming with small logical units of code.
CPS125.
Methods and Data Passing
Presentation transcript:

Functions Inputs Output You've probably used plenty of C functions already like printf() from the stdio library or GetInt() from CS50's library, but now we'll learn how to write our own functions and incorporate them into our code. Basically the point of functions in C is to help you to partition your code into manageable pieces. Think of a function as a black box with a set of inputs and a single (optional) output. The rest of the program does not need to know what goes on inside the function, but the program can call the function, provide it with inputs, and use the output. This is a bit of an oversimplification as functions are also useful for the side effects they cause. For example, you might write a function called print_instructions(), which doesn't return anything but executes a series of printf() statements.

Why Functions? - Organization - Simplification - Reusability The main reasons for using functions in programming are: Organization. Functions help to break up a complicated problem into more manageable subparts and help to make sure concepts flow logically into one another. Simplification. Smaller components are easier to design, easier to implement, and far easier to debug. Good use of functions makes code easier to read and problems easier to isolate. Reusability. Functions only need to be written once, and then can be used as many times as necessary, so you can avoid duplication of code.

A Function Definition int cube(int input) { int output = input * input * input; return output; } Here's an example of the structure of a function definition. A function definition gives all the information that the compiler needs to know about a function. It describes how the function should be used, how its body should be translated into machine-readable language that the computer can execute, and what operations the code in its body will perform. This function, cube(), takes an int as input and returns the cubed value of that int. We'll next cover the components of a function definition in more detail.

Header Body int cube(int input) { int output = input * input * input; function name int cube(int input) { int output = input * input * input; return output; } return type parameter list Body A function definition has a header and a body. The header always contains these parts: Return type. The type of value that the function will output. In our example, it is int. Function name. The name that is used to call this function. In our example, it is cube. Parameter list. The parameters are the types of arguments the function expects as input, and the names by which the function will refer to those inputs. cube() takes an int as its only argument, and this int will be referred to as input in the function's body. Note that the parameter's list can be empty, which would indicate that the function doesn't expect any arguments. The body is the code within the curly braces that is executed when the function is called. It's important to remember that variables declared in the body of a function are local in scope to that function and cannot be used in other functions! One or more of the statements in the function's body can be return statements. A return statement ends the execution of the function and passes the return value back to the function that called it.

#include <stdio.h> int cube(int input); int main(void) { int x = 2; printf("x is %i\n", x); x = cube(x); } int cube(int input) int output = input * input * input; return output; Let's put everything together now! We've got our familiar main() function which calls cube() using the function's name and the argument we want to pass. Note that here the argument to cube() happens to be a variable, but more generally arguments can be constants or other expressions. But what is that line above main() that we've highlighted in pink? This is called a function prototype. As you can see, the function prototype matches the header of the function definition except that it ends with a semicolon. Why do we need this prototype before main()? The function prototype lets us get away with calling a function when the compiler hasn't yet seen the function's full definition (the C compiler reads from top to bottom) by providing the function’s type signature. In other words, the function prototype defines what variable types the function accepts as input and returns as output so that the compiler understands how the function should be used in main(). If you removed the prototype, you'd get a compiler error "implicit declaration of function 'cube' is invalid in C99". So you have two choices: move the definition of cube() above the definition of main() or declare a function prototype for cube() above main() as we did in this slide.

Now that you have a basic idea of how to create your own functions, let's make sure you understand how these functions are represented in memory: At the top of the program's memory is the text segment, which contains the actual 0's and 1's that make up your program. The sections for initialized and uninitialized data are used for storing global variables if your program has any. Most of a program's memory is reserved for the stack and heap. We won't talk about the heap today, but the stack consists of chunks of memory piled on top of each other. Just like the stack of trays in the dining hall, the stack of a program requires that the one on top be taken off before any of the others can be taken off.

cube()'s locals cube()'s parameters main()'s locals Let's zoom in on the stack. The memory at the bottom of the stack is first used for main(). Any functions that main() calls have their memory stacked on top, so we see our function cube() right above main(). As functions return, their chunks of memory are popped off the stack. The important function implication for us is that when main() calls cube(), cube() creates copies of the variables passed to it which are stored in cube()'s stack frame. We'll see in the next example why this is such a big deal. cube()'s parameters main()'s locals main()'s parameters

#include <stdio.h> void swap(int a, int b); int main(void) { int x = 1; int y = 2; swap(x, y); printf("x is %i\n", x); printf("y is %i\n", y); } void swap(int a, int b) { int tmp = a; a = b; b = tmp; } This program attempts to swap the values of x and y. Let's think through the logic of that swap function: Take the value of a and store it in a temporary variable tmp. Store the value of b in a. Store the value of tmp in b. Seems perfectly reasonable, right? Why doesn't this work? Well, swap() has made copies of x and y in a different stack frame and is calling those copies a and b. Whatever operations swap() performs on a and b have no bearing on our original x and y variables in main()'s stack frame. Discuss ways to fix this program!