Department of Computer and Mathematical Sciences. Lab 10: Functions. CS 1410 Intro to Computer Science with C++

Similar documents
Lab 10: Alternate Controls

3. Functions. Modular programming is the dividing of the entire problem into small sub problems that can be solved by writing separate programs.

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.6

I/O Streams and Standard I/O Devices (cont d.)

TEST 1 CS 1410 Intro. To Computer Science Name KEY. October 13, 2010 Fall 2010

4. C++ functions. 1. Library Function 2. User-defined Function

Outline. Why do we write functions? Introduction to Functions. How do we write functions? Using Functions. Introduction to Functions March 21, 2006

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 6: User-Defined Functions I

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

Understanding main() function Input/Output Streams

Programming Language. Functions. Eng. Anis Nazer First Semester

Lab 4: Introduction to Programming

Introduction. What is function? Multiple functions form a larger program Modular programming

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

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

LAB: INTRODUCTION TO FUNCTIONS IN C++

C++ Quick Guide. Advertisements

VARIABLES & ASSIGNMENTS

Getting started with C++ (Part 2)

Chapter 4: Subprograms Functions for Problem Solving. Mr. Dave Clausen La Cañada High School

Function. Mathematical function and C+ + function. Input: arguments. Output: return value

A SHORT COURSE ON C++

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

Chapter 2 - Control Structures

Lab Instructor : Jean Lai

1. Variables 2. Arithmetic 3. Input and output 4. Problem solving: first do it by hand 5. Strings 6. Chapter summary

C++ Functions. Last Week. Areas for Discussion. Program Structure. Last Week Introduction to Functions Program Structure and Functions

Chapter 15 - C++ As A "Better C"

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

Chapter 2 - Control Structures

CSCE 110 PROGRAMMING FUNDAMENTALS

Functions. Lecture 6 COP 3014 Spring February 11, 2018

3.1. Chapter 3: Displaying a Prompt. Expressions and Interactivity

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.

Designing Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6

Computer Programming : C++

CSE 230 Intermediate Programming in C and C++ Functions

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.

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

6 Functions. 6.1 Focus on Software Engineering: Modular Programming TOPICS. CONCEPT: A program may be broken up into manageable functions.

(created by professor Marina Tanasyuk) FUNCTIONS

C++ Support Classes (Data and Variables)

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.7. User Defined Functions II

Introduction to C++ Introduction to C++ 1

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

CHAPTER 4 FUNCTIONS. 4.1 Introduction

C++ Programming Lecture 1 Software Engineering Group

int n = 10; int sum = 10; while (n > 1) { sum = sum + n; n--; } cout << "The sum of the integers 1 to 10 is " << sum << endl;

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

Input and Output File (Files and Stream )

Chapter 2 - Control Structures

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

C++ For Science and Engineering Lecture 15

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

CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011

Makefiles Makefiles should begin with a comment section of the following form and with the following information filled in:

The cin Object. cout << "Enter the length and the width of the rectangle? "; cin >> length >> width;

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

Why Is Repetition Needed?

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

To become familiar with array manipulation, searching, and sorting.

Cpt S 122 Data Structures. Introduction to C++ Part II

Chapter 2 Basic Elements of C++

Lecture 7. Log into Linux New documents posted to course webpage

Expressions, Input, Output and Data Type Conversions

Chapter 1 - What s in a program?

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3

BITG 1113: Files and Stream LECTURE 10

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

6.096 Introduction to C++ January (IAP) 2009

Introduction to Programming

Exercise 1.1 Hello world

Engineering Problem Solving with C++, Etter/Ingber

Honors Computer Science C++ Mr. Clausen Program 4A, 4B, 4C (4D, 4G)

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

LOGO BASIC ELEMENTS OF A COMPUTER PROGRAM

BEng (Hons) Electronic Engineering. Resit Examinations for / Semester 1

Chapter 2. Outline. Simple C++ Programs

BITG 1233: Introduction to C++

What we will learn about this week: Declaring and referencing arrays. arrays as function arguments. Arrays

4. Structure of a C++ program

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

do { statements } while (condition);

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

CSI33 Data Structures

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Chapter 3 - Notes Input/Output

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Program Organization and Comments

C Programming for Engineers Functions

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

Your first C++ program

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++

Variables. Data Types.

2.11 Assignment Operators. Assignment expression abbreviations c = c + 3; can be abbreviated as c += 3; using the addition assignment operator

CISC 1110 (CIS 1.5) Introduc2on to Programming Using C++

Objects and streams and files CS427: Elements of Software Engineering

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Transcription:

_ Unit 2: Programming in C++, pages 1 of 8 Department of Computer and Mathematical Sciences CS 1410 Intro to Computer Science with C++ 10 Lab 10: Functions Objectives: The objective of this lab is to understand the concept of function and its use Recall that the concept of a FUNCTION in programming is similar to the same concept in algebra Like an algebra function, a program function has a name and takes a certain type and number of data values as inputs The function then processes these inputs in some way to produce a single output data value In algebra, a function often has only one input, a real number data value And the way an algebra function processes the inputs to produce the output is usually defined by a mathematical expression or formula In programming, of course, the way a function processes the inputs is defined by a block of statements, called the BODY or IMPLEMENTATION of the function And it is often the case that a program function will have more than one input data value These inputs are also called ARGUMENTS or PARAMETERS of the function The use of functions plays a key role in C++ programming Functions provide an elegant mechanism for breaking complex programs into simpler, easier to understand SUB- PROGRAMS They also provide a means for the same code instructions to be used over and over again in the same program or in other programs, which can save time and money It is easy to create a function in a program The compiler needs to know the following information, in this order: 1 The type of the output value (no identifier necessary) 2 The identifier of the function 3 The types and identifiers of the function parameters (may be several) 4 The body of the function (a list of statements inside of braces) The general syntax for DEFINING (creating) a program function is: return_type function_identifier( list of parameters ) list of statements; return ( return_value ); The last statement in the function body begins with the reserved word "return" followed by an expression inside of parentheses (paren's are optional) This is the value that is output by the function when the function is CALLED or INVOKED in another part of the program The return value must be of the data type indicated on the first line of the function definition Also shown on the first line is the identifier for the function and then, inside of parentheses, the list of function parameters Each parameter is indicated by both its data type and an identifier, and

Unit 2: Programming in C++, pages 2 of 8 parameters in the list are separated by commas Here, for instance, is a C++ implementation of the algebra function f(x) = (x - 2)^2 : double f (double x) x = x - 2; return (x*x); Therefore, this function is named "f" and has one input, a double called "x" It outputs a double value as well (note the expression x*x evaluates as double) Also note that the input x can be used just like a normal variable Task 1: DO-WHILE loop statement The purpose of this task is to trace the execution of a FUNCTION The body of a function does not execute until the function is used in another part of the program The only exception to this rule is the main body of the program You can now see that the main body of a program is really the body of a function called "main" Every C++ program must have a function called "main" Note that the main function outputs an integer, which is why the last line of the main body of all programs we have seen so far is " " Every C++ program begins executing by invoking the main function, thus the main function is called the ENTRY POINT for the program The main function has no inputs, which is indicated by using the reserved word "void" in place of the parameter list Other function definitions are often placed after the main function in the source code file for a program The body of a function can contain any type of statement, such as input/output statements, selection statements, and loops This includes declaration statements for variables and named constants A variable that is defined within a block of statements, such as the body of a function, is called a LOCAL variable This means that the variable is only in existence while the given block of code is executing If the block of code where a local variable is declared terminates, the local variable goes out of existence and is considered to be undeclared Thus it cannot be used outside of that block Here is simplified example of some function definitions and local variables: int a, b=5; double c=100; a = P( b, c ); int P(int m, double n) int x, y, c; return x;

Lab 10: Functions, page 3 of 8 The local variables of function P( ) in the above example are x, y, and c The parameters m and n in the function P( ) definition are called FORMAL PARAMETERS and also count as local variables The statement a = P( b, c ); in the main function is a FUNCTION CALL that invokes (starts) the execution of the body of the called function P The parameters b and c are called ACTUAL PARAMETERS When the function P( ) is called from the main function, the formal parameters are ALLOCATED (set up in memory) and are automatically initialized from the values of the actual parameters, in order So in this example, m is initialized as 5 and n is initialized as 100 Then the other local variables are allocated and the function body executes to the RETURN statement The value stored in the local variable x is returned to the main function and assigned to the variable a All the local variables in the function P( ) are DEALLOCATED (deleted from memory) when the function terminates Activity 11: Study the following program carefully In the following program, the two functions PrintStuff( ) and NumStuff( ) are called from the main program (function) Since the body of the main function is placed before the bodies of the two functions in the source code file, the function identifiers need to be declared before the main function body, otherwise the compiler will give "undeclared identifier" syntax errors when the function call statements are reached in the main function The mechanism used to declare a function identifier without actually defining the body of the function is called a FUNCTION PROTOTYPE or DECLARATION This consists of the first line of the function definition, except that the identifiers for the formal parameters can be left out (but the data types of the formal parameters must remain) Note also that function prototypes must terminate with a semicolonthe return data type of the function PrintStuff( ) is "void" This means that PrintStuff( ) does not return a data value This is why there is no RETURN statement in the body of PrintStuff( ) Another interesting feature of this program is the fact that there are variables named "n", one in the main function and one in the function PrintStuff( ) It is important to understand that these variables are NOT the same and do not represent the same memory location Different values may be stored in these two variables #include <iostream> #include <iomanip> using namespace std; //Program name: Stars_and_Bars void PrintStuff(char, int); int NumStuff(int); int counter, n; for (counter = 0; counter <= 4; counter++) n = NumStuff(counter); if (counter%2 == 0) cout<<n; PrintStuff('*', n); cout<<n; else cout<<n; PrintStuff('-', n); cout<<n;

Unit 2: Programming in C++, pages 4 of 8 cout<<endl; cinget(); cinget(); // Stars_and_Bars int NumStuff(int x) x = 8*x - 2*x*x + 1; return (x); // NumStuff void PrintStuff(char c, int x) int n; for (n=1; n <= x+1; n++) cout<<c; // PrintStuff Activity 12: Predict the output from the program Stars_and_Bars Predicted Output: Activity 13: Start MS Visual Studio and create a C++ project called Lab10 Then add a new file Lab10Tsk1cpp to the project Copy the program in Activity 11 to Lab10Tsk1cpp Then run the program Stars_and_Bars and observe the output Explain any discrepancies with your predicted output Obeserved Outut: Activity 14: List all the identifiers for variables used as FORMAL PARAMETERS in the program Stars_and_Bars Then list the identifiers for all variables used as ACTUAL PARAMETERS Formal parameter: Actual parameters: Activity 15: Now modify the program Stars_and_Bars by deleting the declaration statement " int n; " from the function PrintStuff( ) Predict the syntax error that this causes in the program Then try compiling the modified program to confirm your prediction

Lab 10: Functions, page 5 of 8 Predicted syntax error: Observed sysntax error: Task 2: For-Loop The purpose of this task is to illustrate how to IMPLEMENT functions One advantage to using functions is to simplify the main function Sometimes key segments or processes in the main function can be broken out as functions that are called from the main function This can make the main function easier to design, code, trace, and debug Activity 21: Study the following program carefully This program is designed to compute the monthly payment on an amount borrowed with a given interest rate and pay-back period #include <iostream> #include <iomanip> #include <cmath> using namespace std; //Program name: Amortize double Amount, Rate, Payment, Z; int Years, NoPayment; cout<<"enter the borrowed amount --->"; cin>>amount; cout<<endl<<"enter the annual interest rate (%) --->"; cin>>rate; cout<<endl<<"enter the pay-back period (in years) --->"; cin>>years; /******These statements compute the monthly payment*****/ Rate = Rate / 1200; NoPayment = Years*12; Z = exp(-nopayment * log(1+rate)); Z = (1 - Z) / Rate; Payment = Amount / Z; /*******************************************************/ cout<<endl; cout<<setprecision(2)<<fixed<<showpoint; cout<<"the monthly payment is $"<<Payment<<endl; cinget(); cinget(); // Amortize Activity 22: Add a new cpp file to Lab10 project called Lab10Tsk2cpp and copy the program in Activity 21 to Lab10Tsk2cpp Then run the Amortize program with the following values for the input and observe the output Amount: Rate: Year: Payment: 9500 8% 30 20000 9% 5 20000 75% 5

Unit 2: Programming in C++, pages 6 of 8 Activity 23: Modify the program Amortize by inserting a function FindPayment( ) that will compute the monthly payment The modified program should appear as follows: #include <iostream> #include <iomanip> #include <cmath> using namespace std; /***** Function prototype goes here ******/ //Program name: Amortize double Amount, Rate, Payment, Z; int Years, NoPayment; cout<<"enter the borrowed amount --->"; cin>>amount; cout<<endl<<"enter the annual interest rate (%) --->"; cin>>rate; cout<<endl<<"enter the pay-back period (in years) --->"; cin>>years; /******These statements compute the monthly payment*****/ Payment = FindPayment (Amount, Rate, Year); /*******************************************************/ cout<<endl; cout<<setprecision(2)<<fixed<<showpoint; cout<<"the monthly payment is $"<<Payment<<endl; cinget(); cinget(); // Amortize /*****Insert function definition for FindPayment( ) here*****/ Activity 24: Test your modified program with the same input as in Activity Two Print and turn in a copy of the modified program Amount: Rate: Year: Payment: 9500 8% 30 20000 9% 5 20000 75% 5 Task 3: For-Loop The purpose of this task is to gain experience developing functions based on PRECONDITIONS and POSTCONDITIONS It is important to document the purpose of a function and provide instructions about how to use and call a function This is so the function can be used by programmers other than the original programmer, or can be used again in the future Using functions created by other programmers can be a tremendous way of saving time and therefore money (this process is called CODE REUSE) From your own experience, think of how convenient it has been to use the functions declared in the header file cmath, such as pow( ) and sqrt( ) One means of documenting how

Lab 10: Functions, page 7 of 8 functions work are PRECONDITIONS and POSTCONDITIONS Function preconditions document the conditions that are necessary for the function to execute properly and produce correct output Preconditions often describe how the parameters to a function must be initialized when the function is called and begins executing Postconditions, on the other hand, give information about the status of a program when the function terminates They typically describe the output value returned by the function (if any), and other sorts of actions performed by the function, such as input or output to a stream Remember that pre- and post-conditions are merely comments, so they don't really affect the way a function executes But one of your goals as a programmer should be to make sure that any function you write conforms to its pre- and postconditions Moreover, any function you write should be documented with enough information in the pre- and post-conditions that another programmer can understand the nature and purpose of the function and how it can be used correctly Activity 31: Study the following program carefully This program is intended to take a text file and convert upper-case characters to lower-case and vice versa Punctuation should not be affected In the input text, a ' - ' (dash) indicates a space and a ' / ' (slash) indicates the end of the line The character ' * ' is the sentinel value used to indicate end-of-file This program will use a function called SwitchCase( ) The declaration for SwitchCase and pre- and post-conditions are given in the program #include <iostream> #include <iomanip> #include <fstream> using namespace std; char SwitchCase(char); //Program name: ViceVersa char c; fstream Infile; Infileopen("a:\\inlab83txt", ios::in); Infile>>c; while (c!= '*') while (c!= '/') if (c == '-') cout<<' '; else if (((c>='a')&&(c<='z')) ((c>='a')&&(c<= z'))) cout<<switchcase(c); else cout<<c; Infile>>c; // not end of line cout<<endl; Infile>>c; // not end of file Infileclose(); cinget(); cinget(); // ViceVersa char SwitchCase (char Target) /* Pre-condition: Target is a letter Post-condition: The value returned is Target switched from upper-case to lower-case or vice versa */ // SwitchCase

Unit 2: Programming in C++, pages 8 of 8 Activity 32: Add a new cpp file to Lab10 project called Lab10Tsk3cpp and copy the program ViceVersa in Activity 31 to Lab10Tsk3cpp Then modify the program ViceVersa by completing the code body for SwitchCase( ) Be careful that SwitchCase( )satisfies the preand post-conditions As you write the function body, remember you can assume that the preconditions will be true as the function executes Any program that uses this function should be careful to only use the function in the way described by the pre- and post-conditions Create a text file called InLab103txt and test the modified program with the input file that you just created Print and turn in a copy of your modified program InLab103txt This-file's-just-a/ test-to-see-how-your-program-converts-lowercase-letters/ to-uppercase-letters-and-vice-versa--after-running-the-program-all/ the-letters-should-switch-cases/ / Good-Job/* Activity 33: What provisions are made in the main function of the program ViceVersa to guarantee that when the function SwitchCase( ) is called, the pre-condition for this function will be true? Answer: