User-defined Functions

Slides:



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

Introduction to C Programming
Modular Programming With Functions
Chapter 7: User-Defined Functions II
1 Engineering Problem Solving With C++ An Object Based Approach Chapter 5 Functions.
Chapter 5 Functions.
Functions Most useful programs are much larger than the programs that we have considered so far. To make large programs manageable, programmers modularize.
1 Lecture 18:User-Definded function II(cont.) Introduction to Computer Science Spring 2006.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Methods of variable creation Global variable –declared very early stage –available at all times from anywhere –created at the start of the program, and.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
Chapter 6: Functions.
Copyright © 2012 Pearson Education, Inc. Chapter 6 Modular Programming with Functions.
1 Chapter 9 Scope, Lifetime, and More on Functions.
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
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.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
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.
C++ Programming Lecture 11 Functions – Part III By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Modular Programming ELEC 206 Computer Applications for Electrical Engineers Dr. Ron Hayne.
Engineering Problem Solving with C++, Second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 5 Parameter Passing 11/06/13.
#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.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
 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 Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
CHAPTER 8 Scope, Lifetime, and More on Functions.
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
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.
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
Chapter 9: Value-Returning Functions
Review 1.
Chapter 1.2 Introduction to C++ Programming
C Functions -Continue…-.
A Lecture for the c++ Course
Engineering Problem Solving with C++, Etter/Ingber
Chapter 5 Functions.
FUNCTIONS IN C++.
C-language Lecture By B.S.S.Tejesh, S.Neeraja Asst.Prof.
Pointers and Pointer-Based Strings
CSC113: Computer Programming (Theory = 03, Lab = 01)
CSCI 161: Introduction to Programming Function
User-Defined Functions
Modular Programming with Functions
Chapter 9 Scope, Lifetime, and More on Functions
Functions.
User-defined Functions
Pointers & Functions.
More ‘concepts’ on Function
Pass by Reference.
Chapter 6: User-Defined Functions I
Chapter 9: Value-Returning Functions
The Function Prototype
Pointers and Pointer-Based Strings
Fundamental Programming
Functions Lecture 5.
Programming fundamentals 2 Chapter 1: Functions (Sub-Algorithms)
Predefined Functions Revisited
Functions Imran Rashid CTO at ManiWeber Technologies.
Pointers & Functions.
Single-Result Functions & Modularity
CS1201: Programming Language 2
Presentation transcript:

User-defined Functions ELEC 206 Computer Tools for Electrical Engineering

Functions A program can be thought of as a collection of sub parts or sub tasks: input data analyze data output results In C++ these subtasks are called functions.

Functions Complex problems can be broken down into sub tasks, each of which is easy to implement in C++. What are some other advantages to using functions, as opposed to writing the entire solution in main? Multiple programmers Testing/Debugging/Maintaining Reduce duplication of code

Functions Pre-defined standard libraries User-defined

Pre-defined Functions - Example #include <iostream> #include <cmath> using namespace std; int main() { double angle; cout << “input angle in radians: “; cin >> angle; cout << “\nthe sine of the angle is “ << sin(angle) << endl; return 0; }//end main

Cast Functions Return value as new data type, Have no affect on the argument #include <iostream> using namespace std; int main() { int x=9, y=2; cout << x/y << endl; cout << (double)x/(double)y << endl; cout << (double)x/y << endl; cout << ((double)x)/y << endl; return 0; }//end main Output? 4.5 4

User-defined Functions Terminology Function Prototype describes how a function is called Function Call Function Arguments used in the function call Function Definition function header function body Formal Parameters used in function definition Formal parameters must agree with arguments in order, number and data type, but the identifiers can be different.

User-defined Functions Can be defined to perform a task (return no value) return a single value to the calling function change the value of multiple variables

Void Functions A void function may be called to perform a particular task modify data perform input and output A void function does not return a value to the calling program return statement is optional if a return statement is used, it has the following form: return;

Example of void function //output formatted date //function definition void print_date(int mo, int day, int year) //function header { string month; switch(mo) { case 1: month = “January”; break; case 2: month = “February”; … case 12: month = “December”; }//end switch cout << month << ‘ ’ << day << “, << year << endl; return; //return is optional } //end print date

Value-returning Functions A function returns a single value to the calling program The function header declares the type of value to be returned A return statement is required in the body of the function

Example: n! n! = n*(n-1)*(n-2)*…*1 n is a positive integer 0! is 1 by definition

Example - factorial function //function definition: n! = n*(n-1)*(n-2)*…*1, // 0! is 1 by definition //Function fact returns n! //Function fact assumes n is non-negative integer int fact(int n) //function header, NO SEMICOLON { int nfact = 1; while(n>1) { nfact = nfact*n; n--; }//end while block return(nfact); }//end fact

Calling a function #include <iostream> using namespace std; int fact(int n); //function prototype, semicolon required // parameter identifier is optional int main() { int n; cin >> n; if(n>=0) cout<<n<<“! is ” <<fact(n)<<endl; //n is the argument else cout <<“factorial not defined for negative numbers” <<endl; return 0; }//end main

Calling a function- second example int fact(int); //function prototype, //parameter identifier is optional #include <iostream> using namespace std; int main() { int n, factorial; cin >> n; if(n>=0) { factorial = fact(n); //function call cout << n <<“! is ” << factorial << endl; } else cout << “factorial not defined for negative numbers” << endl; return 0; }//end main

2 Points of Style When Writing Value-returning Functions Formal parameters are used to pass information to the function. cin statements are usually not required. A return statement returns a value to the calling program. cout statements are usually not required. Use library functions as model (sin, log, etc)

Parameter Passing - pass by value the default in C++ (except when passing arrays as arguments to functions) formal parameter receives the value of the argument changes to the formal parameter do not affect the argument

#include <iostream> using namespace std; int fact(int); //function prototype int main() { int n, factorial; cin >> n; if(n>=0) { factorial = fact(n); //function call cout << n <<“! is “ << factorial << endl; }//end if return 0; }//end main int fact(int n) //function header, NO SEMICOLON { int nfact = 1; while(n>1) { nfact = nfact*n; n--; }//end while block return(nfact); } //end fact

Parameter Passing - pass by reference append an & to the parameter data type in both the function prototype and function header void get_date(int& day, int& mo, int& year) formal parameter receives the address of the argument any changes to the formal parameter directly change the value of the argument

Example - pass by reference #include <iostream> using namespace std; void swap(double&, double&); //function prototype int main() { double x=5, y=10; swap(x,y); //function call; x y are arguments cout >> “x = “ << x << ‘,’ << “ y= “ << y << endl; return 0; }//end main Output is: x = 10, y = 5

Example - pass by reference //Function swap interchanges the values of two variables //function definition void swap(double& x, double& y) //function header { double temp; //local variable temp temp = x; x=y; y=temp; return; //optional return statement }//end swap

Practice! - What is the output? #include <iostream> using namespace std; void fun(int&, int&, int); int main() { int c1=1, c2=2, c3=3; cout << c1 << ‘,’ << c2 << ‘,’ << c3 << endl; fun(c1,c2,c3); fun(c3, c2, c1); return 0; } void fun(int& a1, int& a2, int a3) { a1++; a2++; a3--; 1,2,3 2,3,3 2,4,4

Storage Class and Scope Scope refers to the portion of the program in which it is valid to reference a function or a variable Storage class refers to the lifetime of a variable

Scope Local scope - a local variable is defined within a function or a block and can be accessed only within the function or block that defines it Global scope - a global variable is defined outside the main function and can be accessed by any function within the program file.

Storage Class - 4 types automatic - key word auto - default for local variables Memory set aside for local variables is not reserved when the block in which the local variable was defined is exited. external - key word extern - used for global variables Memory is reserved for a global variable throughout the execution life of the program. static - key word static Requests that memory for a local variable be reserved throughout the execution life of the program. The static storage class does not affect the scope of the variable. register - key word register Requests that a variable should be placed in a high speed memory register.

//Scope Example - What is the output #include <iostream> using namespace std; void a(); //Function prototypes void b(); int x=1; //Global (file scope) int main() { int x=5; //Local to main cout << "before call to a, x= " << x << endl; cout << "global x is " << ::x << endl; a(); cout << "after call to a, x= " << x << endl; b(); cout << "after call to b, x= " << x << endl; cout << "after 2nd call to b, x= " << x << endl; return(0); } void a() { int x=25; //Local to a x++; void b() {

Scope Example - Output before call to a, x= 5 global x is 1 after call to a, x= 5 after call to b, x= 5 global x is 2 after 2nd call to b, x= 5 global x is 3

//Storage Class Example - What is the output #include <iostream> using namespace std; void donothing(); int main() { donothing(); donothing(); return(0); }//endmain void donothing() { int x=0; static int y=0; x++; y++; cout <<“x is ” x << “, y is ” << y << endl; return; }//end donothing

Storage Class Example - Output x is 1, y is 1 x is 1, y is 2 x is 1, y is 3