CSCI 123 Introduction to Programming Concepts in C++

Similar documents
Chapter void Functions. Overview. Functions for All Subtasks. void-functions. Using a void-function. void-function Definition

Programmer-Defined Functions

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Call- by- Reference Func0ons Procedural Abstrac0ons Numerical Conversions CS 16: Solving Problems with Computers I Lecture #9

Computer Programming

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

Problem Solving with C++

Call-by-Type Functions in C++ Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #5

Func%ons in C++ Part 2 CS 16: Solving Problems with Computers I Lecture #5

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

Chapter 9: Pointers Co C pyr py igh i t gh Pear ea so s n n E ducat ca io i n, n Inc. n c.

Void Functions Call-By-Reference Parameters Using Procedural Abstraction Testing and Debugging General Debugging Techniques

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

More on Func*ons Command Line Arguments CS 16: Solving Problems with Computers I Lecture #8

Lab Instructor : Jean Lai

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Absolute C++ Walter Savitch

Program Organization and Comments

Introduction to Programming I COS1511 School of Computing Revision Notes

CAMBRIDGE SCHOOL, NOIDA ASSIGNMENT 1, TOPIC: C++ PROGRAMMING CLASS VIII, COMPUTER SCIENCE

Homework #3 CS2255 Fall 2012

9.2 Pointer Variables. Pointer Variables CS Pointer Variables. Pointer Variables. 9.1 Getting the Address of a. Variable

UNIT- 3 Introduction to C++

Chapter 4 Defining Classes I

Exam 3 Chapters 7 & 9

Chapter 2 Basic Elements of C++

Functions. CS111 Lab Queens College, CUNY Instructor: Kent Chin

CS242 COMPUTER PROGRAMMING

Announcements. Lab 1 this week! Homework posted Thursday -Due next Thursday at 11:55pm

BITG 1113: Function (Part 2) LECTURE 5

What will happen if the user presses <enter> after every input? Will all work like below? Enter the values of x, y, z: Result: The sum is 17.

Computer Programming: C++

5. Control Statements

A SHORT COURSE ON C++

CSCI 1061U Programming Workshop 2. Function Basics

Chapter 1. C++ Basics. Copyright 2010 Pearson Addison-Wesley. All rights reserved

What is an algorithm?

FORM 2 (Please put your name and form # on the scantron!!!!) CS 161 Exam II:

This watermark does not appear in the registered version - Slide 1

8. Functions (II) Control Structures: Arguments passed by value and by reference int x=5, y=3, z; z = addition ( x, y );

Developed By : Mrs. K. M. Sanghavi

Lab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1

In this chapter, you will learn about: Pointers. Dynamic Arrays. Introduction Computer Science 1 CS 23021

At the end of this module, the student should be able to:

C introduction: part 1

(6) The specification of a name with its type in a program. (7) Some memory that holds a value of a given type.

CSI33 Data Structures

CSCI Wednesdays: 1:25-2:15 Keller Thursdays: 4:00-4:50 Akerman 211

Help File on C++ and Programming at CSUSM by Rika Yoshii

Fundamentals of Programming CS-110. Lecture 2

Chapter-11 POINTERS. Important 3 Marks. Introduction: Memory Utilization of Pointer: Pointer:


Annotation Annotation or block comments Provide high-level description and documentation of section of code More detail than simple comments

Programming Studio #9 ECE 190

CSI33 Data Structures

Data types. CISC 1600/1610 Computer Science I. Array syntax. Memory allocation. Zero-indexing 4/4/2016. Arrays

Add Subtract Multiply Divide

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

Numerical Computing in C and C++ Jamie Griffin. Semester A 2017 Lecture 2

VARIABLES & ASSIGNMENTS

Expressions and Casting

EECS402 Lecture 02. Functions. Function Prototype

Software Design and Analysis for Engineers

Announcements. Lab 1 this week! Homework posted Wednesday (late)

C++ Programming: From Problem Analysis to Program Design, Third Edition

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

UEE1302(1066) F12: Introduction to Computers and Programming Function (II) - Parameter

Exam 1. CSI 201: Computer Science 1 Fall 2018 Professors: Shaun Ramsey

Introduction to Programming in Turing. Input, Output, and Variables

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

CSCE 110 PROGRAMMING FUNDAMENTALS

Chapter 3 Function Basics

Chapter 16. Templates. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Functions. Arash Rafiey. September 26, 2017

Compiling with Multiple Files The Importance of Debugging CS 16: Solving Problems with Computers I Lecture #7

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Getting started with C++ (Part 2)

Overloading Functions & Command Line Use in C++ CS 16: Solving Problems with Computers I Lecture #6

Chapter 9. Pointers and Dynamic Arrays

6.096 Introduction to C++

Lecture 3 Tao Wang 1

Programming with Arrays Intro to Pointers CS 16: Solving Problems with Computers I Lecture #11

Computer Programming C++ Classes and Objects 6 th Lecture

What have we learned about when we learned about function parameters? 1-1

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language. Dr. Amal Khalifa. Lecture Contents:

Chapter Overview. Pointers and Dynamic Arrays. Pointers. Pointers. Declaring Pointers. Pointers Tell Where To Find A Variable. 9.

Lecture 3: C Programm

[Page 177 (continued)] a. if ( age >= 65 ); cout << "Age is greater than or equal to 65" << endl; else cout << "Age is less than 65 << endl";

CSCI 111 First Midterm Exam Spring Solutions 09.05am 09.55am, Wednesday, March 14, 2018

The University Of Michigan. EECS402 Lecture 02. Andrew M. Morgan. Savitch Ch. 3-4 Functions Value and Reference Parameters.

Programming with C++ as a Second Language

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

TEMPLATE IN C++ Function Templates

CSci 1113 Midterm 1. Name: Student ID:

Review. Modules. CS 151 Review #6. Sample Program 6.1a:

CS 251 Intermediate Programming Methods and Classes

Transcription:

CSCI 123 Introduction to Programming Concepts in C++ Brad Rippe Function Pass By Reference

What s wrong? for(int star = 0; star < 10; star++) { } for(star = 0; star < 10; star++) { } Style Open and End Brackets Indenting

Overview 5.1 void Functions 5.2 Call-By-Reference Parameters 5.3 Using Procedural Abstraction 5.4 Testing and Debugging

void-functions In top-down design, a subtask might produce No value (just input or output for example) One value More than one value We have seen how to implement functions that return one value A void-function implements a subtask that returns no value or more than one value

void-function Definition Two main differences between void-function definitions and the definitions of functions that return one value Keyword void replaces the type of the value returned void means that no value is returned by the function The return statement does not include an expression or value Example: void promptforlowerchar() { } cout << "Please type a lowercase character "; cout << "and I will make it uppercase.\n"; return;

Using a void-function void-function calls are executable statements They do not need to be part of another statement They end with a semi-colon Example: NOT: promptforlowerchar(); cin >> thechar; outputuppercase(thechar); cout << promptforlowerchar(); May accept parameters or not

void-function Calls Mechanism is nearly the same as the function calls we have seen Argument values are substituted for the formal parameters It is fairly common to have no parameters in void-functions In this case there will be no arguments in the function call Statements in function body are executed Optional return statement ends the function Return statement does not include a value to return Return statement is implicit if it is not included

Multiple Returns void fixacar(int numberofcarstofix) { if(numberofcarstofix == 0) return; int carscounter = 1; cin >> hours; cout << Your current charges are: ; cout << calculatecharges(hours) << endl; return; }

void-functions Why Use a Return? Is a return-statement ever needed in a void-function since no value is returned? Yes! What if a branch of an if-else statement requires that the function ends to avoid producing more output, or creating a mathematical error? void-function in next example, avoids division by zero with a return statement

void outputdivide(int op1, int op2) { if(op2 == 0) return; else cout << (op1/op2) << endl; }

The Main Function The main function in a program is used like a void function do you have to end the program with a return-statement? Because the main function is defined to return a value of type int, the return is needed C++ standard says the return 0 can be omitted, but many compilers still require it

Section 5.1 Conclusion Can you Describe the differences between void-functions and functions that return one value? Tell what happens if you forget the returnstatement in a void-function? Distinguish between functions that are used as expressions and those used as statements? Return value the other returns void or nothing

Call-By-Reference Parameters 5.2

Call-by-Reference Parameters Call-by-value is not adequate when we need a sub-task to obtain input values Call-by-value means that the formal parameters receive the values of the arguments To obtain input values, we need to change the variables that are arguments to the function Recall that we have changed the values of formal parameters in a function body, but we have not changed the arguments found in the function call Call-by-reference parameters allow us to change the variable used in the function call Arguments for call-by-reference parameters must be variables, not numbers

Call-by-Reference Example void square(int& avar) { avar *= avar; cout << "\tinside " << avar << endl; } & symbol (ampersand) identifies a as a call-by-reference parameter Used in both declaration and definition! The book places the & at the end of the formal parameters type, but it may be placed at the beginning of the variable name I like the book s style passbyreference.cpp

Call-By-Reference Details Compare what happens with pass-by-value to what happens with pass-by-reference Call-by-reference works almost as if the argument variable is substituted for the formal parameter, not the argument s value In reality, the memory location of the argument variable is given to the formal parameter Whatever is done to a formal parameter in the function body, is actually done to the value at the memory location of the argument variable subpassbyvalue.cpp subpassbyreference.cpp

Call Comparisons Call By Reference vs Value Call-by-reference The function call: getsubmarines(subs, torps); Call-by-value The function call: getsubmarines(subs, torps); Name Location Contents subs 1001 0 torps 1002 0 1003 1004 void getsub(int& subs,int& torps); Memory void getsubs(int subs, int torps);

Example: swap void swap(int& variable1, int& variable2) { int temp = variable1; variable1 = variable2; variable2 = temp; } If called with swap(num1, num2); num1 is substituted for variable1 in the parameter list num2 is substituted for variable2 in the parameter list temp is assigned the value of variable1 (num1) since the next line will loose the value in num1 variable1 (num1) is assigned the value in variable2 (num2) variable2 (num2) is assigned the original value of variable1 (num1) which was stored in temp swap.cpp

Mixed Parameter Lists Call-by-value and call-by-reference parameters can be mixed in the same function Example: void getsubmarines(int& submarines, int& torpedos, int depthcharges); submarines and torpedoes are call-by-reference formal parameters Changes in submarines and torpedos change the argument variable depthcharges is a call-by-value formal parameter Changes in depthcharges do not change the argument variable Side Note: One disadvantage of pass-by-value is that, if a large data item is being passed, copying that data can take a considerable amount of execution time and memory space. Mixedpassing.cpp

Choosing Parameter Types How do you decide whether a call-by-reference or call-by-value formal parameter is needed? Does the function need to change the value of the variable used as an argument? Yes? Use a call-by-reference formal parameter No? Use a call-by-value formal parameter

Inadvertent Local Variables If a function is to change the value of a variable the corresponding formal parameter must be a call-by-reference parameter with an ampersand (&) attached Forgetting the ampersand (&) creates a call-by-value parameter The value of the variable will not be changed The formal parameter is a local variable that has no effect outside the function Hard error to find it looks right! swap.cpp

Section 5.2 Conclusion Can you Write a void-function definition for a function called zeroboth that has two reference parameters, both of which are variables of type int, and sets the values of both variables to 0. Write a function that returns a value and has a call-by-reference parameter? Write a function with both call-by-value and call-by-reference parameters

Using Procedural Abstraction 5.3

Using Procedural Abstraction Functions should be designed so they can be used as black boxes To use a function, the declaration and documentation should be sufficient Programmer should not need to know the details of the function to use it

Functions Calling Functions A function body may contain a call to another function The called function declaration must still appear before it is called Functions cannot be defined in the body of another function Example: void setdepthcharges(int& submarines, int& torpedoes, int depthcharges) { getsubsandtorpedoes(submarines, torpedoes); for(int i = 0; i < depthcharges; i++) { int hitsub = 1 + rand() % (submarines * 2); if(hitsub <= submarines) { cout << "Submarine " << hitsub << " has been hit by "; cout << "a depth charge\n"; } else { cout << "Depth charge " << (i+1) << " missed.\n"; } } }

Pre and Postconditions - Documentation Precondition uses the @pre annotation States what is assumed to be true when the function is called Function should not be used unless the precondition holds Postcondition uses the @post annotation Describes the effect of the function call Tells what will be true after the function is executed (when the precondition holds) If the function returns a value, that value is described Changes to call-by-reference parameters are described

swapbyref Documentation Using preconditions and postconditions the declaration of swapbyref becomes: /** * Swaps the values of variable 1 with variable 2 * * @param var1 the value of variable 1 * @param var2 the value of variable 2 * @pre var1 and var2 have been initialized to values * @post the value of variable 1 has been replaced with the value * of variable 2 and the value of variable 2 has been replaced * with the value of variable 1 */ void swapbyref(int& var1, int& var2);

Function outputvars Preconditions and postconditions make the declaration for outputvars: /** * This function outputs the values in var1 and var2 * It is intended use is after one of the swap functions * have been called. * @param funcname the name of the swap function that was called before * outputvars * @param var1 the value of variable 1 * @param var2 the value of variable 2 * @pre variable 1 and 2 have been swapped by one of the swap functions * @post The name of the swap function and the values of variables 1 and 2 * have been output to the user */ void outputvars(string& funcname, int var1, int var2);

Why use preconditions and postconditions? Preconditions and postconditions should be the first step in designing a function specify what a function should do Always specify what a function should do before designing how the function will do it Minimize design errors Minimize time wasted writing code that doesn t match the task at hand

Case Study Garage Pricing Problem definition Determine the parking charge for 3 cars parked Flat fee of $2.00 for up to and including 3 hour of parking Flat fee $10.00 for a car parked for 24 hours No car will exceed 24 hours $0.50 charge for each hour or part of an hour in excess of three hours Input The hours that each car was parked in the garage Output The hours for each car, the charge, the total hours and the total charges for the day

Garage Pricing: Problem Analysis Three main subtasks Input the data Compute the charges based on the hours Output the results Each task can be implemented with a function Notice the use of call-by-value and call-by-reference parameters in the following function declarations

Garage Pricing: Function gethoursforcars /** * Prompt the user to input hours for three cars and sets the * hours for each car * @param hour1 the hours for car 1 * @param hour2 the hours for car 2 * @param hour3 the hours for car 3 * @pre hours have been declared * @post hours 1 2 and 3 have been sent from user input */ void gethoursforcars(double& hours1, double& hours2, double& hours3);

Garage Pricing: Function setdecimalformat /** * Sets the cout object to display decimal digits with two decimal places * @pre none * @post cout will display decimal digits with two decimal places */ void setdecimalformat();

Garage Pricing: Function outputcharges /** * Outputs the charges for all three cars. * @param hour1 the hours for car 1 * @param hour2 the hours for car 2 * @param hour3 the hours for car 3 * @pre hours have been initialized and the cout object * has been manipulated to output decimal digits * with two decimal places * @post hours and charges for each car has been output * in addition to the total hours and charges for * all three cars */ void outputcharges(double hours1, double hours2, double hours3);

Garage Pricing: The main function With the functions declared, we can write the main function: int main() { double hours1; double hours2; double hours3; } gethoursforcars(hours1, hours2, hours3); setdecimalformat(); outputcharges(hours1, hours2, hours3);

Algorithm Design calculatecharges pseudocode for the price function if hours <= 3 return $2.00 if hours == 24 return $10.00 otherwise return 2.00 + roundup (hours-3)*0.50;

Coding The calculatecharges Function The body of the price function double calculatecharges(double hours) { if(hours <= 3) { return 2.0; } else if(hours == 24) { return 10.0; } else { return 2.0 + ceil(hours-3.0)*.50; } }

Garage Pricing : Program Testing Testing strategies Use data that tests both the high and low markup cases Test boundary conditions, where the program is expected to change behavior or make a choice 3 hours, 4 hours and 24 hours Test for exactly 4.5 hours make sure your program is rounding up 3 = 2.00 4.5-3 = 1.5 2*.5 = 1.00 Total 3.00

Section 5.3 Conclusion Can you Define a function in the body of another function? Call one function from the body of another function? Give preconditions and postconditions for the predefined function sqrt?

5.4 Testing and Debugging

Testing and Debugging Functions Each function should be tested as a separate unit Testing individual functions facilitates finding mistakes Driver programs allow testing of individual functions Once a function is tested, it can be used in the driver program to test other functions Function getsubsandtorpedoes is tested in the driver program

void getsubsandtorpedoes(int& submarines, int& torpedoes) ; int main() { int submarines = 0; int torpedoes = 0; int depthcharges = 10; char again = 'Y'; } while(toupper(again)!= 'N') { cout << "Type integers for subs and torpedoes\n"; getsubsandtorpedoes(submarines, torpedoes); cout << "Subs set by the user " << submarines << endl; cout << "Torpedoes set by the user " << torpedoes << endl; cout << "Would you like to continue?\n"; cout << "Y for yes and N for no\n"; cin >> again; } return 0;

void getsubsandtorpedoes(int& submarines, int& torpedoes) { cin >> submarines; cin >> torpedoes; cout << "You have typed "; cout << submarines << " submarines and "; cout << torpedoes << " torpedoes\n"; }

Stubs When a function being tested calls other functions that are not yet tested, use a stub A stub is a simplified version of a function Stubs are usually provide values for testing rather than perform the intended calculation Stubs should be so simple that you have confidence they will perform correctly Function getsubsandtorpedoes is used as a stub to test the rest of the submarine program

/**************************************************** / /* getsubsandtorpedoes is now a stub /* suppose the requirement was to read subs and torpedoes /* from a file since this code hasn't been tested, we can use a stub /* to test setdepthcharges before we tackle the problem of /* reading submarines from a file /**************************************************** / void getsubsandtorpedoes(int& submarines, int& torpedoes) { submarines = 5; torpedoes = 2; }

void setdepthcharges(int& submarines, int& torpedoes, int depthcharges) { getsubsandtorpedoes(submarines, torpedoes); } for(int i = 0; i < depthcharges; i++) { int hitsub = 1 + rand() % (submarines * 2); if(hitsub <= submarines) { cout << "Submarine " << hitsub << " has been hit by "; cout << "a depth charge\n"; submarines--; } else { cout << "Depth charge " << (i+1) << " missed.\n"; } }

Rule for Testing Functions Fundamental Rule for Testing Functions Test every function in a program in which every other function in that program has already been fully tested and debugged.