C++ PROGRAMMING SKILLS Part 3 User-Defined Functions

Similar documents
Introduction to Programming

Chapter 3 - Functions

Functions and Recursion

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

C Functions. 5.2 Program Modules in C

Chapter 3 - Functions

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

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

Functions. Systems Programming Concepts

Methods: A Deeper Look

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

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

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

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

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

CSE123. Program Design and Modular Programming Functions 1-1

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

C++ Programming Lecture 11 Functions Part I

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Methods (Deitel chapter 6)

Methods (Deitel chapter 6)

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Functions. Introduction :

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

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

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

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

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

C Functions Pearson Education, Inc. All rights reserved.

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

Lecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch

C Programs: Simple Statements and Expressions

Chapter 5 C Functions

Programming Language. Functions. Eng. Anis Nazer First Semester

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

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

Functions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa

ECET 264 C Programming Language with Applications

Lab Instructor : Jean Lai

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

Lecture 04 FUNCTIONS AND ARRAYS

Downloaded from

Fundamentals of Programming & Procedural Programming

Lecture 2:- Functions. Introduction

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

Downloaded from Chapter 2. Functions

Programming for Engineers Functions

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

C Programming for Engineers Functions

Functions and Recursion

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

Functions. Lecture 6 COP 3014 Spring February 11, 2018

CT 229 Java Syntax Continued

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

Chapter 3 - Functions

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

Chapter 6 - Notes User-Defined Functions I

C++ How to Program, 9/e by Pearson Education, Inc. All Rights Reserved.

Unit 7. Functions. Need of User Defined Functions

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

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.

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

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

Using Free Functions

EECS402 Lecture 02. Functions. Function Prototype

UNIT- 3 Introduction to C++

Introduction to C Language

1001ICT Introduction To Programming Lecture Notes

LESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long

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

Computing and Statistical Data Analysis Lecture 3

(created by professor Marina Tanasyuk) FUNCTIONS

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

Objectives. In this chapter, you will:

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

Fall Semester (081) Dr. El-Sayed El-Alfy Computer Science Department King Fahd University of Petroleum and Minerals

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

Built-in Types of Data

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

CSCE 110 PROGRAMMING FUNDAMENTALS

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

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

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Lecture 9 - C Functions


SUHAIL T A

Introduction to Functions in C. Dr. Ahmed Telba King Saud University College of Engineering Electrical Engineering Department

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

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

UNIT 1. Introduction

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

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

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

Assoc. Prof. Dr. Tansu FİLİK

CS110: PROGRAMMING LANGUAGE I

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

Lecture 04 FUNCTIONS AND ARRAYS

142

Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations

Transcription:

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions Introduction Function Definition Void function Global Vs Local variables Random Number Generator Recursion Function Overloading Sample Code 1

Functions in C++ 2 Experience has shown that the best way to develop and maintain large programs is to construct it from smaller pieces(modules) This technique Called Divide and Conquer Bad Development Approach main() ----- ----- ----- -----... ---- ----- ----- Return 0; Easer To Design Build Debug Extend Modify Understand Reuse Better Organization Wise Development Approach main() ----- ---- function f1() --- --- function f2() --- ---

Function Calling Functions called by writing functionname (argument); or functionname(argument1, argument2, ); Example cout << sqrt( 900.0 ); sqrt (square root) function The preceding statement would print 30 All functions in math library return a double Function Arguments can be: - Constant sqrt(9); - Variable sqrt(x); - Expression sqrt( x*9 + y) ; sqrt( sqrt(x) ) ; 3

Function Calling Calling/invoking a function sqrt(x); Parentheses an operator used to call function Pass argument x Function gets its own copy of arguments After finished, passes back result Function Name cout<< sqrt(9); argument 3 Output 4 Parentheses used to enclose argument(s)

Math Library Functions Revisited Method Description Example ceil( x ) rounds x to the sm allest integer not less than x ceil( 9.2 ) is 10.0 ceil( -9.8 ) is -9.0 cos( x ) trigonometric cosine of x cos( 0.0 ) is 1.0 (x in radians) exp( x ) exponential function ex exp( 1.0 ) is 2.71828 exp( 2.0 ) is 7.38906 fabs( x ) absolute value of x fabs( 5.1 ) is 5.1 fabs( 0.0 ) is 0.0 fabs( -8.76 ) is 8.76 floor( x ) rounds x to the largest integer not greater than x floor( 9.2 ) is 9.0 floor( -9.8 ) is -10.0 fmod( x, y ) rem ainder of x/y as a floatingpoint fmod( 13.657, 2.333 ) is 1.992 num ber log( x ) natural logarithm of x (base e ) log( 2.718282 ) is 1.0 log( 7.389056 ) is 2.0 log10( x ) logarithm of x (base 10) log10( 10.0 ) is 1.0 log10( 100.0 ) is 2.0 pow( x, y ) x raised to pow er y (xy) pow( 2, 7 ) is 128 pow( 9,.5 ) is 3 sin( x ) trigonom etric sine of x sin( 0.0 ) is 0 (x in radians) sqrt( x ) square root of x sqrt( 900.0 ) is 30.0 sqrt( 9.0 ) is 3.0 tan( x ) trigonom etric tangent of x (x in radians) tan( 0.0 ) is 0 Fig. 3.2 M a th lib ra ry func tio ns. 5

Functions Functions Modularize a program Software reusability Call function multiple times 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 to function when called Provide outside information 6

Function Definition Function prototype Tells compiler argument type and return type of function int square( int ); Function takes an int and returns an int Explained in more detail later Calling/invoking a function square(x); Parentheses an operator used to call function Pass argument x Function gets its own copy of arguments After finished, passes back result 7

Function Definition Syntax format for function definition returned-value-type function-name (parameter-list) Declarations of local variables and Statements Parameter list Comma separated list of arguments Data type needed for each argument If no arguments, use void or leave blank Return-value-type Data type of result returned (use void if nothing returned) 8

Function Definition Example function int square( int y ) return y * y; return keyword Returns data, and control goes to function s caller If no data to return, use return; Function ends when reaches right brace Control goes to caller Functions cannot be defined inside other functions 9

// Creating and using a programmer-defined function. #include <iostream.h> int square( int ); // function prototype int main() // loop 10 times and calculate and output // square of x each time for ( int x = 1; x <= 10; x++ ) cout << square( x ) << " "; // function call cout << endl; return 0; // indicates successful termination Function prototype: specifies data types of arguments and return values. square expects an int, and returns an int. Parentheses () cause function to be called. When done, it returns the result. // end main // square function definition returns square of an integer int square( int y ) // y is a copy of argument to function return y * y; // returns square of y as an int // end function square Definition of square. y is a copy of the argument passed. Returns y * y, or y squared. 1 4 9 16 25 36 49 64 81 100 10

compute square and cube of numbers [1..10] using functions #include<iostream.h> int square(int); // prototype int cube(int); // prototype main() int i; for (int i=1;i<=10;i++) cout<< i<< square= << square(i) << endl; cout<< i<< cube= <<cube(i) << endl; // end for return 0; // end main function int square(int y) //function definition return y*y; // returned Result Output 1 square=1 1 cube=1 2 square=4 2 cube=8.... 10 square=100 10 cube=1000 int cube(int y) //function definition return y*y*y; // returned Result 11

// Finding the maximum of three floating-point (real) numbers. #include <iostream.h> double maximum( double, double, double ); // function prototype int main() double number1, number2; double number3; cout << "Enter three real numbers: "; cin >> number1 >> number2 >> number3; Function maximum takes 3 arguments (all double) and returns a double. // number1, number2 and number3 are arguments to the maximum function call cout << "Maximum is: " << maximum( number1, number2, number3 ) << endl; return 0; // indicates successful termination // end main // function maximum definition. x, y and z are parameters double maximum( double x, double y, double z ) double max = x; // assume x is largest if ( y > max ) // if y is larger, max = y; // assign y to max if ( z > max ) // if z is larger, max = z; // assign z to max return max; // max is largest value // end function maximum 12 Enter three real numbers: 99.32 37.3 27.1928 Maximum is: 99.32 Enter three real numbers: 1.1 3.333 2.22 Maximum is: 3.333

Function Prototypes Function prototype contains Function name Parameters (number and data type) Return type (void if returns nothing) Only needed if function definition after function call Prototype must match function definition Function prototype double maximum( double, double, double ); Definition double maximum( double x, double y, double z ) 13

void Function takes arguments If the Function does not RETURN result, it is called void Function #include<iostream.h> void add2nums(int,int); main() int a, b; cout<< enter tow Number: ; cin >>a >> b; add2nums(a, b); return 0; void add2nums(int x, int y) cout<< x<< + << y << = << x+y; 14

void Function take no arguments If the function Does Not Take Arguments specify this with EMPTY-LIST OR write void inside #include<iostream.h> void funa(); void funb(void); main() funa(); funb(); return 0; void funa() Will be the same in all cases cout << Function-A takes no arquments\n ; void funb() cout << Also Function-B takes No arguments\n ; 15

Remarks on Functions Local variables Known only in the function in which they are defined All variables declared inside a function are local variables Parameters Local variables passed to function when called (passing-parameters) Variables defined outside and before function main: Called global variables Can be accessible and used anywhere in the entire program 16

Remarks on Functions Omitting the type of returned result defaults to int, but omitting a non-integer type is a Syntax Error If a Global variable defined again as a local variable in a function, then the Local-definition overrides the Global defining Function prototype, function definition, and function call must be consistent in: 1- Number of arguments 2- Type of those arguments 3-Order of those arguments 17

Local vs Global Variables #include<iostream.h> int x,y; //Global Variables int add2(int, int); //prototype main() int s; x = 11; y = 22; cout << global x= << x << endl; cout << Global y= << y << endl; s = add2(x, y); cout << x << + << y << = << s; cout<<endl; cout<< \n---end of output---\n ; return 0; int add2(int x1,int y1) int x; //local variables x=44; cout << \nlocal x= << x << endl; return x1+y1; global x=11 global y=22 Local x=44 11+22=33 ---end of output--- 18

Finding Errors in Function Code int sum(int x, int y) int result; result = x+y; this function must return an integer value as indicated in the header definition (return result;) should be added ----------------------------------------------------------------------------------------- int sum (int n) if (n==0) return 0; else n+sum(n-1); the result of n+sum(n-1) is not returned; sum returns an improper result, the else part should be written as:- else return n+sum(n-1); 19

Finding Errors in Function Code void f(float a); float a; cout<<a<<endl; ; found after function definition header. redefining the parameter a in the function void f(float a) float a2 = a + 8.9; cout <<a2<<endl; 20

Finding Errors in Function Code void product(void) int a, b, c, result; cout << enter three integers: ; cin >> a >> b >> c; result = a*b*c; cout << Result is << result; return result; According to the definition it should not return a value, but in the block (body) it did & this is WRONG. Remove return Result; 21

Function Call Methods Call by value A copy of the value is passed Call by reference The caller passes the address of the value Call by value Up to this point all the calls we have seen are call-by-value, a copy of the value (known) is passed from the caller-function to the called-function Any change to the copy does not affect the original value in the caller function Advantages, prevents side effect, resulting in reliable software 22

Function Call Methods Call By Reference We introduce reference-parameter, to perform call by reference. The caller gives the called function the ability to directly access the caller s value, and to modify it. A reference parameter is an alias for it s corresponding argument, it is stated in c++ by flow the parameter s type in the function prototype by an ampersand(&) also in the function definition-header. Advantage: performance issue void function_name (type &);// prototype main() ----- ------ void function_name(type &parameter_name) 23

Function Call Example #include<iostream.h> int squareval(int); //prototype call by value function void squareref(int &); // prototype call by reference function int main() int x=2; z=4; cout<< x= << x << before calling squareval ; cout << \n << squareval(x) << \n ; // call by value cout<< x= << x << After returning cout<< z= << z << before calling squareref ; squareref(z); // call by reference cout<< z= << z<< After returning squareref return 0; int squareval(int a) return a*=a; // caller s argument not modified void squarref(int &cref) cref *= cref; // caller s argument modified x=2 before calling squareval 4 x=2 after returning z=4 before calling squareref z=16 after returning squareref 24

Random Number Generator rand function generates an integer between 0 and RAND- MAX(~32767) a symbolic constant defined in <stdlib.h> You may use modulus operator (%) to generate numbers within a specifically range with rand. 25 //generate 10 random numbers open-range int x; for( int i=0; i<=10; i++) x=rand(); cout<<x<< ; ------------------------------------------------------- //generate 10 integers between 0..49 int x; for( int i=0; i<10; i++) x=rand()%50; cout<<x<< ;

Random Number Generator //generate 10 integers between 5 15 int x; for ( int i=1; i<=10; i++) x= rand()%11 + 5; cout<<x<< ; ------------------------------------ //generate 100 number as simulation of rolling a dice int x; for (int i=1; i<=100; i++) x= rand%6 + 1; cout<<x<< ; 26

Random Number Generator the rand( ) function will generate the same set of random numbers each time you run the program. To force NEW set of random numbers with each new run use the randomizing process Randomizing is accomplished with the standard library function srand(unsigned integer); which needs a header file <stdlib.h> Explanation of signed and unsigned integers: int is stored in at least two-bytes of memory and can have positive & negative values unsigned int also stored in at least two-bytes of memory but it can have only positive values 0..65535 27

Randomizing with srand #include<iostream.h> #include<iomanip.h> #include<stdlib.h> int main() int i; unsigned num; // we will enter a different number each time we run cin>>num; srand(num); for(i=1; i<=5; i++) cout<<setw(10)<< 1+rand()%6; return 0; 19 6 1 1 4 2 1 18 6 1 5 1 4 4 3 1 2 5 6 2 4 0 1 5 5 3 5 5 3 1 2 5 6 3 4 Output for Multiple Runs Different-set of Random numbers 28

#include<iostream.h> #include<iomanip.h> #include<stdlib.h> int main() int i; without srand for(i=1; i<=5; i++) cout<<setw(10)<< 1+rand()%6; return 0; 5 3 3 5 4 2 5 3 3 5 4 2 5 3 3 5 4 2 5 3 3 5 4 2 6 5 3 3 5 4 Output for Multiple Runs Same set of numbers for each run 29

Recursion and Recursive Functions Main calls another function..normal A function calls another function2.normal A function calls itself?! Possible?? YES A recursive function is one that call itself. 30

Concept Of recursion A recursive function is called to solve a problem The function knows to solve only the simplest cases or so-called base-cases Thus if the function called with a base-case, it simply returns a result. But if it is called with more complex problem, the function divides the problem into two conceptual pieces, one knows how to do, and another doesn't know what to do. The second case/piece must resemble the original problem, but be a slightly simpler/smaller version of the original problem 31

Concept Of recursion (cont.) Thus the function launches (calls) a fresh copy of itself to work on the smaller problem this is related as a Recursive-call/recursive step. The function keeps dividing each new sub problem into two conceptual pieces until eventually terminates after converging on the base-case. The function thus recognize the base-case and returns a result to the previous copy of the way up the line until original call of the function returns the final result to main. 32

Finding Factorial Recursively 5! 5! Final value=120 5*4! 5*4! 5!=5*24=120 returned 4*3! 3*2! 4*3! 3*2! 4!=4*6=24 returned 3!=3*2=6 returned 2*1! 2*1! 2!=2*1=2 returned 33 1 1 1

Finding Factorial Recursively //Recursive factorial Function #include<iostream.h> #include<iomonip.h> unsigned lion factorial(unsigned long);//prototype int main() int num; cout<< enter a positive integer: ; cin>>num; cout<< factorial= <<factorial(num); return 0; unsigned long factorial(unsigned long n) if ( n <= 1) //the base case return 1; else return n * factorial (n - 1); 34

Function overloading Function Overloading Functions with same name and different parameters Should perform similar tasks I.e., function to square ints and function to square floats int square( int x) return x * x; float square(float x) return x * x; A call-time c++ complier selects the proper function by examining the number, type and order of the parameters 35