A function (procedure) code to perform a task (carry out an algorithm) Return_type Func(parameters) ---- Func (arguments) --- Return value.

Slides:



Advertisements
Similar presentations
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Advertisements

1 C++ Syntax and Semantics The Development Process.
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
True or false A variable of type char can hold the value 301. ( F )
Types and Variables. Computer Programming 2 C++ in one page!
COSC 120 Computer Programming
Chapter 10.
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Introduction.
© 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5/e Starting Out with C++: Early Objects 5 th Edition Chapter 2 Introduction.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Lecture 29 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Chapter 11 – Structured Data
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Basic Elements of C++ Chapter 2.
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
More Storage Structures A Data Type Defined by You Characteristics of a variable of a specific ‘data type’ has specific values or range of values that.
Functions Programming in C++ Computer Science Dept Va Tech August 2000 ©2000 William D McQuain 1 #include // for file streams for input/output #include.
CSC 125 Introduction to C++ Programming Chapter 2 Introduction to C++
COMPUTER PROGRAMMING. Data Types “Hello world” program Does it do a useful work? Writing several lines of code. Compiling the program. Executing the program.
Elements of a C++ program 1. Review Algorithms describe how to solve a problem Structured English (pseudo-code) Programs form that can be translated into.
Input & Output: Console
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 2 Introduction to C++
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
1 Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
1 C++ Syntax and Semantics, and the Program Development Process.
C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:
CIS-165 C++ Programming I CIS-165 C++ Programming I Bergen Community College Prof. Faisal Aljamal.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
 2008 Pearson Education, Inc. All rights reserved Pointers and Pointer-Based Strings.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
Pointers A pointer is a variable that contains a memory address as it’s value. The memory address points to the actual data. –A pointer is an indirect.
CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout
Slides created by: Professor Ian G. Harris Hello World #include main() { printf(“Hello, world.\n”); }  #include is a compiler directive to include (concatenate)
Chapter 10 Structures, Unions, Bit Manipulations, and Enumerations Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering.
CSC 143A 1 CSC 143 Introduction to C++ [Appendix A]
More About Data Types & Functions. General Program Structure #include statements for I/O, etc. #include's for class headers – function prototype statements.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Managers and “mentors” identified on projects page. All member accounts created and projects populated.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
Variables and memory addresses
Lecture 5 Computer programming -1-. Input \ Output statement 1- Input (cin) : Use to input data from keyboard. Example : cin >> age; 2- Output (cout):
1 CSC 1111 Introduction to Computing using C++ C++ Basics (Part 1)
CPS120 Introduction to Computer Science Exam Review Lecture 18.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Functions Procedural Abstraction Flow of Control INFSY 307 Spring 2003 Lecture 4.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
1 Chapter 12 Classes and Abstraction. 2 Chapter 12 Topics Meaning of an Abstract Data Type Declaring and Using a class Data Type Using Separate Specification.
Chapter 12 Classes and Abstraction
C++ Lesson 1.
Chapter Topics The Basics of a C++ Program Data Types
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 2: Introduction to C++
Basic Elements of C++.
Student Book An Introduction
DATA HANDLING.
Basic Elements of C++ Chapter 2.
Enumeration used to make a program more readable
Introduction to Abstract Data Types
2.1 Parts of a C++ Program.
More About Data Types & Functions
Built-In (a.k.a. Native) Types in C++
Pointers and Pointer-Based Strings
Chapter 2: Introduction to C++.
Presentation transcript:

a function (procedure) code to perform a task (carry out an algorithm) Return_type Func(parameters) ---- Func (arguments) --- Return value

Parameters Java parameters are either –primitive types - parameter is a copy of the argument (argument cannot be changed) –objects - parameter is an alias for the argument (argument can be changed) C++ parameters are either –value parameters –reference parameters –constant reference parameters –array parameters

Java parameter passing public void myMethod (int number, SomeClass myObj) { --- } number myObj 36 activation record (memory space) created when myMethod is called obj.myMethod (intArg, objArg); 36 intArg objArg

C++ Parameters C++ parameters are either –value - (type param_name) parameter is a copy of the argument, thus argument cannot be modified –reference - (type & param_name) parameter is an alias for the argument, thus argument is modified if parameter is modified –constant reference - (const type & param_name) parameter is an alias for the argument, but compiler disallows assignment to parameter

C++ parameter passing void myFunction (int val, int & ref, const int & constref) { --- } v 36 myFunction (v, r, cr); r 25 cr 6 36 val ref activation record (memory space) created when myFunction is called constref

Decomposition Example main Instruct GetEmployee Info GrossWages Compute NetPay Print EmpInfo from Figure C.6 Using Functions on p.781

/* Program to compute wages for several employees. Written at ___________ by _________________- Input: Id-number, number of dependents, hours worked, and hourly rate for each of several employees Output: Id-number, hours worked, gross pay, taxes withheld and net pay ____________________________________________________*/ #include using namespace std; void Instruct ( ); void GetEmployeeInfo (int & empNumber, int & dependents, double & hours, double & rate, bool & done); double GrossWages (int dependents, double hours, double rate); void ComputeNetPay (double grossPay, int dependents, double & tax, double & netPay); void PrintEmpInfo (int idNumber, double hours, double grossPay, double taxes, double netPay); int main ( ) { }

int main ( ) { int idNumber, // employee's id-number numDependents; // number of dependents double hoursWorked, // hours worked this pay period hourlyRate, // dollars per hour grossPay, // pay before taxes taxWithheld, // amount of tax withheld netPay; // grossPay - tasWithheld bool endOfData; // signals end of data Instruct ( ); for ( ; ; ) { GetEmployeeInfo (idNumber, numDependents, hoursWorked, hourlyRate, endOfData); if (endOfData) break; // MUST BE CHANGED!! grossPay = GrossWages (numDependents, hoursWorked, hourlyRate); ComputeNetPay (grossPay, numDependents, taxWithheld, netPay); PrintEmpInfo (idNumber, hoursWorked, grossPay, taxWithheld, netPay); } return 0; }

int main ( ) { int idNumber, // employee's id-number numDependents; // number of dependents double hoursWorked, // hours worked this pay period hourlyRate, // dollars per hour grossPay, // pay before taxes taxWithheld, // amount of tax withheld netPay; // grossPay - tasWithheld // bool endOfData; // signals end of data Instruct ( ); while (GetEmployeeInfo (idNumber, numDependents, hoursWorked, hourlyRate)) { // if (endOfData) break; // TO BE CHANGED!! grossPay = GrossWages (numDependents, hoursWorked, hourlyRate); ComputeNetPay (grossPay, numDependents, taxWithheld, netPay); PrintEmpInfo (idNumber, hoursWorked, grossPay, taxWithheld, netPay) } return 0; }

Change Needed? void GetEmployeeInfo (int & empNumber, int & dependents, double & hours, double & rate, bool & done); bool GetEmployeeInfo (int & empNumber, int & dependents, double & hours, double & rate);

/* bool GetEmployeeInfo (int & empNumber, int & dependents, double & hours, double & rate) Purpose: read information for one employee Precondition(s): none Postcondition(s): The four parameters have been assigned values Returns: false if end of data reached; true otherwise */ bool GetEmployeeInfo (int & empNumber, int & dependents, double & hours, double & rate) { cout << "\nEnter employee number (0 to stop): "; cin >> empNumber; if (empNumber == 0) return false; cout << "Enter # of dependents, hours worked, and hourly rate for " << empNumber << ": "; cin >> dependents >> hours >> rate; return true; }

/* double GrossWages (int dependents, double hours, double rate) Purpose: compute gross wages as determined by number of hours employee worked plus a dependency allowance for each dependent. Precondition(s): dependents, hours and rate >= 0 Postcondition(s): none Returns: Gross wages */ double GrossWages (int dependents, double hours, double rate) { const double DEP_ALLOWANCE = 100; // bonus per dependent double wages; // wages earned if (hours <= 40) // no overtime wages = hours * rate; else // overtime wages = 40 * rate * rate * (hours - 40); return wages + DEP_ALLOWANCE * dependents; }

/* void Instruct ( ) Purpose: Display instructions to the user Precondition(s): none Postcondition(s): instructions have been displayed on the screen Returns: nothing **********************************************************************************/ /* void ComputeNetPay(double grossPay, int dependents, double & tax, double & netPay) Purpose: compute taxes withheld and net pay Precondition(s): grossPay and dependents are valid Postcondition(s): tax and netPay have been assigned computed values Returns: nothing ************************************************************************************/ /* void PrintEmpInfo( int idNumber, double hours, double grossPay double taxes, double netPay) Purpose: display payroll information regarding one employee Precondition(s): idNumber, hours, grossPay, taxes and netPay are valid Postcondition(s): payroll information has been displayed on the screen Returns: nothing *************************************************************************************/

Programming & Problem Solving Representation of real world problem Processing algorithms Representation of results Real world problem Real world results PROBLEM DOMAIN PROGRAM DOMAIN

Variables (data objects) Components of a data object –name (programmer defined) –address (memory location) –type –value (determined by interpretation of the sequence of bits stored in memory) type name [= value];

Types predefined (built-in) vs programmer defined simple (fundamental) vs structured type of a data object determines –number of bytes used to store the value –interpretation of the bit pattern stored in those bytes –possible operations data abstraction refers to the separation of the use of a data type from the implementation details

C++ Types Characters IntegralFloating point (reals) char short int int unsigned short unsigned float double long double IntegersEnumerations Arithmetic void pointers struct union priority_queue long int unsigned long unsigned char signed char array boolcomplex Fundamental Types Structured Types valarray vector deque list set map multiset multimap stack queue string bitset istream ostream iostream ifstream ofstream fstream C++ Standard Library classes

C++ arrays groups data items of same type under one name –double Numbers[4]; –int List = {45, 63, 22}; individual items accessed by indexing –Numbers[2] = 85.3; –first array element is at index position 0 C++ arrays are not objects –no length data member number of elements is determined either –at compile-time (both examples above) –at run-time (coming later)

C++ array implementation array name is a variable whose value is the base address of the array, i.e. a pointer variable accessing an individual element involves calculating its address –base_address + index * element_size List b b+1 b+2 b+3 b b b+12 List[0] List[1] List[2]

Alternative Syntax Given: int List = {45, 63, 22}; first element can be accessed by –List[0]; –*List; // * is the dereferencing operator second element can be accessed by –List[1]; –*(List + 1); what is the value of List? always use the indexing notation

C++ array parameters void func (double A[ ], int N) { --- } arguments provided when func is called Numbers N 4 activation record (memory space) created when func is called ANAN const

C++ structs struct - group of data items of different types –struct person { string Name; int Age; }; –person is a type grouping together 2 data members –person OneStudent; //represents 1 person –person Class[25]; //represents 25 persons dot operator (.) used to access members –Class[i].Age struct to struct assignments are legal –Class[i] = Class[i+1];

Creating New C++ Types enumeration –allows defining your own set of values for a scalar type typedef –allows for defining a synonym or alias for an existing type struct –allows a variable to have multiple values of different types class –allows encapsulating data members and operations

Enumeration used to make a program more readable associates a set of programmer defined values with the integer values 0, 1, 2, - - Example –enum Suit {CLUBS, SPADES, HEARTS, DIAMONDS}; – Suit mySuit = HEARTS; – if (mySuit == SPADES) --- – switch (mySuit) { case CLUBS: ---- case SPADES: ---

typedef statement used to declare a new name (synonym) for an already existing type –const int SIZE = 100; –typedef int intArrayType[SIZE]; –intArrayType numberList; usually given global (file) scope used to make a program easier to modify

C++ strings early versions of C++ used “C-style strings” –array of char with a special character (null character) marking the end – or have functions to manipulate C-style strings C++ standard library provides the class string –#include –use C++ string class, not C-style strings –see Ch.3 sec.4 for information and examples; also TableD.4