Download - CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

Transcript
Page 1: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

CPSC 230Computers and Programming I

Spring 2003Dr. Lynn Lambert

Page 2: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

This course will teach you: C++ Object-oriented concepts Programming Some stabs at problem solving

Page 3: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

How computers work Computers understand machine

language only Each computer has its own

language All computer languages are in

binary (1s and 0s) No computer understands English,

Powerpoint, or C++

Page 4: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

A computer program: Add X to Y and store in Z

In machine language: 01040100 (already simplified to decimal)

01050160 04040506 02060180

HUH!?

Page 5: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

Assembly

Each machine instruction has matching, more English-like assembler:

Load X (was: 01040100) Load Y (was: 01050160) Add X Y Z (was: 04040506) Store Z (was: 02060180)Better, but … all this for one addition!?

Page 6: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

C++

z=x+y;

Much better!

BUT, no machines understand source code. Only machine code.

Page 7: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

Designing a Program1. Decide the problem to solve.

2. Design the solution. 3. Translate design to C++4. Type the C++ program (source code) using

an editor (emacs): program.cc5. Compile (g++). Translates C++ into

machine language (object, machine, executable code)

6. Link (g++). Creates executable. Can be done with step 5 or separately.

7. Run the program (after 1-6).

Page 8: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

At each step:

1. Think

2. Do

3. Debug

4. Test

Page 9: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

Write a program to calculate the volume of a sphere Problem well-defined Design solution:

Read radius Calculate volume (V = 4/3(pi)r3

Print answer

Page 10: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

C++ Program#include <iostream> // allows reading in and out

using namespace std; // standard namespace

int main() { float radius; // radius of a sphere float volume; // volume of sphere Float is decimal.// other types are int, char, bool, double

Page 11: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

const float mypi = 3.14159; // const values cannot be

// changed. M_PI also defined in cmathcout << “This program calculates the volume “ << “of a sphere given its radius.” << endl;// lots of other ways to do this cout. cout << “Enter the radius> “;cin >> radius;// volume = 4/3 r3

try 1: volume = 4/3 M_PI r …? 3?try 2: volume = 4 / 3 * M_PI * r * r;try 2.b: volume = 4/3 * M_PI * pow(r, 3); // in cmathcout << "The volume of a sphere with radius ";cout << radius << " is " << volume << endl;return EXIT_SUCCESS; // in <cstdlib>}

Page 12: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

great. except it doesn't work.

int + int is int float + float is float

int - int is int float - float is float

int * int is int float * float is float

int / int is int float / float is float

Page 13: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

Functions

(modified from Deitel & Deitel web page)

Page 14: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

Why functions? divide and conquer repeatable. reuse reliable code encapsulated

Page 15: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

Program Components in C++

Modules: functions and classes Programs use new and “prepackaged”

modules New: programmer-defined functions, classes Prepackaged: from the standard library

Functions invoked by function call Function name and information

(arguments/parameters) it needs Function definitions

Only written once

Page 16: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

Program Components in C++

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

Page 17: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

Library Functions Functions called by writing

functionName(argument1, argument2, …);

Perform common mathematical calculations Include the header file <cmath> Call the appropriate function

Page 18: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

Library Functions Examplevolume = 4.0 / 3.0 * M_PI * pow(r, 3); pow (exponentiation) function returns

baseexponent (pow(2,3) would return 8) Other math functions listed on p. 173

of text All functions in math library return a double

Page 19: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

Parameters/Arguments Function arguments can be

Constants sqrt( 4 );

Variables sqrt( x );

Expressions sqrt( sqrt( x ) ) ; sqrt( 3 - 6x );

Page 20: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

Other libraries Perform string operations, include

<string> Perform character manipulations,

include <cctype> file handling, <fstream> standard constants and routines

<cstdlib> Lots of others

Page 21: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

Writing your own functions

To call a function, you need: Function call – invokes function execution

To write your own function, you need: Function call (e.g., pow, sqrt). We know

this. Function prototype (shown in function libraries,

like <cmath> -- contains interface information) Function definition– contains the C++ that

defines how that function will be executed (e.g., main). Really, we know this.

Page 22: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

function call, prototype 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 Function prototype

Tells compiler argument(s) type and return type of function

int square( int ); Function takes an int and returns an int

Explained in more detail later

Page 23: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

Function definition Format for function definition

return-value-type function-name( parameter-list ){ declarations 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)

Page 24: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

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

Page 25: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

// Fig. 3.3: fig03_03.cpp. But modified from code in book// Creating and using a programmer-defined function.#include <iostream>#include <cstdlib> using namespace std; // modified from code in book int square( int ); // function prototype int main() { int number; // Ask user for number square then square that number cout << “This program calculates the square of an integer.”

<< endl; cout << “Enter a number> “; cin >> number; // next line is function call cout << number << “ squared is “ << square( x ) << endl; return EXIT_SUCCESS; // indicates successful termination} // end main

Parentheses () cause function to be called. When done, it returns the result.

Function prototype: specifies data types of arguments and return values. square expects and int, and returns an int.

Page 26: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

function header: return typefunction name, parameter list.

// this continues program begun on previous slide// 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

OR

int square(int nbr){ int answer; answer = nbr * nbr; return answer;}

function body: C++ statements in between {}s.

Page 27: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

Function Prototypes Function prototype contains

Function name Parameters (number and data type) Return type (void if returns nothing) Only needed if definition after function call semicolon (unlike header in function definition)

Prototype must match function definition Function prototype

int sqr(int); • Function Definition

int sqr(int y){ …}

Page 28: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

Functions with empty parameter lists Empty parameter lists

void or leave parameter list empty Indicates function takes no arguments Function print takes no arguments

and returns no value void print(); void print( void );

Page 29: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

print function example Prototype

void printinfo(void); Function call

int main (){ ... printinfo(); …}

Page 30: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

print function example cont'd function definition

void printinfo(){ cout << "this program calculates";

cout << " the area of a sphere"; cout << endl;}

Page 31: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

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 floatsint square( int x) {return x * x;}

float square(float x) { return x * x; }

Similar to overloaded +, /, etc. operators

Page 32: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

Function overloading cont'd Overloaded functions distinguished

by signature Based on position, number, and type of

parameters (order of parameters matters)

Name mangling Encodes function identifier with parameters

Type-safe linkage Ensures proper overloaded function called

Page 33: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

// Fig. 3.25: fig03_25.cpp2 // Using overloaded functions.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 // function square for int values 9 int square( int x ) 10 { 11 cout << "Called square with int argument: " << x << endl;12 return x * x; 13 14 } // end int version of function square 15 16 // function square for double values 17 double square( double y ) 18 { 19 cout << "Called square with double argument: " << y << endl;20 return y * y; 21 } // end double version of function square 23

Page 34: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

24 int main()25 {26 int intResult = square( 7 ); // int version called27 double doubleResult;28 doubleResult = square( 7.5 ); // calls double version29 cout << "\nThe square of integer 7 is " << intResult30 << "\nThe square of double 7.5 is " 31 << doubleResult << endl; 32 33 return 0; // indicates successful termination34 35 } // end main

Called square with int argument: 7Called square with double argument: 7.5 The square of integer 7 is 49The square of double 7.5 is 56.25

Page 35: CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

Write a program Write a program that uses

functions Talk to your neighbors Use the book Use your notes