Using Free Functions

Similar documents
Introduction to Programming

C++ Programming Lecture 11 Functions Part I

C Programs: Simple Statements and Expressions

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1

DUBLIN CITY UNIVERSITY

The Math Class (Outsource: Math Class Supplement) Random Numbers. Lab 06 Math Class

DUBLIN CITY UNIVERSITY

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from

(created by professor Marina Tanasyuk) FUNCTIONS

Chapter 6 - Notes User-Defined Functions I

CISC 1110 (CIS 1.5) Introduc2on to Programming Using C++

1st and 3rd September 2015

static int min(int a, int b) Returns the smaller of two int values. static double pow(double a,

Programming Language. Functions. Eng. Anis Nazer First Semester

Chapter 2. Outline. Simple C++ Programs

Procedural Abstraction and Functions That Return a Value. Savitch, Chapter 4

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

ECET 264 C Programming Language with Applications

Engineering Problem Solving with C++, Etter/Ingber

Chapter 3 - Functions

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

Functions and Recursion

Lab Instructor : Jean Lai

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

CT 229 Java Syntax Continued

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

Summary of basic C++-commands

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

PASS$MOCK$EXAM$ $FOR$PRACTICE$ONLY$

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Advanced features of the Calculate signal tool

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

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 6: User-Defined Functions I

12. Numbers. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.6

CS110: PROGRAMMING LANGUAGE I

The Math Class. Using various math class methods. Formatting the values.

CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011

Primitive Data Types: Intro

Preview from Notesale.co.uk Page 2 of 79

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction

Function. Mathematical function and C+ + function. Input: arguments. Output: return value

Methods: A Deeper Look

Function Example. Function Definition. C Programming. Syntax. A small program(subroutine) that performs a particular task. Modular programming design

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A.

1. Variables 2. Arithmetic 3. Input and output 4. Problem solving: first do it by hand 5. Strings 6. Chapter summary

1001ICT Introduction To Programming Lecture Notes

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

Functions and an Introduction to Recursion Pearson Education, Inc. All rights reserved.

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types

Chapter 5 Methods. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

The cin Object. cout << "Enter the length and the width of the rectangle? "; cin >> length >> width;

Function. specific, well-defined task. whenever it is called or invoked. A function to add two numbers A function to find the largest of n numbers

3. Functions. Modular programming is the dividing of the entire problem into small sub problems that can be solved by writing separate programs.

Functions. Systems Programming Concepts

C Functions. 5.2 Program Modules in C

Programming I Lecture 7

Chapter 5 Methods. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

Fundamentals of Programming & Procedural Programming

Methods CSC 121 Fall 2014 Howard Rosenthal

Expressions and operators

CSCE 110 PROGRAMMING FUNDAMENTALS

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

3.1. Chapter 3: The cin Object. Expressions and Interactivity

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

Top-Down Design Predefined Functions Programmer-Defined Functions Procedural Abstraction Local Variables Overloading Function Names

Chapter 5 Methods / Functions

Python Lists: Example 1: >>> items=["apple", "orange",100,25.5] >>> items[0] 'apple' >>> 3*items[:2]

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions

Programming in C Quick Start! Biostatistics 615 Lecture 4

Lecture 14. Daily Puzzle. Math in C. Rearrange the letters of eleven plus two to make this mathematical statement true. Eleven plus two =?

JAVA Programming Concepts

CS2141 Software Development using C/C++ C++ Basics

Outline. Functions. Functions. Predefined Functions. Example. Example. Predefined functions User-defined functions Actual parameters Formal parameters

Chapter 3. Numeric Types, Expressions, and Output

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

Benefits of Methods. Chapter 5 Methods

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

What did we talk about last time? Examples switch statements

Chapter 6 Methods. Dr. Hikmat Jaber

Methods CSC 121 Fall 2016 Howard Rosenthal

What did we talk about last time? Math methods boolean operations char operations


Chapter 5 Methods. Modifier returnvaluetype methodname(list of parameters) { // method body; }

Chapter Two: Fundamental Data Types

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

Functions. A function is a subprogram that performs a specific task. Functions you know: cout << Hi ; cin >> number;

Chapter 2 C++ Fundamentals

Character Functions & Manipulators Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10

CSC 1051 Algorithms and Data Structures I. Midterm Examination March 1, Name: KEY A

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

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

MYSQL NUMERIC FUNCTIONS

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

Announcements. Lab 1 this week! Homework posted Wednesday (late)

Unit 6. Thinking with Functions

Transcription:

Chapter 3 Using Free Functions 3rd Edition Computing Fundamentals with C++ Rick Mercer Franklin, Beedle & Associates

Goals Evaluate some mathematical and trigonometric functions Use arguments in function calls Appreciate why programmers divide software into functions Read function headings so you can use existing functions

cmath functions C++ defines a large collection of standard math and trig functions such as sqrt(x) // return the square root of x fabs(x) // return the absolute value of x Functions are called by specifying the function name followed by the argument(s) in parentheses: cout << sqrt(4.0) << " " << fabs(-2.34); To use mathematical functions, you must #include <cmath> // For ceil, floor, pow

The pow function The pow function returns the first argument to the second argument's power pow(2.0, 3.0) returns 2 to the 3rd power (2 3 = 8.0) #include <cmath> // For the cmath functions #include <iostream> using namespace std; int main() { double base, power; base = 2.0; power = 4.0; cout << pow(base, power) << endl; cout << pow(-2, 3) << endl; return 0; }

Function Headings Can understand how to use a function if you see the function heading General form type functionname (type arg1, type arg2, ) One function heading double pow(double base, double power) Comments example function calls also help pow(5.0, 3.0) // evaluates to 125

Some cmath functions double ceil(double x) Smallest integer >= x ceil(2.1) 3.0 double cos(double x) Cosine of x radians cos(1.0) 0.5403 double fabs(double x) Absolute value of x fabs(-1.5) 1.5 double floor(double x) Largest integer <= x floor(2.9) 2.0 double round(double x) Nearest integer to x round(1.5) 2 double sin(double x) Sine of x radians sin(1.0) 0.84147 double sqrt(double x) Square root of x sqrt(4.0) 2.0

Evaluate some Function Calls Different arguments cause different return values ceil(0.1) sqrt(16.0) ceil(1.1) pow(2.0, 3) sqrt(4.0) sqrt(sqrt(16)) fabs(-1.2) floor(3.99)

Rounding to n decimals Code that rounds x to n decimal places using the pow and floor functions x = 456.789; n = 2; x = x * pow(10, n); // x x = x + 0.5; x = floor(x); x = x / pow(10, n); // x // x // x

Calling Documented Functions C++ has many free functions available Programmers can write their own free functions to develop programs Functions are more easily understood when documented with comment Functions may also include pre- and postconditions next slide

Preconditions and Postconditions C++ comments that represents a contract between the implementers of a function and the user (client) of that function Precondition What the function requires to be true when called Postcondition What the function will do if the precondition(s) is/are met

Pre: and Post: conditions The preconditions are the circumstances that must be true in order for the function to successfully fulfill the postconditions Example Precondition abbreviates to pre: double sqrt(double x) // pre: x >= 0 // post: Returns square root of x sqrt(-1.0) evaluates to nan (not a number)

Function Headings A function heading is the complete declaration of a function without its implementation (sometimes called the function's signature). For example, this signature tells us how to call the function, but not how it works: double sqrt(double x)

Function Headings General form of a function heading: return-type function-name ( parameter-list ) return-type is any C++ type e.g. double int string function-name is any valid C++ identifier that is not reserved parameter-list is a set of 0 or more parameters General form for declaring parameters: class-name identifier Examples double f(double x) int max(int j, int k) string duplicate(string str, int n)

Argument/Parameter Associations Example call to max shows that arguments match parameters by position double max(double x, double y) cout << max(3.0, -5.32); The value of the 1 st argument is copied to the 1 st parameter, the value of the 2 nd argument to the 2 nd parameter, and so on, like assignments: x = 3.0; y = -5.32;

char and bool types C++ has two other primitive types that are used as the return types or parameters: char and bool bool type functions return 0 if the function returns false or a non-zero for true (usually 1) #include <cctype> // isdigit isalpha #include <iostream> using namespace std; int main() { cout << isdigit('9') << endl; // 1 cout << isdigit('x') << endl; // 0 cout << isalpha('a') << endl; // 1 cout << isalpha('<') << endl; // 0 return 0; }

char and int The toupper and tolower functions convert a char to its lower case or upper case equivalent Because the return type for both is int instead of char, the functions need to be cast to char with the code (char) to see the character toupper('a') // 65 (char) toupper('a') // A tolower('a') // 97 (char) tolower('a') // a

Summary Documented function headings provide the following information: The type of value returned by the function The function name The number of arguments to use in a call The type of arguments required in the function call Pre- and post-conditions tell us what the function will do if the preconditions are met