CSC 107 – Programming For Science. Today’s Goal  Write functions that take & return values  How parameters declared and how we call functions  What.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

CSC 107 – Programming For Science. Today’s Goal  Get familiar with multi-dimensional arrays  Creating variables for multi-dimensional array  Multi-dimensional.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Introduction to Python
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.
Computer Science 1620 Lifetime & Scope. Variable Lifetime a variable's lifetime is finite Variable creation: memory is allocated to the variable occurs.
Basic Elements of C++ Chapter 2.
CSC 107 – Programming For Science. Science Means Solving Problems  Physics – How does an atom work?
CSC 107 – Programming For Science. Today’s Goal ALL  Understand why ALL I/O is file I/O  Common bugs to avoid when coding with files in C++  Get a.
1 Chapter 9 Scope, Lifetime, and More on Functions.
CSC 107 – Programming For Science. Announcements  Textbook available from library’s closed reserve.
CSC 107 – Programming For Science. Today’s Goal  Discuss writing & using functions  How to declare them, use them, & trace them  Could write programs.
CSC 107 – Programming For Science. Spacing in a Program  C++ ignores spaces in a program  This also means where newlines placed ignored  #define &
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
CSCI 130 Chapter 5 Functions. Functions are named uniquely Performs a specific task Is independent –should not interfere with other parts of program May.
CSC 107 – Programming For Science. Today’s Goal Variables  Variable  Variable name location to store data  Only for humans; 0 x 7E8A2410 harder to.
COMPUTER PROGRAMMING. Functions What is a function? A function is a group of statements that is executed when it is called from some point of the program.
CSC 107 – Programming For Science. Today’s Goal  Discuss how to hand data to functions  Review loopholes in variables & scoping rules  Ways to get.
PHY 107 – Programming For Science. Announcements  Slides, activities, & solutions always posted to D2L  Note-taking versions before class, for those.
CPS120: Introduction to Computer Science Decision Making in Programs.
CSC 107 – Programming For Science. Today’s Goal  When lecture over, start understanding pointers  What a pointer is and what it is not  Why pointers.
CSC 107 – Programming For Science. Announcements  Memorization is not important, but…  … you will all still be responsible for information  Instead.
CSC 107 – Programming For Science. Today’s Goal  When lecture over, start understanding pointers  What a pointer is and what it is not  Why pointers.
CPS120: Introduction to Computer Science Functions.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 7 Clicker Questions September 22, 2009.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Chapter 8 Scope of variables Name reuse. Scope The region of program code where it is legal to reference (use) a variable The scope of a variable depends.
CSC 107 – Programming For Science. The Week’s Goal.
CSC 107 – Programming For Science. Today’s Goal  Become familiar with simple arrays  Declaring an array variable  Assigning data to array entries 
CSC 107 – Programming For Science. Today’s Goal  Discuss writing functions that return values  return statement’s meaning and how it works  When and.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
CSC 107 – Programming For Science. Today’s Goal  Better understand arrays and how they work  Using array variable & its entries  When calling function,
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
#include using namespace std; // Declare a function. void check(int, double, double); int main() { check(1, 2.3, 4.56); check(7, 8.9, 10.11); } void check(int.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Today’s Lecture  Literal  Constant  Precedence rules  More assignment rules  Program Style.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
CSC 107 – Programming For Science. Today’s Goal  Know how to write selections besides if-else  When each of the options makes sense  When each selection.
Functions Structured Programming. Topics to be covered Introduction to Functions Defining a function Calling a function Arguments, local variables and.
1 Chapter 9 Scope, Lifetime, and More on Functions.
1 CS1430: Programming in C++ Section 2 Instructor: Qi Yang 213 Ullrich
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
PHY 107 – Programming For Science. Today’s Goal  Discuss how to hand data to functions  Review loopholes in variables & scoping rules  Ways to get.
CSC Programming for Science Lecture 37 : Course Review.
PHY 107 – Programming For Science. Science Means Solving Problems  Physics – How does an atom work?
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
CSC 107 – Programming For Science. Announcements  Lectures may not cover all material from book  Material that is most difficult or challenging is focus.
Chapter 6 Functions. 6-2 Topics 6.1 Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5.
Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
User-Written Functions
Chapter 7: User-Defined Functions II
CSC113: Computer Programming (Theory = 03, Lab = 01)
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
User-Defined Functions
Chapter 9 Scope, Lifetime, and More on Functions
Chapter 6: Functions Starting Out with C++ Early Objects Ninth Edition
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.
Chapter 9: Value-Returning Functions
CS150 Introduction to Computer Science 1
Understanding Conditions
Based on slides created by Bjarne Stroustrup & Tony Gaddis
CS150 Introduction to Computer Science 1
Presentation transcript:

CSC 107 – Programming For Science

Today’s Goal  Write functions that take & return values  How parameters declared and how we call functions  What it means when we pass a value as a parameter  return statement’s meaning and how it works  When and why we use the return statement  Why skipping return statements are bad ideas

Why We Use Functions  Simplify code  Replace copies of code by placing in single location  Locate commonly-used computations & actions  Good to find code, but can only return a single value  Input & output performed in these functions  Will discuss ways to change parameters’ values

Functions  Already been programming with functions  Built-in functions like pow, exp, & log  Writing & using programmer-defined function: main  All functions similar  Will be using same process to call function  Handling return result same for all functions  Process is same for variables, scoping, passing data

Functions  All functions similar, differ only in who wrote it Built-in Function WriterUser-Defined Function Writer

Function Names  Rules over legal names identical to variables  Letter or underscore start name for it to be legal  Can use any letters, numbers, or underscore after  Names should be unique (including variables)  Function names rely upon relaxed style rules  Start with a letter & make name meaningful  Names should only use words you would say to:

Function Declaration

Return Type  Functions must specify their return type  Type of value returned by the function float abs(float x); double pow(double x, double t); int main();  Use special return type, void, if no value is returned void goodSoldier(); void doSomethingWithX(int x);

Function Definitions

return Statement

return Examples

 Function ends when return is executed  Any and all code after return will be ignored  Calling function will resume its execution common  There are no errors or warnings for this common bug return Statement

return Examples

Multiple return Statements  Multiple return s possible in a single function  Each time function is called, only one is executed  Gives greater flexibility by not tying code down bool getNumber() { int num; cout > num; if ( (num % 2) == 1) { return true; } else { return false; } }

Variables  Variable  Variable names location to store data  Memory location's initial value is unknown  Assignments update memory location with new value  Memory location updated by assignment ONLY  When variable is used in program…  …uses current value at that memory location

Variable Scope  Scoping rules specify variables' lifetimes  Variables not universal  Variables not universal, but have specific lifetimes  Variable usable only in braces in which declared  For this copy of variable, scope defines its lifetime  Variable "dies" with end of scope in which declared  At start of scope, new copy created  Cannot use outside scope: error for bad variable  Must have unique names within a scope  Can reuse names between scopes – meaning is clear

Variable Scope void readNumber(int len) { int num = 0; for (int i = 0; i > ch; num *= 10; num += ch – '0'; } cout << num << endl; } int main() { int num = 3; readNumber(num); readNumber(5); return 0; }

Variable Scope void readNumber(int len) { int num = 0; for (int i = 0; i > ch; num *= 10; num += ch – '0'; } cout << num << endl; } int main() { int num = 3; readNumber(num); readNumber(5); return 0; } One name -but- two memory locations One name -but- two memory locations

Global Variables  Global variables are evil  Name for variables declared outside of any function  Exists throughout the entire program  Since they are global, can be used in any function  Functions can make variable with name of global  Within this function, would use local variable  Good luck figuring code out; prayers for debugging it

Global Variable Scope void readNumber(int len) { int num = 0; for (int i = 0; i > ch; num *= 10; num += ch – '0'; } cout << num << endl; } int num = 3; int main() { readNumber(num); readNumber(5); return 0; } Scopes overlap -but- two memory locations Scopes overlap -but- two memory locations

Global Variables  Evil idea sold by suits like this guy

Functions' Parameters

Parameters are Variables  Just like variables, they name memory location  Get new location each time function is called  Value stored at location changed by assignments  Unrelated to other variables even if names overlap assignments copy value  Like Xerox machine, assignments copy value

Calling Function w/Arguments  No different than we have been doing forever  Need name & parentheses like all function calls  Arguments specify value for each parameter  Must  Must have equal number of arguments & parameters  Argument that is 1 st in parens is value of 1 st parameter  2 nd parameter uses 2 nd argument in function call, etc.

Will It Compile?

Parameters Get Initialized  Assigned value of argument at start of function  Argument could be literal, variable or expression  Works like normal assignment; no connection made WILL NOT  Assigning parameter WILL NOT update argument  Like Xerox machine, assignments copy value

Sample Trace double powerLoss(double wattage) { double current = wattage / 110; wattage = current * current; return wattage; } int main() { double watt = 1100; double printed = powerLoss(watt); cout << printed << " " << watt << endl; double wattage = 0; printed = powerLoss(11.0); cout << printed << " " << wattage << endl; }

Your Turn  Get into your groups and try this assignment

For Next Lecture  Read about parameters in Section 9.4.4, 9.6  How do we pass references to a function?  What does it mean to pass-by-reference?  What is difference with what we discussed today?  Weekly Assignment #7 out & due on Tues.  Avoid the rush by start working on it now  Project #2 available so start working on it now  Project solution relies on topics up through today