CSCI 171 Presentation 6 Functions and Variable Scope.

Slides:



Advertisements
Similar presentations
Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Advertisements

Introduction to C Programming
Chapter 8 Scope, Lifetime and More on Functions. Definitions Scope –The region of program code where it is legal to reference (use) an identifier Three.
Chapter 7: User-Defined Functions II
CSCI 171 Presentation 11 Pointers. Pointer Basics.
16/11/2015 9:05 AM6/11/2015 9:05 AM6/11/2015 9:05 AMFunctions Functions A function consists of: Name Name Arguments (also called parameters) Arguments.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
Methods of variable creation Global variable –declared very early stage –available at all times from anywhere –created at the start of the program, and.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
Functions in C. Function Terminology Identifier scope Function declaration, definition, and use Parameters and arguments Parameter order, number, and.
Computer Science 210 Computer Organization Introduction to C.
Chapter 4:Functions| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2005 Slide 1 Functions Lecture 4 by Jumail Bin.
1 Chapter 9 Scope, Lifetime, and More on Functions.
CSCI 130 Scope of Variables Chapter 6. What is scope Parts of program which can access a variable –accessibility –visibility How long variable takes up.
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
MAHENDRAN CHAPTER 6. Session Objectives Explain Type of Functions Discuss category of Functions Declaration & Prototypes Explain User Defined Functions.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 6 Functions.
Chapter 6: User-Defined Functions
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.
PASSING VALUE TO A FUNCTION # CALL BY VALUECALL BY VALUE # CALL BY REFERENCECALL BY REFERENCE STORAGE CLASS # AUTOAUTO # EXTERNALEXTERNAL # STATICSTATIC.
C Functions Pepper. Objectives Create functions Function prototypes Parameters – Pass by value or reference – Sending a reference Return values Math functions.
CPS120: Introduction to Computer Science Functions.
CPS120: Introduction to Computer Science Lecture 14 Functions.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
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.
C++ Programming Lecture 11 Functions – Part III By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
ECE 103 Engineering Programming Chapter 36 C Storage Classes Herbert G. Mayer, PSU CS Status 8/4/2014 Initial content copied verbatim from ECE 103 material.
Dale Roberts CSCI 230 Functions Scope, Parameter Passing, Storage Specifiers Department of Computer and Information Science, School of Science, IUPUI Dale.
Functions in C CSE 2451 Rong Shi. Functions Why use functions? – Reusability Same operation, different data – Abstraction Only need to know how to call.
Functions: Part 2 of /11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park 1.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
Functions Chapter 6. Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules Function: a collection.
Chapter 5 Modular Design and Function C Programming for Scientists & Engineers with Applications by Reddy & Ziegler.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
 2000 Prentice Hall, Inc. All rights reserved Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
NOTE: C programs consist of functions one of which must be main. C programs consist of functions one of which must be main. Every C program begins executing.
Functions Modules in C++ are called functions and classes. Main reason to use functions is : – get aid in conceptual organization.
Computer Programming II Lecture 4. Functions - In C++ we use modules to divide the program into smaller and manageable code. These modules are called.
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
Announcements. Practice questions, with and without solutions will be uploaded by Friday 5 th November, make sure to check them before the weekend \\netstorage\Subjects\ITCA-b\Exam.
C Part 2 Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens The Three Attributes of an Identifier Identifiers have three essential.
Chapter 9: Value-Returning Functions
Computer Science 210 Computer Organization
The Three Attributes of an Identifier
CSC113: Computer Programming (Theory = 03, Lab = 01)
CSCI 161: Introduction to Programming Function
User-Defined Functions
Computer Science 210 Computer Organization
Scope, Parameter Passing, Storage Specifiers
Functions, Part 2 of 3 Topics Functions That Return a Value
Functions, Part 2 of 3 Topics Functions That Return a Value
Standard Version of Starting Out with C++, 4th Edition
Functions, Part 2 of 3 Topics Functions That Return a Value
Presentation transcript:

CSCI 171 Presentation 6 Functions and Variable Scope

Functions Functions: –are named uniquely –perform specific tasks –are independent should not interfere with other parts of program –may need data to accomplish their task parameters (arguments) –may send data back to their initiator returning a value

Function Example #include double calcForce (double, double);//function prototype int main( void ) { double mass = 3; double acceleration = 4; double force = 0; force = calcForce (mass, acceleration);//calling the function printf("%lf", force); } double calcForce(double m, double a)//function header { return (m * a);//function body }

Function Example - cont’d Function definition (header and body): double calcForce(double m, double a) { return (m * a); } Function name is: calcForce Function parameters are: 2 doubles (m and a) Function returns: 1 double

Sample Program 7.1 #include float findArea(float, float); void main() { float base = 0, height = 0, area = 0; printf("Enter triangle base: "); scanf("%f", &base); printf("Enter triangle height: "); scanf("%f", &height); area = findArea(base, height); printf("The area is: %.2f", area); } float findArea(float b, float h) { float area = 0; area = 0.5 * b * h; return area; }

How a function works Is not executed unless called “Calling function” sends in any arguments –information to perform the process Control returns to –statement following function call (if no return) –function call (if a value is returned)

Parts of a function Prototype –function name –argument type(s) –return type Definition –header –body (actual code)

Local Variables Variables declared within a function are local –only defined within the function –not accessible by other functions Arguments act locally as well

Note the local variables in 7.1 #include float findArea(float, float); void main() { float base = 0, height = 0, area = 0; printf("Enter triangle base: "); scanf("%f", &base); printf("Enter triangle height: "); scanf("%f", &height); area = findArea(base, height); printf("The area is: %.2f", area); } float findArea(float b, float h) { float area = 0; area = 0.5 * b * h; return area; }

Return values Functions may have more than 1 return value, but only 1 is ever returned –Generally this is bad structure, not suggested Ex: if (a > b) return a; else return b;

Return types Return type is declared in function header & prototype Actual value being returned is in return statement Examples: double calcForce(double m, double a) { return (m * a); } float findArea(float b, float h) { float area = 0; area = 0.5 * b * h; return area; }

No return type void specifies that there is no return value no return statement in function Ex: void writeErrorMessage() { printf(“\nInvalid input”); printf(“\nPlease check specifications”); errorCount += 1; }

Calling a function Calling a function with no return  writeToFile( ); Calling a function with a return value  x = square(3);  printf(“The square of 3 is: %d”, square(3)); Calling a function as a parameter  c = sumTheValues(square(3), square(4)); Multiple functions in an expression  b = square(3) + square(4);

Global Variables Placed outside of all functions Scope of variable is entire program –can be accessed by any function within the file Generally considered bad programming style

Sample Program 7.6 #include double force = 0.0;//Global variable – accessible to all functions in file double calcForce (double, double); int main( void ) { double mass = 3.0; double acceleration = 4.0; force = calcForce (mass, acceleration); printf("%lf", force); } void calcForce(double m, double a)//function header { force = m * a; }

What is scope? Parts of program which can access a variable –accessibility –visibility How long variable takes up system resources (memory) –Dynamic memory allocation

Scope Program 1 (compiles) | Program 2 (does not compile) int x = 999;|void squareX() | void squareX();|void main() { |int x = 999; void main() {|x = x * x; x = x * x;|} }| |void squareX() { void squareX () { |x = x * x; x = x * x;|} }|

Importance of scope Modularization –each function should be independent –variables isolated from interference Scope allows for control over degree of isolation

Local Variables Defined within a code block Visibility limited to that code block Usually a function’s local variable’s value is re-initialized with each call to the function Can request variable not be destroyed –static keyword

Local variables - example void main() { outputNumbers(); } ____________________________ void outputNumbers() {|Program output: static int x = 0;|0 0 int y = 0;|1 0 printf(“\n%d %d”, x++, y++);|2 0 }|

Parameters and Scope A variable in the parameter list acts locally void function1(int x) { int y = 0; printf(“%d %d”, x, y); } In the preceding: –x is a parameter (and so is only accessible within the function) –y is a local variable (and so is only accessible within the function)

Register variables Suggests that a local variable be stored in processor register (not regular memory) void function1() { register int x; …. } Any processing with x will be done quicker Can only be used with simple numeric variables –can’t use with arrays, structures, etc.

Code Blocks Variables can be declared as local within program blocks (statements enclosed in {}) void main() { int count = 0; printf(“%d”, count); { int count = 10; printf(“%d”, count); } printf(“%d”, count); }

Guidelines Initialize all variables Pass data as function parameters unless most functions use the data Use symbolic constants for constant data that is used in most of the functions –PI in a math library Put definitions at beginning of scope –functions, files, etc.