21
Functions/Methods Methods in Theory Couple of definitions o a procedure to complete a SPECIALIZED task, no matter how small or large o a PACKAGE of code Methods can be run any numbers of time you want Will do the SAME THING each time it is run, no exception EVERY PROGRAM MUST START WITH A MAIN( ) (which is a function) o MAIN( ) is considered the starting function Methods are SEQUENTIAL – starts from top , ends a bottom o so declare variables at beginning of function/program so you can use later o compiler will READ top to bottom Lupoli’s Routine Lupoli’s Routine using subroutines 1

Functionsfaculty.cse.tamu.edu/slupoli/notes/C++/FunctionsINotes.docx · Web viewFunctions/Methods Methods in Theory Couple of definitions a procedure to complete a SPECIALIZED task,

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Functionsfaculty.cse.tamu.edu/slupoli/notes/C++/FunctionsINotes.docx · Web viewFunctions/Methods Methods in Theory Couple of definitions a procedure to complete a SPECIALIZED task,

Functions/MethodsMethods in Theory Couple of definitions

o a procedure to complete a SPECIALIZED task, no matter how small or largeo a PACKAGE of code

Methods can be run any numbers of time you want Will do the SAME THING each time it is run, no exception EVERY PROGRAM MUST START WITH A MAIN( ) (which is a function)

o MAIN( ) is considered the starting function Methods are SEQUENTIAL – starts from top, ends a bottom

o so declare variables at beginning of function/program so you can use latero compiler will READ top to bottom

Lupoli’s Routine Lupoli’s Routine using subroutineswake up

shower, dress

drive to work

go to frigfind foodgrab a cokefind a seateat food

teach

go to frigfind foodgrab a cokefind a seateat food

drive home

wake up

wake up

shower, dress

drive to work

EATING

teach

EATING

drive home

wake up

EATINGgo to frigfind foodgrab a cokefind a seateat food

1

Page 2: Functionsfaculty.cse.tamu.edu/slupoli/notes/C++/FunctionsINotes.docx · Web viewFunctions/Methods Methods in Theory Couple of definitions a procedure to complete a SPECIALIZED task,

The file Setup - Version 1 depending on the programming language this may be different the Main() is the starting point for many languages like C, C++. Java, etc. What is a PROTOTYPE

o definition of a functiono think of it as a listing in a Table of Contentso MANDATORY, except for the main()o exact copy of the function header (described below), with an “;” at end

MAIN DOES NOT NEED A PROTOTYPE o Where does the PROTOTYPE goo remember the 6 sections of a programo ABOVE THE MAIN!!! o Order of the prototypes does not matter

File SetupSetup order for functions

2

Page 3: Functionsfaculty.cse.tamu.edu/slupoli/notes/C++/FunctionsINotes.docx · Web viewFunctions/Methods Methods in Theory Couple of definitions a procedure to complete a SPECIALIZED task,

1. // Name and description2. Includes3. Prototypes4. Main5. Functions

The file Setup – Version 2

depending on the programming language this may be different

the Main() is the starting point for many languages like C, C++. Java, etc.

What is a PROTOTYPEo definition of a functiono think of it as a listing in a

Table of Contentso MANDATORY, except for

the main()o exact copy of the function header (described below), with an “;” at end

MAIN DOES NOT NEED A PROTOTYPE o Where does the PROTOTYPE goo remember the 6 sections of a programo ABOVE THE MAIN!!! o Order of the prototypes does not matter

File SetupSetup order for functions

Lupoli.cpp// intro// other stuff

// includes

// PROTOTYPESvoid printmenu();void temp_swap(int a, int b);

int main(..){ … printmenu(); // stuff here // function calls temp_swap(Ravens, Deadskins); temp_swap(Ravens, Pittsburg);}

// Methodsvoid temp_swap(int a, int b){ …. ….}void printmenu(){…}

3

Page 4: Functionsfaculty.cse.tamu.edu/slupoli/notes/C++/FunctionsINotes.docx · Web viewFunctions/Methods Methods in Theory Couple of definitions a procedure to complete a SPECIALIZED task,

1. Names and Description2. Includes3. Functions4. Main

Lupoli.cpp// intro// other stuff

// includes

// Methodsvoid temp_swap(int a, int b){ …. ….}void printmenu(){…}

int main(..){ … printmenu(); // stuff here // function calls temp_swap(Ravens, Deadskins); temp_swap(Ravens, Pittsburg);}

4

Page 5: Functionsfaculty.cse.tamu.edu/slupoli/notes/C++/FunctionsINotes.docx · Web viewFunctions/Methods Methods in Theory Couple of definitions a procedure to complete a SPECIALIZED task,

Different types of functions When referring to functions, it is sometimes useful to differentiate them into

types that depend upon what they return. o functions - return values (lists, int, doubles, floats, etc…)o predicate functions - return booleans (True/False)o procedures - return nothing, or None in python

Creating the simple VOID function (procedure) void means the function/method does not return any values to YOU AS THE

PROGRAMMER BUT, the function does some work!!

void printmenu( ) first line of ANY function is called a “function header”{

cout << “Menu Choices” << endl;cout << “Z – zip code” << endl;cout << “M – middle initial” << endl;cout << “T – Temporary Swap” << endl;cout << “P – Permanent Swap” << endl;

}

return type function name – case sensitive, make sure EXACT name ( )’s – parameter list, (get into later), ALWAYS needed NOTICE – no “;” like prototype beginning/opening code bracket ending/closing code bracket

5

Page 6: Functionsfaculty.cse.tamu.edu/slupoli/notes/C++/FunctionsINotes.docx · Web viewFunctions/Methods Methods in Theory Couple of definitions a procedure to complete a SPECIALIZED task,

What can you put into a function?? Anything you have already learned!!

o Loopso Arrayso If-elseo Variableso Etc…

6

Page 7: Functionsfaculty.cse.tamu.edu/slupoli/notes/C++/FunctionsINotes.docx · Web viewFunctions/Methods Methods in Theory Couple of definitions a procedure to complete a SPECIALIZED task,

See how a VOID function works (Mechanics)

int main(){… …printmenu( ); // calling// NEXT LINE }

void printmenu( ){

}

Also note:

The prototype is an EXACT copy of the function header with a “;” at the end.If the function header changes, SO MUST YOUR PROTOTYPE

7

//includes

void printmenu();

int main(){………printmenu();………}void printmenu(){……}

Page 8: Functionsfaculty.cse.tamu.edu/slupoli/notes/C++/FunctionsINotes.docx · Web viewFunctions/Methods Methods in Theory Couple of definitions a procedure to complete a SPECIALIZED task,

Calling other Functions, determining order when calling another function name be sure to be CASE SENSITIVE with the

name of the function calls are sequential!!!

o ORDER in when they are called matters!! functions can be called from:

o the main()o or OTHER functions!!o BUT ALWAYS START AT THE MAIN!!!!

Function Calling Exercise #1void getFunction1(){

cout << "A" << endl;getFunction3();

}

void getFunction2(){

cout << "B" << endl;}

void getFunction3(){

cout << "C" << endl;}

void getFunction4(){

cout << "D" << endl;getFunction3();

}

void getFunction5(){

cout << "E" << endl;}

void getFunction6(){

cout << "F" << endl;}

void main(){

getFunction1();getFunction2();getFunction4();

}1. Which function in this ENTIRE program is called 1st?2. Which function in this ENTIRE program is called 2nd?3. What will be displayed from the code above

8

Page 9: Functionsfaculty.cse.tamu.edu/slupoli/notes/C++/FunctionsINotes.docx · Web viewFunctions/Methods Methods in Theory Couple of definitions a procedure to complete a SPECIALIZED task,

Function Calling Exercise #2#include <iostream>using namespace std;

void getFunction1(){

cout << "A" << endl;getFunction3();

}

void getFunction2(){

cout << "B" << endl;}

void getFunction3(){

cout << "C" << endl;}

void getFunction4(){

cout << "D" << endl;getFunction3();

}

void getFunction5(){

cout << "E" << endl;}

void getFunction6(){

cout << "F" << endl;}

int main(){

getFunction3();getFunction1();getFunction5();getFunction6();getFunction2();

return 0;}# what will be displayed from the code above

9

Page 10: Functionsfaculty.cse.tamu.edu/slupoli/notes/C++/FunctionsINotes.docx · Web viewFunctions/Methods Methods in Theory Couple of definitions a procedure to complete a SPECIALIZED task,

Creating a INT function returns a value (fun.)

Int means the function/method will return a value to YOU AS THE PROGRAMMER (int)

The function does some work!!

int zipcode( ){

int zip = 21118; // put in YOUR zip codereturn zip;

}

See how an INT function works** Run program int zipcode( )

{

int getZip = zipcode( ); return “21118”;

}

you see: 21118 NOT zipcode( );

zipcode( ) acts like a VALUE , since it returns a INT VALUE

THIS HAPPENS FOR ANY FUNCTION THAT RETURNS A VALUEfloatdoublechar…

Identify Method Exercise #1bool hasValue(string x){ // x is the input value

if(x == null){ return false; }else{ return true; }

1. What type of data is this function returning?2. Are there any variables declared INSIDE the

method? (be careful)3. What possible values could be returned from this

function?

10

int zipcode();void main(){………int getZip = zipcode();………}int zipcode(){……return 21118;}

Page 11: Functionsfaculty.cse.tamu.edu/slupoli/notes/C++/FunctionsINotes.docx · Web viewFunctions/Methods Methods in Theory Couple of definitions a procedure to complete a SPECIALIZED task,

} bool answer = hasValue(“Lupoli”);

Scope of variables (Jurisdiction)Global variables

“live” and can be accessed thru-out the ENTIRE program is NOT declared WITHIN a function dead giveaway

Local live and die in function it was created can only be accessed by that function is declared WITHIN a function dead giveaway

Scope of variable exercisesExercise 1 Exercise 2 Exercise 3

void main(){…int x = 0;…printmenu();………}void printmenu(){…cout << x; // will x display??…}

int x = 0;

void main(){……printmenu();………}void printmenu(){…cout << x; // will x display??…}

void main(){…int x = 0;…printmenu();………}void printmenu(){…int x = 30;cout << x; // will x display??…}

What will X display in EACH example? (options are “error”, 0, 30) for each

11

Page 12: Functionsfaculty.cse.tamu.edu/slupoli/notes/C++/FunctionsINotes.docx · Web viewFunctions/Methods Methods in Theory Couple of definitions a procedure to complete a SPECIALIZED task,

Why use Global constants? ONE spot to change values if the variable is use throughout the program constant will

o stop any changes to the variable while coding AND runningo remember, your code for NOW may be short

when it goes longer, you might forget about it

Global Constants and Returning an Array#include <iostream>using namespace std;

const bool DEBUG = false;const int SIZE = 10;

int * resetArray();void displayArray(int * x);

int main(){

if(DEBUG) // just a DEBUG statement{ cout << "DEBUG ->Started the main()" << endl; }

int * values;

values = resetArray();

if(DEBUG) // just a DEBUG statement{ cout << "DEBUG ->about to display the arrays AFTER reset" << endl; }

displayArray(values);

return 0;}

// Description: Will return an integer array of SIZE// Input: none// Output: an integer array full of -1sint * resetArray(){

int * array = new int[SIZE];

// clear garbagefor(int i = 0; i < SIZE; i++) { array[i] = -1; }

return array;}

// Description: Will display an integer array// Input: none// Output: none (returned)void displayArray(int * x){

for(int i = 0; i < SIZE; i++) { cout << x[i] << endl; }}

12

Page 13: Functionsfaculty.cse.tamu.edu/slupoli/notes/C++/FunctionsINotes.docx · Web viewFunctions/Methods Methods in Theory Couple of definitions a procedure to complete a SPECIALIZED task,

Returning if you use the "return" reserved word, it can return ONLY ONE value!!!

How many POSSIBLE values can this return?How many values WILL BE returned?

How to store values that are returned

13

bool hasValue(string x){ # x is the input value

if(x == NULL) return false;else return true;

}

Page 14: Functionsfaculty.cse.tamu.edu/slupoli/notes/C++/FunctionsINotes.docx · Web viewFunctions/Methods Methods in Theory Couple of definitions a procedure to complete a SPECIALIZED task,

Real Life Example#include <iostream>#include <string>using namespace std;

// global variableconst int SIZE = 10;

// prototypefloat average(int grade1, int grade2);

int main(){

// programmer enters values in callfloat result1 = average(78, 80);cout << "James' average is " << result1 << endl;

// user enters values in callint x, y;cout << "Enter Cheater's 2 grades: " << endl;cin >> x;cin >> y;float result2 = average(x, y);cout << "Cheater's average is " << result2 << endl;

// cout is the MAJORcout << "Enter Dylan's 2 grades: " << endl;cin >> x;cin >> y;//float result2 = average(x, y);cout << "Dylan's average is " << average(x, y) << endl;

return 0;}

// description:// inputs:// outputs:float average(int grade1, int grade2){

float finalAverage = (grade1+grade2)/2.0;return finalAverage;

}

14