Chapter 1. Section 1.4 Subprograms or functions. CS 50 - Hathairat Rattanasook

Similar documents
C Programming for Engineers Functions

Methods. Contents Anatomy of a Method How to design a Method Static methods Additional Reading. Anatomy of a Method

EECS402 Lecture 02. Functions. Function Prototype

Functions. CS111 Lab Queens College, CUNY Instructor: Kent Chin

M.CS201 Programming language

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

( &% class MyClass { }

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

Discrete Structures Lecture 14

CS313D: ADVANCED PROGRAMMING LANGUAGE

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

Lecture 2: C Programming Basic

Chapter 7 Functions. Now consider a more advanced example:

Methods. CSE 114, Computer Science 1 Stony Brook University

Program Organization and Comments

Lecture 8 Tao Wang 1

Chapter 2, Part I Introduction to C Programming

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

CS-201 Introduction to Programming with Java

ENERGY 211 / CME 211. Functions

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

User Defined Functions

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

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

CHAPTER 4 FUNCTIONS. 4.1 Introduction

Functions. Lecture 6 COP 3014 Spring February 11, 2018

Lecture 5: Methods CS2301

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

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 9: OCT. 4TH INSTRUCTOR: JIAYIN WANG

UEE1302 (1102) F10: Introduction to Computers and Programming

Lesson 05 Methods. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Computer Programming, I. Laboratory Manual. Experiment #7. Methods

A function is a named piece of code that performs a specific task. Sometimes functions are called methods, procedures, or subroutines (like in LC-3).

4. Structure of a C++ program

4. C++ functions. 1. Library Function 2. User-defined Function

CS1150 Principles of Computer Science Methods

University of Toronto

Programming for Engineers Functions

Language Reference Manual

More loops Ch

CS1150 Principles of Computer Science Methods

COP3502 Programming Fundamentals for CIS Majors 1. Instructor: Parisa Rashidi

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

2. Functions I: Passing by Value

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017

Lecture 16. Daily Puzzle. Functions II they re back and they re not happy. If it is raining at midnight - will we have sunny weather in 72 hours?

Scope of this lecture. Repetition For loops While loops

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II


Preview 8/28/2018. Review for COSC 120 (File Processing: Reading Data From a File)

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

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

CS111: PROGRAMMING LANGUAGE II

Introduction to Programming (Java) 4/12

Introduction to Programming Using Java (98-388)

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

b. array s first element address c. base address of an array d. all elements of an array e. both b and c 9. An array elements are always stored in a.

Functions. Arash Rafiey. September 26, 2017

Chapter 7 User-Defined Methods. Chapter Objectives

UIC. C Programming Primer. Bharathidasan University

CS113: Lecture 4. Topics: Functions. Function Activation Records

2/3/2018 CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II. Lecture Contents. C# basics. Methods Arrays. Dr. Amal Khalifa, Spr17

1 Lexical Considerations

Introduction to C Programming

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

C: How to Program. Week /Mar/05

CSc Introduction to Computing

Fundamentals of Programming & Procedural Programming

Lexical Considerations

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

Admin. CS 112 Introduction to Programming. Recap: Exceptions. Summary: for loop. Recap: CaesarFile using Loop. Summary: Flow Control Statements

A PROBLEM can be solved easily if it is decomposed into parts. Similarly a C program decomposes a program into its component functions.

CS 112 Introduction to Programming

Some Computer Preliminaries

Key Differences Between Python and Java

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

Defining Classes and Methods

Advanced Computer Programming

Chapter 2 - Introduction to C Programming

Chapter 6 Methods. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Chapter 4 Defining Classes I

Exceptions and Design

CSI33 Data Structures

Function: function procedures and sub procedures share the same characteristics, with

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

CS 177 Recitation. Week 8 Methods

2008/11/05: Lecture 15 CMSC 104, Section 0101 John Y. Park

C++ Quick Guide. Advertisements

Sums. Here's a (poor) program to add three numbers

Makefiles Makefiles should begin with a comment section of the following form and with the following information filled in:

C Programming Language

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

Lecture 2 Tao Wang 1

My First Command-Line Program

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

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

Transcription:

Chapter 1 Section 1.4 Subprograms or functions 0

Functions Functions are essential in writing structured and well-organized code. Functions help for code to be reused. Functions help to reduce errors and bugs. When to create a function: When you repeat to write the same code multiple times If a function gets too long, split the code into several smaller functions and call these smaller functions instead. Write a function for a logical self-contained section of code, For example: calculation the maximum of two variables. 1

Example of a function return type function name parameters function body int square(int num) { int result; result = num * num return result; Function name: Use a name that meaninfully describes what your function does return type: the data type your function produces, for example: int, char, etc. parameters: these are 0..n variables that are passed to the function function body: this is the code of the function. You can use return to exit there function and a variable or value, like result if your function returns a value. 2

Function Components A function consists of the following components: Function header: it consists of the function type, the function s name (an identifier), optionally parameters, a pair of parentheses. int slicecake( double cakeradius, int count ) {... Type: the type of the function s return value. Type void: This means that the function does not return a value. name: the name of the function describes what the function does parameters: data can be passed into and even out of a function. Parameters are optional and can be left out. Function body or function block: { and the braces mark the beginning and the end of the function. The task that the function performs must be written inside this block. 3

Questions? 1. Can you have a function that has no parameters and does not return anything? 2. Can a function return multiple values? 3. How many statements are allowed inside the function body? 4. Write a function that adds two int numbers. What would that function look like? 4

Answers 1. Sure, you can but it may not be useful most of the time. The function would look like this: void donothing() {... 2. No, each function may return none (void as return type) or a single value. 3. As many as you like but each function should only perform one task or one idea. 4. The function return type would be int, and we need two parameters for the two numbers to be added which also would be of type int: int add(int num1, int num2) { return num1 + num2; 5

Examples of function signatures // this function returns int and has no parameters int readnumber() {... // this function the average of the three given numbers double calculateavg(double num1, double num2, double num3) {... // this function calculates the maximum value in the given array int calcmax(int[] numberarray) {... // this function prints the name, gender, and age to the console void printperson(char[] name, char gender, int age) {... 6

Function Body The function body is the code inside a function. The body is surrounded by braces, { and The return keyword is used to stop execution of the function and returns a value of the defined return type, for example: int getmax(int num1, int num2) { if (num1 > num2) { return num1; else { return num2; Note: If the function's return type is void, using return; without a value is enough. 7

Comments Comments are used to make notes or describe code Multi line comments start with /* and end with */ Single line comments start with // and end with the end of the line Comments are ignored by the compiler A good programmer uses comments to describe his code to make it easier for others to understand 8

Comments Example /* This program asks the user for two numbers and prints out the maximum of these two numbers */ // declare variables int num1, num2; int result; // ask user for input num1 = readinput(); num2 = readinput(); // calculate maximum result = calculatemax(num1, num2); printf("%d", result); 9

Main Function The main() function is special as it defines the start of the program. int main() { // // write your code here // return 0; The return type must be int. Return 0 at the end of your program to show the compiler that everything is fine. We will not go into the details of the return value in this chapter. 10

Calling a function We learned how to write a function but how to call and execute it? A function call consists of the function name followed by ( and ). If the function has parameters, we also need to pass in the arguments that match the expected parameters. For example: // this function adds two numbers int add(int num1, num2) { return num1 + num 2; /* we just write the function name and pass in two numbers as arguments */ add(1, 2); 11

Calling a function Every function must be declared before we can call it. Therefore, it is good practice to declare all functions before the main() function. On the right is an example of a nice program that calls multiple functions. Note: the function bodies are left empty for clarity: // this function adds two numbers int add(int num1, num2) {... // ask the user for a number int readinput() {... // print the result to the console void print(int result) {... int main() { int num1, num2, result; num1 = readinput(); // calling readinput() above num2 = readinput(); result = add(num1, num2); // calling add(..) above print(result); // calling print(..) above 12

Questions? 1. Do you need to write the return type when you call a function? 2. Do you have to assign the returned value to a variable? 3. Do you need a cell phone to call a function? 13

Answers 1. No, you don't write the return type when calling a function but the return type in the function's declaration helps you to know what you can expect. 2. No, if you have a function like int add(int num1, num2) {... which returns int, you can call it and assign the return value or you could just ignore it: int main() {... result = add(1, 5); // assign returned value to result add(1, 5); // ignore returned value... 3. No, you don't need a cell phone, you don't even need network coverage! 14