Week 3. Muhao Chen.

Similar documents
CS 345. Functions. Vitaly Shmatikov. slide 1

Implementing Subprograms

Programming Languages: Lecture 12

Chapter 10. Implementing Subprograms ISBN

Lecture 11: Subprograms & their implementation. Subprograms. Parameters

Week 5. Muhao Chen.

Chapter 9 Subprograms

Lecture 2:- Functions. Introduction

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

CSE202-Lec#4. CSE202 C++ Programming

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

Binding and Variables

CS 115 Exam 2, Fall 2009

EECS402 Lecture 02. Functions. Function Prototype

SFU CMPT Topic: Control Statements

UEE1302(1066) F12: Introduction to Computers and Programming Function (II) - Parameter

1 #include <iostream > 3 using std::cout; 4 using std::cin; 5 using std::endl; 7 int main(){ 8 int x=21; 9 int y=22; 10 int z=5; 12 cout << (x/y%z+4);

Functions. Arash Rafiey. September 26, 2017

The University Of Michigan. EECS402 Lecture 02. Andrew M. Morgan. Savitch Ch. 3-4 Functions Value and Reference Parameters.

PROCEDURES, METHODS AND FUNCTIONS

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Pointers, Dynamic Data, and Reference Types

More on Functions. Lecture 7 COP 3014 Spring February 11, 2018

Study Guide for Test 2

CS31 Discussion 1E Spring 17 : week 08

FUNCTIONS OMPAL SINGH

Type Inference Systems. Type Judgments. Deriving a Type Judgment. Deriving a Judgment. Hypothetical Type Judgments CS412/CS413

COP4020 Programming Languages. Subroutines and Parameter Passing Prof. Robert van Engelen

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

Introduction to Programming (Java) 4/12

(6) The specification of a name with its type in a program. (7) Some memory that holds a value of a given type.

8. Functions (II) Control Structures: Arguments passed by value and by reference int x=5, y=3, z; z = addition ( x, y );

CPE Summer 2015 Exam I (150 pts) June 18, 2015

CSE 230 Intermediate Programming in C and C++ Functions

FORM 2 (Please put your name and form # on the scantron!!!!)

UNIT III (PART-II) & UNIT IV(PART-I)

Computer Programming

The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science

EE 368. Weeks 4 (Notes)

Fundamentals of Programming Languages

Darshan Institute of Engineering & Technology for Diploma Studies

Chapter 10. Implementing Subprograms

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Week 2. Muhao Chen.

APS105. Pointers. Memory RAM 11/5/2013. Pointers. Need a way to refer to locations of things. a pointer: Address. Example: In C

type name(arg1, arg2,...) { body return }

Learning Recursion. Recursion [ Why is it important?] ~7 easy marks in Exam Paper. Step 1. Understand Code. Step 2. Understand Execution

Getting started with C++ (Part 2)

The paramaterless ctor (aka default ctor)

Programming Studio #9 ECE 190

8/5/10 TODAY'S OUTLINE. Recursion COMP 10 EXPLORING COMPUTER SCIENCE. Revisit search and sorting using recursion. Recursion WHAT DOES THIS CODE DO?

Module Contact: Dr Pierre Chardaire, CMP Copyright of the University of East Anglia Version 1

known as non-void functions/methods in C/C++/Java called from within an expression.

Unit 3 Functions. 1 What is user defined function? Explain with example. Define the syntax of function in C.

CSCE 206: Structured Programming in C++

Downloaded from

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

The University Of Michigan. EECS402 Lecture 07. Andrew M. Morgan. Sorting Arrays. Element Order Of Arrays

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each):

5. Assuming gooddata is a Boolean variable, the following two tests are logically equivalent. if (gooddata == false) if (!

6. C++ Subprograms David Keil CS I slides 7/03 1

Chapter 2. Procedural Programming

Functions. Arizona State University 1

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

Recap. ANSI C Reserved Words C++ Multimedia Programming Lecture 2. Erwin M. Bakker Joachim Rijsdam

Programming Paradigms

C++ Programming. Pointers and Memory Management. M1 Math Michail Lampis

ASSIGNMENT CLASS-11 COMPUTER SCIENCE [C++]

/* EXAMPLE 1 */ #include<stdio.h> int main() { float i=10, *j; void *k; k=&i; j=k; printf("%f\n", *j);

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

If the numbers are 5 and 2,

Arrays in C. Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. Indian Institute of Technology Kharagpur. Basic Concept

Local and Global Variables

Week 9. Muhao Chen

Lecture 9 - C Functions

What Is a Function? Illustration of Program Flow

Bangalore South Campus

To define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug,

Lab Instructor : Jean Lai

CS 161 Intro to CS I. Finish Pointers/Start Recursion

More Functions. Pass by Value. Example: Exchange two numbers. Storage Classes. Passing Parameters by Reference. Pass by value and by reference

Midterm Review. Short Answer. Short Answer. Practice material from the Winter 2014 midterm. Will cover some (but not all) of the questions.

Unit 6. Thinking with Functions

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition)

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

Statements execute in sequence, one after the other, such as the following solution for a quadratic equation:

All the operations used in the expression are over integers. a takes a pair as argument. (a pair is also a tuple, or more specifically, a 2-tuple)

for (i=1; i<=100000; i++) { x = sqrt (y); // square root function cout << x+i << endl; }

Organization of Programming Languages CS 3200/5200N. Lecture 09

Inheritance and Overloading. Week 11

Algorithm. An algorithm is a computational process for solving a problem. computational: a computer must be able to perform the steps of the process

Weeks 6&7: Procedures and Parameter Passing

CS31 Discussion 1E Spring 17 : week 05

Transcription:

Week 3 Muhao Chen Email: muhaochen@ucla.edu 1

Outline Function Break, continue, return 2

Function A batch of statements: Input some parameters to the function, run a procedure, return a result. Y=f(X) 3

A Simple Function int max(int a, int b) { if (a>b)return a; return b; Type of the return value Declare parameters (using local variables) int main(){ int a; //call the function a=max(4,6); //a is 6 4

Another function //trim(). Remove all from the beginning and the end of a string. string trim(string str) { string result= ; int i,j; for (i=0; str[i]== && i<str.size(); ++i); for (j=str.size() - 1; j>=i && str[j]== ; --j); for (int k=i; k<=j; ++k)result+=str[k]; return result; int main(){ string s = Galneryus is a great band. s = trim(s); cout<<s<<endl; // Galneryus is a great band. return str.substr(i, j-i); 5

Void A function with a void return type: no return value. Also known as a procedure or subprogram in some other languages (e.g. pascal). void printfactorial(int n) { int prod = 1; for (int i = 2; i <= n; i++) prod *= i; cout << "The factorial of " << n << " is " << prod << endl; 6

Void void f( ); int a; a=f(); X No return value! 7

Main() main() is also a function. The operating system calls main() to start the program. return 0 of main() In some environment (e.g., a remote procedure call in a distributed system), the system need to know if a program ends successfully by returning a 0. 8

Everything inside a function is local void printfactorial(int n) { int prod = 1; for (int i = 2; i <= n; i++) prod *= i; cout << "The factorial of " << n << " is " << prod << endl; int main () { printfactorial(4); cout << prod; // compiler : prod is not defined 9

Everything inside a function is local 10

Forbidden in functions void function(int a, int b) { int a; double b; 1. Define local variables using the same name as a parameter. (Compile error) X 11

Forbidden in functions bool non_negative(int a) { if (a>0)return true; else if(a<0)return false; 2. A condition (a==0) causes no return of a function. (undefined behavior; compile error in some IDE) X 12

Forbidden in functions int function(int a, int b){ double c = 1.0 * a / b; return c; 3. Inconsistent type of return value. X 13

Forbidden in functions int function1() { int function2() { 4. Nested definition of functions. X 14

Where to place the defined function Before the caller int func(int a, int b){ int main() { c=func(4,6); After the caller Require signature int func(int, int); int main() { c=func(4,6); int func(int a, int b){ 15

Can we define multiple functions with the same name Only if they have different combinations and/or types of parameters. (Overloading) int func(int a) int func(int a, int b) int func(int a, float b) int func(float c, int d) 16

Example //func1 int max(int a, int b) { if(a>b)return a; return b; //func2 float max(float a, float b) { if(a>b)return a; return b; //func3 int max(int a, int b, int c) { //call func1 return max(a, max(b, c)); We can always call a function in another function. int main(){ //call func1 cout<<max(2, 3)<<endl; //call func2 cout<<max(3.7, 4.0)<<endl; //call func3 cout<<max(3,4,5)<<endl; 17

Can we define multiple functions with the same name double func(int a, int b) int func(int a, int b) X It is impossible to tell which definition func(0, 1) corresponds to. Signature of a function: name, #parameters, type of parameters. (Do not incl. type of return) 18

Formal Parameters & Actual Parameters Formal parameters: a.k.a. Pass by Value to a function, but won t change the values of the variables we use to pass the value. (In fact they are just local variables.) int max(int a, int b) { if(a>b)return a; return b; int x=4, y=6; cout<<max(x,y); max() uses the vals of x,y, but does not change their vals. It s OK. void swap(int a, int b) { int tmp=a; a=b; b=tmp; int x=4, y=6; swap(x,y); Change the vals of x,y? It won t work! X is still 4, y is still 6. void mod(int a, intb) { a%=b; int x=40, y=6; mod(x,y); Again, it won t work! X is still 40. 19

Actual Parameters (Pass by Reference) Actual Parameters: we want to both read and write the passed parameters. void swap(int a, int b) { int tmp=a; a=b; c=a; int x=4, y=6; swap(x,y); Changes to void swap(int &a, int &b) { int tmp=a; a=b; c=a; x is 6. y is 4 int x=4, y=6; swap(x,y); void mod(int a, int b) { a%=b; int x=40, y=6; mod(x,y); Changes to void mod(int &a, int b) { a%=b; x is 40%6 -> 4 int x=40, y=6; mod(x,y); 20

Example void trim(string &str) { int i, j; for (i=0; str[i]== && i<str.size(); ++i); for (j=str.size()-1; str[j]== && j>=i; --j); str = str.substr(i, j-i); return; 21

Formal Parameters & Actual Parameters An easy way to remember when to use formal / reference parameters. Type Representation R/W Pass by Value a Read-only Pass by Reference &a Read-or-write 22

Formal Parameters & Actual Parameters The principles Pass by value: parameters are copied local variables Pass by reference: no copying, pass the addresses 23

void swap(int &a,int &b) { a=a^b; b=a^b; a=a^b; Silly, ordinary, and showy swaps (once on social media) void swap(int a,int b) { int temp; temp=a; a=b; b=temp; void swap(int &a,int &b) { int temp; temp=a; a=b; b=temp; void swap(int &a,int &b) { a=a^b; b=a^b; a=a^b; Silly swap Ordinary swap Showy swap 24

An Open Question During industrial development, people (almost) never use pass by value parameters in C++. (Why?) 25

Recursion A function that calls itself. int factorial(unsigned int n) { result = 1; for (int i=2;i<=n;++i)result*=i; return result; int factorial(unsigned int n) { if (n<=1) return 1; else return n * factorial(n-1); Recursive version 26

Recursion More complex problems to solve with recursion: Eight queen problem. Hanoi tower. Transitive closure. Etc We will see a lot of these in CS32. 27

Return; Break; Continue 28

Return; Break; Continue Return: terminates a function. Break: terminates a loop. Continue: terminates a cycle of a loop. 29

Return; Break; Continue void main () { string s= Nissan GTR ; for (int i=0;i<s.size();++i) { if(islower(s[i])) return; cout<s[i]; cout<< Nismo ; void main () { string s= Nissan GTR ; for (int i=0;i<s.size();++i) { if(islower(s[i])) break; cout<s[i]; cout<< Nismo ; void main () { string s= Nissan GTR ; for (int i=0;i<s.size();++i) { if(islower(s[i]))continue; cout<s[i]; cout<< Nismo ; N N Nismo N GTR Nismo 30

Thank you! 31