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

Slides:



Advertisements
Similar presentations
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Advertisements

Chapter 5 C Functions The best way to develop and maintain a large program is to divide it into several smaller program modules, each of which is more.
Functions Quick Review What is a Function? A module of code that performs a specific job. Examples: Function that determines the maximum of two numbers.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
 2007 Pearson Education, Inc. All rights reserved C Functions.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
 2007 Pearson Education, Inc. All rights reserved C Functions.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
Chapter 6: User-Defined Functions I
C++ Functions CS242 COMPUTER PROGRAMMING T.Banan Al-Hadlaq.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
1 Lecture 3 Part 1 Functions with math and randomness.
Function. Introduction Library function New defined function Random number generator Scope Inline function Function overload Function Function.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Functions in C Programming Dr. Ahmed Telba. If else // if #include using namespace std; int main() { unsigned short dnum ; cout
Functions Modules in C++ are called functions and classes Functions are block of code separated from main() which do a certain task every C++ program must.
Programming in C++ Language ( ) Lecture 5: Functions-Part1 Dr. Lubna Badri.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
1 Chapter 6 - Functions Outline 6.1Introduction 6.2Program Components in C++ 6.6Math Library Functions 6.4Functions 6.5Function Definitions 6.6Function.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6 - Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Functions Outline 5.1Introduction 5.2Program Modules.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
Function ( I ) Ying Wu Electrical & Computer Engineering Northwestern University ECE230 Lectures Series.
KIC/Computer Programming & Problem Solving 1.  Introduction  Program Modules in C  Math Library Functions  Functions  Function Definitions  Function.
 In this chapter you ‘’ll learn: ◦ To construct programs modularly from functions ◦ To use common math library functions ◦ The mechanism for passing.
1 Lecture 14 Functions Functions with Empty Parameter Lists Empty parameter lists  void or leave parameter list empty  Indicates function takes.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
1 Advanced Topics in Functions Lecture Unitary Scope Resolution Operator Unary scope resolution operator ( :: )  Access global variable if.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.15Functions with Empty Parameter Lists 3.16Inline Functions 3.17References.
EC-111 Algorithms & Computing Lecture #6 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME NUST.
 2003 Prentice Hall, Inc. All rights reserved Storage Classes Variables have attributes –Have seen name, type, size, value –Storage class How long.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
Programming Fundamentals Enumerations and Functions.
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Program Components in C++ 3.Math Library Functions 4.Functions 5.Function Definitions.
Dale Roberts CSCI N305 Functions Declarations Department of Computer and Information Science, School of Science, IUPUI.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 2 Functions September.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Chapter 6: User-Defined Functions I
-Neelima Singh PGT(CS) KV Sec-3 Rohini
Dr. Shady Yehia Elmashad
Chapter 1: Introduction to computers and C++ Programming
IS Program Design and Software Tools Introduction to C++ Programming
FUNCTIONS IN C++.
CSC113: Computer Programming (Theory = 03, Lab = 01)
This technique is Called “Divide and Conquer”.
Dr. Shady Yehia Elmashad
Functions.
Functions Najah Alsubaie Kingdom of Saudi Arabia
Chapter 5 - Functions Outline 5.1 Introduction
Dr. Shady Yehia Elmashad
Functions Declarations CSCI 230
Zhen Jiang West Chester University
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
Chapter 6: User-Defined Functions I
Variables have attributes
Functions Imran Rashid CTO at ManiWeber Technologies.
Presentation transcript:

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

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++

A computer program: Add X to Y and store in Z In machine language: (already simplified to decimal) HUH!?

Assembly Each machine instruction has matching, more English-like assembler: Load X (was: ) Load Y (was: ) Add X Y Z (was: ) Store Z (was: ) Better, but … all this for one addition!?

C++ z=x+y; Much better! BUT, no machines understand source code. Only machine code.

Designing a Program 1. 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.cc 5. 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).

At each step: 1.Think 2.Do 3.Debug 4.Test

Write a program to calculate the volume of a sphere Problem well-defined Design solution: Read radius Calculate volume (V = 4/3(pi)r 3 Print 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 = ; // const values cannot be // changed. M_PI also defined in cmath cout << “This program calculates the volume “ << “of a sphere given its radius.” << endl; // lots of other ways to do this cout. cout “; cin >> radius; // volume = 4/3 p r 3 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 cmath cout << "The volume of a sphere with radius "; cout << radius << " is " << volume << endl; return EXIT_SUCCESS; // in }

great. except it doesn't work.

Functions (modified from Deitel & Deitel web page)

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

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

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

Library Functions Functions called by writing functionName(argument1, argument2, …); Perform common mathematical calculations Include the header file Call the appropriate function

Library Functions Example volume = 4.0 / 3.0 * M_PI * pow(r, 3); pow (exponentiation) function returns base exponent (pow(2,3) would return 8) Other math functions listed on p. 173 of text All functions in math library return a double

Parameters/Arguments Function arguments can be Constants sqrt( 4 ); Variables sqrt( x ); Expressions sqrt( sqrt( x ) ) ; sqrt( 3 - 6x );

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

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 -- 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, 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

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)

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

// Fig. 3.3: fig03_03.cpp. But modified from code in book // Creating and using a programmer-defined function. #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 << “This program calculates the square of an integer.” << endl; cout “; 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.

function header: return type function 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.

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) { … }

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 );

print function example Prototype void printinfo(void); Function call int main () {... printinfo(); … }

print function example cont'd function definition void printinfo() { cout << "this program calculates"; cout << " the area of a sphere"; cout << endl; }

Function overloading Functions with same name and different parameters Should perform similar tasks i.e., function to square int s and function to square float s int square( int x) {return x * x;} float square(float x) { return x * x; } Similar to overloaded +, /, etc. operators

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

// Fig. 3.25: fig03_25.cpp 2 // 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 << "Called square with int argument: " << x << endl; 12 return x * x; } // end int version of function square // 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

24 int main() 25 { 26 int intResult = square( 7 ); // int version called 27 double doubleResult; 28 doubleResult = square( 7.5 ); // calls double version 29 cout << "\nThe square of integer 7 is " << intResult 30 << "\nThe square of double 7.5 is " 31 << doubleResult << endl; return 0; // indicates successful termination } // end main Called square with int argument: 7 Called square with double argument: 7.5 The square of integer 7 is 49 The square of double 7.5 is 56.25

Write a program Write a program that uses functions Talk to your neighbors Use the book Use your notes