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

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

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

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

Introduction to Programming

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.

Computer Science & Engineering 150A Problem Solving Using Computers

Lab Instructor : Jean Lai

A SHORT COURSE ON C++

Programming Fundamentals. With C++ Variable Declaration, Evaluation and Assignment 1

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

C++ Programming Lecture 11 Functions Part I

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

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

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

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

Top-Down Design with Functions and Classes

Programming Language. Functions. Eng. Anis Nazer First Semester

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

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

Chapter 7 - Notes User-Defined Functions II

Engineering Problem Solving with C++, Etter/Ingber

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

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 (!

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

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Chapter 4: Subprograms Functions for Problem Solving. Mr. Dave Clausen La Cañada High School

M.CS201 Programming language

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

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.

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

Functions that Return a Value. Approximate completion time Pre-lab Reading Assignment 20 min. 92

Summary of basic C++-commands

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.7. User Defined Functions II

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Review. Modules. CS 151 Review #6. Sample Program 6.1a:

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

A First Program - Greeting.cpp

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

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

True or False (12 Points)

Name SECTION: 12:45 2:20. True or False (12 Points)

TEMPLATE IN C++ Function Templates

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

C++ Functions. Last Week. Areas for Discussion. Program Structure. Last Week Introduction to Functions Program Structure and Functions

Chapter 3 - Functions

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

CSCE 110 PROGRAMMING FUNDAMENTALS

Chapter 2. Outline. Simple C++ Programs

Functions. Function Prototypes. Function prototype is needed if the function call comes before the function definition in the program.

CPE 112 Spring 2015 Exam III (100 pts) April 8, True or False (12 Points)

CSCE Practice Midterm. Data Types

Using Free Functions

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

C Programming for Engineers 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++ For Science and Engineering Lecture 15

do { statements } while (condition);

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

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Question 2. [5 points] Given the following symbolic constant definition

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

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

EECS402 Lecture 02. Functions. Function Prototype

C++ basics Getting started with, and Data Types.

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

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

Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Programming in C++ The manager of a company. Lecture Notes 6. Functions (Procedures) 4/24/2018. he he he. Does Does Does

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:

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

Object Oriented Design

Objectives. In this chapter, you will:

Unit 7. Functions. Need of User Defined Functions

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

Constructor - example

Name Section: M/W or T/TH. True or False (14 Points)

WARM UP LESSONS BARE BASICS

I/O Streams and Standard I/O Devices (cont d.)

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

Computing and Statistical Data Analysis Lecture 3

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

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

LOGO BASIC ELEMENTS OF A COMPUTER PROGRAM

Understanding main() function Input/Output Streams

Functions and Recursion

What we will learn about this week: Declaring and referencing arrays. arrays as function arguments. Arrays

1. In C++, reserved words are the same as predefined identifiers. a. True

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

CMPE110 - EXPERIMENT 1 * MICROSOFT VISUAL STUDIO AND C++ PROGRAMMING

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

Fast Introduction to Object Oriented Programming and C++

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

C++ Programming for Non-C Programmers. Supplement

Chapter 1 INTRODUCTION

Why VC++ instead of Dev C++?

Chapter 3. Numeric Types, Expressions, and Output

Transcription:

Function Topic 4

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

Pre-defined and User-defined Pre-defined Function Is a function that is already defined in one of the many C libraries. It is included in the program through the preprocessor directive statement #include< > and used in the program to perform a specific task. Ex: #include<iostream> Defines printf & scanf functions User-defined Function Is a function that is created by the user. It is defined before the main program through a function prototype and called upon in the main program to perform a specific task.

Pre-defined Arithmetic Are functions that perform arithmetic operations. They are usually located in the cmath libraries. (see page 109). Examples: abs(x) is a function that returns the absolute value of its integer argument. sqrt(x) is a function that returns the square root of x.

Pre-defined Function call in an Assignment Statement Syntax Y = function name(argument); Example Y = sqrt(x); function call function sqrt x square root computation y

Pre-defined Examples x = -5 y = abs(x) y = 5 x = 90 y = abs(x) + 2 y = 92 x = 10 y = sqrt(x + 6) y = 4 x = 2.25 y = sqrt(x) y = 1.25

Types of 1. Program sends data to the function and receives data from the function. Ex. y=sqrt(x); x sqrt y 2. Program sends data to the function and doesn t receive data from the function. Ex. cout << Hi ; Hi cout

Types of (Continue) 3. Program doesn t sends data to the function and receives data from the function. Ex. Number = Get_Number(); Get_Number Number 4. Program doesn t sends data to the function and doesn t receive data from the function. Ex. Display_Comment(); Display_Comment

Top-Down Design (Continue) Structured Chart Original Problem Subproblem 1 Subproblem 2 Subproblem 3 Detailed Subproblem 2.1 Detailed Subproblem 2.2 11

Advantages of Writing 1. Decreases the main program s length and reduces the chance to make errors. 2. Makes it easier to define programming tasks between programmers. Each programmer can be responsible for a particular set of functions. 3. Allows procedural abstraction; a programming technique in which a main function consists of a sequence of function calls and each function is implemented separately. This helps to focus on one function at a time instead of writing the complete program all at once. 4. Allows code reuse of function programs.

Code Reuse Reusing program fragments that have already been written and tested whenever possible. It is a way to help in writing error free code.

User-defined Function Prototype A way to declare a function. This tells the compiler: The name of the function The data type of received data(if there is). The type & name of sent data (if there is). Also called the parameters of the function. Syntax ftype fname (); Example defines a function called drawcircle with not sent nor received data (when the program doesn t send to the function and doesn t receive from the function, the function is called a void function) void drawcircle();

User-defined Function Call A function call transfers control from the main program to the function or subprogram. Syntax fname (); Example Drawcircle(); calls function drawcircle and causes it to begin execution

User-defined Function Definition Defines the function operation by writing the code for the function in a similar way to writing the code for the main program. Syntax Ftype fname(void) { local declaration executable statements } Example void drawcircle(void) { cout << *** <<endl; cout << * * <<endl; cout << *** endl; } does not contain the return statement because this function will not send any data to the program main function (i.e. a function should contain the return statement only if it is going to send data to the program)

User-defined Main Program void drawcircle ); int main() { drawcircle(); void drawcircle () { } } Function Prototype Function Call Function Definition

User-defined Main Program void drawcircle (); void drawcircle () { int main() { drawcircle(); } } Function Prototype Function Definition Function Call

User-defined Order of Execution transfer of control back to program transfer of control back to program void function1 (); void function2 (); int main() { function1(); function2(); } void function1 (); { } void function2 (); { } transfer of control to function1 transfer of control to function2

Example - Drawing a Stick Figure * * * * * / \ / \ / \ / \ / \ / \ Draw a Figure Draw a Circle Draw a Triangle Draw Intersecting Lines Draw Intersecting Lines Draw a Base

Example - Drawing a Stick Figure /* draws a stick figure */ #include <iostream> using namespace std; void draw_circle(); /* Function prototype */ void draw_intersect(); /* Function prototype */ void draw_base(); /* Function prototype */ void draw_triangle(); /* Function prototype */ int main(void) { draw_circle(); /* function call */ draw_triangle(); /* function call */ draw_intersect(); /* function call */ return(0); } void draw_circle() /* Function definition */ { cout << " * << endl; cout << "* * << endl; cout << " * * <<endl;} (continued)

Example - Drawing a Stick Figure - Continue /* draws a stick figure - continue*/ void draw_intersect() /* Function definition */ { cout << " /\\ << endl; cout << " / \\ << endl;; cout << "/ \\ << endl; } void draw_base() /* Function definition */ { cout << "------ << endl; } void draw_triangle() /* Function definition */ { draw_intersect(); draw_base(); }

Using 1. Declare a function before the main program. 2. Call the function inside the main program. 3. Define a function after the main program.

Review of Syntax Function Prototype & definition ftype fname (data type name,...); an identifier that represents a corresponding actual argument in a function definition. Ex. int square(int x) Formal Parameter List Function Call fname (data type name,...); Actual Argument List An expression used inside the parentheses of a function call Ex. square(x)

Rules for Argument List 1. The number of actual arguments used in a function call must be the same as the number of the formal parameters listed in the function prototype and definition. 2. The Order of the arguments in the lists determines correspondence and must be the same in arguments and parameters. The first actual argument corresponds to the first formal parameter, the second actual argument corresponds to the second formal parameter and so on. 3. The data types of the actual argument and the formal parameter must match.

Example Prototype& definition: double squared (int x, double y) What is returned from the function (i.e. result) What is sent to the function Call: y = squared (x,y) What is returned from the function (i.e. result) What is sent to the function

Types of 1. Program sends data to the function and receives data from the function. Prototype & definition: return_type function_name (parameter list) Call: variable_name = function_name (argument list) 2. Program sends data to the function and doesn t receive data from the function. Prototype & definition: void function_name (parameter list) Call: function_name (argument list)

Types of (Continue) 3. Program doesn t sends data to the function and receives data from the function. Prototype & definition: return_type function_name (void) Call: variable_name = function_name () 4. Program doesn t sends data to the function and doesn t receive data from the function. Prototype & definition: void function_name (void) Call: function_name ()

Examples of Function Prototype & definition float squared (int number) Returns back a float type to the main program An integer type called number is sent to the function squared Void print_report (int report_number) Returns nothing to the main program An integer type called report_number is sent to the function print_report

Examples of Function Prototype & definition char get_menu_choice () Returns back a character type to the main program Nothing is sent to the function get_menu_choice Void print_comment () Returns nothing to the main program Nothing is sent to the function print_comment

Program Example 1 /* computes half of the value of x */... float half_of(float k); /* function prototype */ int main() {... y=half_of(x); /* calling function */... } float half_of(float k) /* function definition */ { k = k / 2; return(k); }

Program Example 2 /* computes the cube of num */... int cubed(int x); /* function prototype */ int main() {... y=cubed(num); /* calling function */... } int cubed(int x) /* function definition */ { return(x*x*x); }

Program Example 3 /* displays the largest of two numbers */... int larger(int x,int y); /* function prototype */ int main() {... y=larger(num1,num2); /* calling function */... } int larger(int x,int y) /* function definition */ {... return(larger_num); }

Program Example 4 /* calculates the area and circumferencce of a circle */... float find_area(float r); /* function prototype */ float find_circum(float r); /* function prototype */ int main() {... area = find_area(r); /* calling function */ circum = find_circum(r); /* calling function */... } float find_area(float r) /* function definition */ { return(pi*pow(r,2);} float find_circum(float r) {return(2.0*pi*r)}

Example 1 #include<iostream> #include<cmath.h> using namespace std; double scale(double x, int n); int main() { double num1; int num2; cout << "Enter a real number> ; cin >> num1; cout << Enter an integer> "; cin >> num2; cout << "Result of call to function scale is \n", scale(num1,num2)); return 0; } double scale(double x, int n) /* This function multiplies its first */ { double scale_factor; /* argument by the power of 10 */ scale_factor = pow(10,n); /* specified by its second argumnet */ return(x * scale_factor); }

Example 2 #include<iostream> # include<cmath> using namespace std; void print_comment(); double scale(double x, int n); int main() { double num1, int num2; print_comment(); cout << "Enter a real number> "; cin >> num1; cout << "Enter an integer> "; cin >> num2; cout << "Result of call to function scale is \n",scale(num1,num2)); return 0; } void print_comment(void) { cout << "The program will... \n";} double scale(double x, int n) {... }

Example 3 include<iostream> # include<cmath> using namespace std; double scale(double x, int n); void display(double result); int main() { double num1, result; int num2; cout << "Enter a real number> "; cin >> num1; cout << "Enter an integer> "; cin >> num2; result = scale(num1,num2); display(result); return 0;} double scale(double x, int n) {... } void display(double result) { printf("result of call to function scale is %.2f\n", result);}

Example 4 #include<iostream> # include<cmath> using namespace std; double get_num1(); int get_num2(); double scale(double x, int n); int main(void) { double num1, int num2; num1 = get_num1(); num2 = get_num2(); cout << "Result of call to function scale is\n",scale(num1,num2)); return 0;} double get_num1(void) { double number1; cout << "Enter a real number> "; cin >> number1; return(number1);} int get_num2(void) {... return(number2); } double scale(double x, int n) {... }

Global and Local Declarations Local Declaration When the declaration is placed at the start of the main function or sub-functions. Global Declaration When the declaration is placed immediately after the pre-processor directives. IMPORTANT: in the C programming language local variables have precedence over global variables.

Global and Local Declarations #include <iostream> /* global declarations */ void function1(); int main() { /* local declarations */ } void function1() { /* local declarations */ }

Example 1 #include<iostream> using namespace std; void function1(); int main() { int z; /* local declaration */ z = 5; function1(); cout << The value of z inside function main is << z); return 0;} void function1() { int z; /* local declaration */ cout << The value of z inside functin1 is << z);} Unknown The value of z inside function1 is -427365653 The value of z inside the function main is 5 Press any key to continue

Example 2 #include<iostream> using namespace std; int z; /* global declaration */ void function1(); int main() { int z; /* local declaration */ Gives the same result as the z = 5; function1(); previous program since local declarations cout << The value of z inside function main is << z ; have precedence return 0;} over global declarations void function1() { int z; /* local declaration */ cout << The value of z inside functin1 is << z);} The value of z inside function1 is -427365653 The value of z inside the function main is 5 Press any key to continue

Example 3 #include<iostram> using namespace std; int z; /* global declaration */ void function1(); int main() { int z; /* local declaration */ z = 5; function1(); cout << The value of z inside function main is \n <<z); return 0;} void function1() { int z; /* local declaration */ cout << The value of z inside functin1 is \n << z);} The value of z inside function1 is 5 The value of z inside the function main is 5 Press any key to continue

Example 4 #include<iostream> using namespace std; int z = 2; /* global declaration */ void function1(); int main() { int z = 5; /* local declaration */ function1(); cout << The value of z inside function main is \n << z); return 0;} void function1() { int z; /* local declaration */ cout << The value of z inside functin1 is \n << z);} The value of z inside function1 is 2 The value of z inside the function main is 5 Press any key to continue

Example 5 #include<iostream> using namespace std; int z; /* global declaration */ void function1(); void function2(); int main() { z = 5; function1(); cout << The value of z inside function main is \n <<z); function2(); cout << The value of z inside function main is\n << z); return 0;} void function1() { int z; /* local declaration */ z = 10; cout << The value of z inside functin1 is \n << z);} void function2() {cout << The value of z inside functin2 is \n << z);} The value of z inside function1 is 10 The value of z inside the function main is 5 The value of z inside function2 is 5 The value of z inside the function main is 5 Press any key to continue

Example 6 #include<iostream> using namespace std; int z; /* global declaration */ void function1(); void function2(); int main() { z = 15; function1(); cout << The value of z inside function main is \n << z); function2(); cout << The value of z inside function main is \n << z); return 0;} void function1() { int z; /* local declaration */ z = 11; cout << The value of z inside functin1 is \n << z);} void function2() { int z; /* local declaration */ cout << The value of z inside functin2 is \n << z);} The value of z inside function1 is 11 The value of z inside the function main is 15 The value of z inside function2 is -757457774 The value of z inside the function main is 15 Press any key to continue Unknown