function

March 20, 2018 | Author: Anonymous | Category: N/A
Share Embed


Short Description

Download function...

Description

Programming

Introduction to Functions

COMP102 Prog Fundamentals I: Introduction to Functions /Slide 2

Introduction to Functions 

A complex problem is often easier to solve by dividing it into several smaller parts, each of which can be solved by itself.

This is called structured programming.  These parts are sometimes made into functions in C++.  main() then uses these functions to solve the original problem. 

COMP102 Prog Fundamentals I: Introduction to Functions /Slide 3

Advantages of Functions Functions separate the concept (what is done) from the implementation (how it is done).  Functions make programs easier to understand.  Functions can be called several times in the same program, allowing the code to be reused. 

COMP102 Prog Fundamentals I: Introduction to Functions /Slide 4

C++ Functions 

C++ allows the use of both internal (userdefined) and external functions.



External functions (e.g., abs, ceil, rand, sqrt, etc.) are usually grouped into specialized libraries (e.g., iostream, stdlib, math, etc.)

COMP102 Prog Fundamentals I: Introduction to Functions /Slide 5

User-Defined Functions 

C++ programs usually have the following form: // // // //

include statements function prototypes main() function function definitions

COMP102 Prog Fundamentals I: Introduction to Functions /Slide 6

Function Input and Output

COMP102 Prog Fundamentals I: Introduction to Functions /Slide 7

Function Definition A function definition has the following syntax: (){ } For example: Definition of a function that computes the absolute value of an integer:

int absolute(int x){ if (x >= 0) return x; else return -x; }

COMP102 Prog Fundamentals I: Introduction to Functions /Slide 8

Function Call 

A function call has the following syntax: ()

Example: int distance = absolute(-5);  The result of a function call is a value of type

COMP102 Prog Fundamentals I: Introduction to Functions /Slide 9

Arguments/Parameters 

one-to-one correspondence between the arguments in a function call and the parameters in the function definition.

int argument1; double argument2; // function call (in another function, such as main) result = thefunctionname(argument1, argument2); // function definition int thefunctionname(int parameter1, double parameter2){ // Now the function can use the two parameters // parameter1 = argument 1, parameter2 = argument2

COMP102 Prog Fundamentals I: Introduction to Functions /Slide 10

Absolute Value #include using namespace std; int absolute (int);// function prototype for absolute() int main(){ int num, answer; cout > num; while (num!=0){ answer = absolute(num); cout num; while (num!=0){ answer = absolute(num); cout
View more...

Comments

Copyright © 2017 DOCUMEN Inc.