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

of 35 /35
CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert

Embed Size (px)

Transcript of CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.

  • CPSC 230Computers and Programming ISpring 2003Dr. Lynn Lambert

  • This course will teach you:C++Object-oriented conceptsProgrammingSome stabs at problem solving

  • How computers workComputers understand machine language onlyEach computer has its own languageAll computer languages are in binary (1s and 0s)No computer understands English, Powerpoint, or C++

  • A computer program: Add X to Y and store in ZIn machine language:01040100 (already simplified to decimal)01050160 0404050602060180

    HUH!?

  • AssemblyEach 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!?

  • C++z=x+y;

    Much better!

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

  • Designing a ProgramDecide the problem to solve.Design the solution. Translate design to C++Type the C++ program (source code) using an editor (emacs): program.ccCompile (g++). Translates C++ into machine language (object, machine, executable code)Link (g++). Creates executable. Can be done with step 5 or separately.Run the program (after 1-6).

  • At each step:ThinkDo DebugTest

  • Write a program to calculate the volume of a sphereProblem well-definedDesign solution:Read radiusCalculate volume (V = 4/3(pi)r3Print answer

  • C++ Program#include // 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

  • const float mypi = 3.14159; // const values cannot be // changed. M_PI also defined in cmathcout
  • 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

  • Functions(modified from Deitel & Deitel web page)

  • Why functions?divide and conquerrepeatable. reuse reliable codeencapsulated

  • Program Components in C++Modules: functions and classesPrograms use new and prepackaged modulesNew: programmer-defined functions, classesPrepackaged: from the standard library Functions invoked by function callFunction name and information (arguments/parameters) it needsFunction definitionsOnly written once

  • Program Components in C++Boss to worker analogyA 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

  • Library FunctionsFunctions called by writingfunctionName(argument1, argument2, );Perform common mathematical calculationsInclude the header file Call the appropriate function

  • Library FunctionsExamplevolume = 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 textAll functions in math library return a double

  • Parameters/ArgumentsFunction arguments can beConstantssqrt( 4 );Variablessqrt( x );Expressionssqrt( sqrt( x ) ) ;sqrt( 3 - 6x );

  • Other librariesPerform string operations, include Perform character manipulations, include file handling, standard constants and routines Lots of others

  • Writing your own functionsTo call a function, you need:Function call invokes function executionTo write your own function, you need:Function call(e.g., pow, sqrt). We know this.Function prototype (shown in function libraries, like -- contains interface information)Function definition contains the C++ that defines how that function will be executed (e.g., main). Really, we know this.

  • function call, prototypeCalling/invoking a functionsquare(x);Parentheses an operator used to call functionPass argument xFunction gets its own copy of argumentsAfter finished, passes back resultFunction prototypeTells compiler argument(s) type and return type of functionint square( int );Function takes an int and returns an intExplained in more detail later

  • Function definitionFormat for function definitionreturn-value-type function-name( parameter-list ) { declarations and statements }Parameter listComma separated list of argumentsData type needed for each argumentIf no arguments, use void or leave blankReturn-value-typeData type of result returned (use void if nothing returned)

  • function definitionExample functionint square( int y ){ return y * y;}return keywordReturns data, and control goes to functions callerIf no data to return, use return;Function ends when reaches right braceControl goes to callerFunctions cannot be defined inside other functions

  • // Fig. 3.3: fig03_03.cpp. But modified from code in book// Creating and using a programmer-defined function.#include #include 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 number; // next line is function call cout
  • 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 PrototypesFunction prototype containsFunction nameParameters (number and data type)Return type (void if returns nothing)Only needed if definition after function callsemicolon (unlike header in function definition)Prototype must match function definitionFunction prototypeint sqr(int); Function Definitionint sqr(int y){ }

  • Functions with empty parameter listsEmpty parameter listsvoid or leave parameter list emptyIndicates function takes no argumentsFunction print takes no arguments and returns no valuevoid print();void print( void );

  • print function examplePrototypevoid printinfo(void);Function callint main (){ ... printinfo(); }

  • print function example cont'dfunction definitionvoid printinfo(){ cout
  • Function overloadingFunction overloadingFunctions with same name and different parametersShould 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

  • Function overloading cont'dOverloaded functions distinguished by signatureBased on position, number, and type of parameters (order of parameters matters)Name manglingEncodes function identifier with parametersType-safe linkageEnsures proper overloaded function called

  • // Fig. 3.25: fig03_25.cpp2 // Using overloaded functions.3 #include 4 5 using std::cout;6 using std::endl;7 8 // function square for int values 9 int square( int x ) 10 { 11 cout
  • 24 int main()25 {26 int intResult = square( 7 ); // int version called27 double doubleResult;28 doubleResult = square( 7.5 ); // calls double version29 cout
  • Write a programWrite a program that uses functionsTalk to your neighborsUse the bookUse your notes