C++ Programming Lecture 11 Functions Part I

Similar documents
CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Introduction to Programming

Chapter 3 - Functions

Functions and Recursion

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

Lecture 04 FUNCTIONS AND ARRAYS

Chapter 2. Outline. Simple C++ Programs

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

Introduction. What is function? Multiple functions form a larger program Modular programming

C Programming for Engineers Functions

C++ Overview. Chapter 1. Chapter 2

CSI31 Lecture 5. Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial

C Functions. 5.2 Program Modules in C

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

Computer Science & Engineering 150A Problem Solving Using Computers

Chapter 6 - Notes User-Defined Functions I

Methods CSC 121 Fall 2014 Howard Rosenthal

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 3. Existing Information. Notes. Notes. Notes. Lecture 03 - Functions

Summary of basic C++-commands

Chapter 3 - Functions

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

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++

Chapter 3. Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus. Existing Information.

Engineering Problem Solving with C++, Etter/Ingber

Functions. Systems Programming Concepts

Chapter 3 - Functions

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

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

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

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

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

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.

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

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

Goals for This Lecture:

Using Free Functions

Methods CSC 121 Fall 2016 Howard Rosenthal

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

CT 229 Java Syntax Continued

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

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions

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

PROGRAMMING WITH MATLAB DR. AHMET AKBULUT

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

Methods CSC 121 Spring 2017 Howard Rosenthal

Introduction to C++ Introduction to C++ 1

A. Introduction to Function 1. Modular Programming input processing output functions library functions 2. Function 1. Benefit of Using Functions

Computing and Statistical Data Analysis Lecture 3

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

Functions and Recursion

MYSQL NUMERIC FUNCTIONS

C++ Programming: Functions

Lecture 04 FUNCTIONS AND ARRAYS

Introduction to Engineering gii

Functions and Recursion

Lab Instructor : Jean Lai

Fundamentals of Programming & Procedural Programming

Chapter 4: Basic C Operators

Structured programming

The Number object. to set specific number types (like integer, short, In JavaScript all numbers are 64bit floating point

2 Making Decisions. Store the value 3 in memory location y

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

Intrinsic Functions Outline

CSE123. Program Design and Modular Programming Functions 1-1

A function is a named group of statements developed to solve a sub-problem and returns a value to other functions when it is called.

Standard Library Functions Outline

Product Price Formula extension for Magento2. User Guide

Functions. Lecture 6 COP 3014 Spring February 11, 2018

Programming for Engineers Functions

Introduction to C++ Systems Programming

ANSI C Programming Simple Programs

Introduction to Computers II Lecture 4. Dr Ali Ziya Alkar Dr Mehmet Demirer

Introduction to C++ Dr Alex Martin Room 6.10

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

C Functions. Object created and destroyed within its block auto: default for local variables

Introduction to MATLAB

ECET 264 C Programming Language with Applications

Operations. Making Things Happen

Introduction to Programming

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

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

Python Programming: An Introduction to Computer Science

Maths Functions User Manual

IS 0020 Program Design and Software Tools

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

Methods: A Deeper Look

Chapter 15 - C++ As A "Better C"

PIC 10A. Lecture 3: More About Variables, Arithmetic, Casting, Assignment

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 5. Playing with Data Modifiers and Math Functions Getting Controls

IS 0020 Program Design and Software Tools

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

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

Variable and Data Type 2

Methods (Deitel chapter 6)

Methods (Deitel chapter 6)

Introduction to C++ Introduction and History. Characteristics of C++

Programming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming.

Object Oriented Methods : Deeper Look Lecture Three

Transcription:

C++ Programming Lecture 11 Functions Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department

Introduction Till now we have learned the basic concepts of C++. All the programs that we have written are simple, have few lines of code, and flat (i.e. all the code resides inside the main() body). But: What about large programs? What about code reuse (when the same code block is used many times within the program)? Divide and conquer technique: Construct a program from smaller pieces or components Each piece more manageable than the original program The Hashemite University 2

Program Components in C++ I C++ modules are functions and classes. Programs are written by: Combining new functions with prepackaged functions in the C++ standard library. The standard library provides a rich collection of functions. Functions are invoked by a function call A function call specifies the function name and provides information (as arguments) that the called function needs. Similar to the boss to worker analogy: A boss (the calling function or caller) asks a worker (the called function) to perform a task and return (i.e., report back) the results when the task is done. The Hashemite University 3

Program Components in C++ II Function definition: It is the body of the function which include all the processing done by the function. It makes use of the parameters (arguments) passed by the function call and specifies what will be returned by the function (result of the function). Only written once. These statements are hidden from other functions. Boss to worker analogy: The boss does not know how the worker gets the job done; he just wants it done The Hashemite University 4

Math Library Functions I Math library functions Allow the programmer to perform common mathematical calculations Are used by including the header file <cmath> or <math.h> Functions called by writing functionname (argument) Example cout << sqrt( 900.0 ); Calls the sqrt (square root) function. The preceding statement would print 30 The sqrt function takes an argument of type double and returns a result of type double, as do all functions in the math library The Hashemite University 5

Math Library Functions II All math library functions return double values (as a result). Function arguments can be Constants sqrt( 4 ); Variables sqrt( x ); Expressions sqrt( sqrt( x ) ) ; sqrt( 3-6x ); The Hashemite University 6

Math Library Functions III acos(x) inverse cosine, -1 <= x <= +1, returns value in radians in range 0 to PI asin(x) inverse sine, -1 <= x <= +1, returns value in radians in range 0 to PI atan(x) inverse tangent, returns value in radians in range -PI/2 to PI/2 cos(x) returns cosine of x, x in radians sin(x) returns sine of x, x in radians tan(x) returns tangent of x, x in radians exp(x) exponential function, e to power x log(x) natural log of x (base e), x > 0 sqrt(x) square root of x, x >= 0 fabs(x) absolute value of x floor(x) largest integer not greater than x ceil(x) smallest integer not less than x. pow(x, y) returns x y. fmod(x, y) computes the modulus of floating point numbers. Note: Have a look at Figure 3.2 in chapter 3. The Hashemite University 7

Functions Functions Allow the programmer to modularize a program. Local variables Known only in the function in which they are defined. All variables declared in function definitions are local variables. Parameters Local variables passed when the function is called that provide the function with outside information. The Hashemite University 8

1 // Fig. 3.3: fig03_03.cpp 2 // Creating and using a programmer-defined function 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 int square( int ); // function prototype 9 10 int main() 11 { 12 for ( int x = 1; x <= 10; x++ ) 13 cout << square( x ) << " "; 14 15 cout << endl; 16 return 0; 17 } 18 19 // Function definition 20 int square( int y ) 21 { 22 return y * y; 23 } Notice how parameters and return value are declared. 1 4 9 16 25 36 49 64 81 100 The Hashemite University 9

Function Definitions Create customized functions to: Take in data Perform operations Return the result Format for function definition: return-value-type function-name( parameter-list ) { declarations and statements } Function name is any valid identifier. Example: int square( int y) { return y * y; } The Hashemite University 10

Function Prototypes I Used by the compiler to check the validity of the function call within the main program (function name, its return data type, number of arguments, their data types, and their order). Function prototype consist of: Function name Parameters Information the function takes in, can be void. Return type Type of information the function passes back to caller (default int) void signifies the function returns nothing The Hashemite University 11

Function Prototypes II If you have passed arguments of different data types from the one specified in the function prototype and definition, the compiler will convert them to the proper data type for the function (implicit casting). Not following the Promotion Rule in C++ an cause errors in the obtained results. E.g. converting from double to integer causes data loss but converting integer to double is not. Only needed if function definition comes after the function call in the program (after the main()). Another example: int maximum( int, int, int ); Takes in 3 ints Returns an int The Hashemite University 12

Functions Returning Results Three ways to return top the point at which we have called a function: Reaching closing brace } of the function definition (the function return nothing).. Executing return; (the function returns nothing). Executing return result; (the function returns a specific result). The Hashemite University 13

1 // Fig. 3.4: fig03_04.cpp 2 // Finding the maximum of three integers 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 int maximum( int, int, int ); // function prototype 10 11 int main() 12 { 13 int a, b, c; 14 15 cout << "Enter three integers: "; 16 cin >> a >> b >> c; 17 18 // a, b and c below are arguments to 19 // the maximum function call 20 cout << "Maximum is: " << maximum( a, The b, c Hashemite ) << endl; University 14

21 22 return 0; 23 } 24 25 // Function maximum definition 26 // x, y and z below are parameters to 27 // the maximum function definition 28 int maximum( int x, int y, int z ) 29 { 30 int max = x; 31 32 if ( y > max ) 33 max = y; 34 35 if ( z > max ) 36 max = z; 37 38 return max; 39 } Enter three integers: 22 85 17 Maximum is: 85 Enter three integers: 92 35 14 Maximum is: 92 Enter three integers: 45 19 98 Maximum is: 98 The Hashemite University 15

Header Files Header files Contain function prototypes for library functions <cstdlib>, <cmath>, etc. Load with #include <filename> Example: #include <cmath> Custom header files Defined by the programmer Save as filename.h Loaded into program using #include "filename.h Have a look at Figure 3.6 in chapter 3. The Hashemite University 16

Additional Notes This lecture covers the following material from the textbook: Chapter 3: Sections 3.1 3.7 The Hashemite University 17