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

Similar documents
CSCE Practice Midterm. Data Types

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

Programming Language. Functions. Eng. Anis Nazer First Semester

CSCE Practice Midterm. Data Types

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

Introduction to Programming

Chapter Five: Functions. by Cay Horstmann Copyright 2018 by John Wiley & Sons. All rights reserved

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each):

5. Assuming gooddata is a Boolean variable, the following two tests are logically equivalent. if (gooddata == false) if (!

Getting started with C++ (Part 2)

Lab Instructor : Jean Lai

CSc Introduction to Computing

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

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

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

Understanding main() function Input/Output Streams

The following expression causes a divide by zero error:

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

Exception with arguments

CHAPTER 4 FUNCTIONS. 4.1 Introduction

Chapter 3 - Functions

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

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

EECS402 Lecture 02. Functions. Function Prototype

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Functions. A function is a subprogram that performs a specific task. Functions you know: cout << Hi ; cin >> number;

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.

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

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

UNIT- 3 Introduction to C++

CMSC 202 Midterm Exam 1 Fall 2015

Arithmetic Operators. Binary Arithmetic Operators. Arithmetic Operators. A Closer Look at the / Operator. A Closer Look at the % Operator

Unit 6. Thinking with Functions

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

Chapter 1 INTRODUCTION

Computer Science II Lecture 1 Introduction and Background

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

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

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

Sample Final Exam. 1) (24 points) Show what is printed by the following segments of code (assume all appropriate header files, etc.

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

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

Chapter 2: Introduction to C++

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

CS2255 HOMEWORK #1 Fall 2012

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

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

Lab # 02. Basic Elements of C++ _ Part1

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

C++ Programming Lecture 1 Software Engineering Group

VARIABLES & ASSIGNMENTS

1. In C++, reserved words are the same as predefined identifiers. a. True

Lecture 3 Tao Wang 1

CHAPTER 3 BASIC INSTRUCTION OF C++

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

1) You want to determine whether time has run out. The following code correctly implements this:

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Local and Global Variables

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

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:

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Arrays in C++ Instructor: Andy Abreu

1st Midterm Exam: Solution COEN 243: Programming Methodology I

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

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Lecture 2 Tao Wang 1

6.1. Chapter 6: What Is A Function? Why Functions? Introduction to Functions

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

CSc Introduc/on to Compu/ng. Lecture 8 Edgardo Molina Fall 2011 City College of New York

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

Introduction to Programming

Complex data types Structures Defined types Structures and functions Structures and pointers (Very) brief introduction to the STL

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

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy

Global & Local Identifiers

The C++ Language. Arizona State University 1

The American University in Cairo Department of Computer Science & Engineeringt CSCI &09 Dr. KHALIL Exam-I Fall 2009

CS 007A Midterm 1 Practice Chapters 1 5

Objectives. In this chapter, you will:

C++ Support Classes (Data and Variables)

C++ Programming Lecture 11 Functions Part I

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

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

Input And Output of C++

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

Chapter 2 Basic Elements of C++

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

BITG 1113: Function (Part 2) LECTURE 5

Computer Programming C++ Classes and Objects 6 th Lecture

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

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

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:

Unit 7. Functions. Need of User Defined Functions

A SHORT COURSE ON C++

Chapter 4 - Notes Control Structures I (Selection)

Creating a C++ Program

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

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

Transcription:

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004 Functions and Program Structure Today we will be learning about functions. You should already have an idea of their uses. Cout and cin are both examples of functions. In general, functions perform a number of pre-defined commands to accomplish something productive. Functions that a programmer writes will generally require a prototype. Like a blueprint, the prototype tells the compiler what output value (if any) the function will return, what the function will be called, as well as what arguments (or inputs) the function can be passed (if any). Functions have many uses. For example, a programmer may have a block of code that he has repeated forty times throughout the program. A function to execute that code would save a great deal of space; and, it would make the program more readable. Another reason to use functions is to break down a complex program into more manageable pieces. For example, take a menu program that runs complex code when a menu choice is selected. The program would probably best be served by making functions for each menu choice, and then breaking down the complex tasks into smaller, more manageable ones, which could in turn be their own functions. In this way, a program can be designed that makes sense when it is read. Why use functions? Code re-use Divide and Conquer, i.e., By decomposing a program into functions, we can divide the work among several programmers Clarify the program by keeping details out of the main program Each function solves a part of the problem Can change one function without changing other parts of the program We can test one function separately from the rest For example, #include < cmath > int a, base = 4, exp = 2; a = pow(base, exp); // sets a = 4^2 = 16 pow is the function name. The values of base and exp (i.e., the arguments) are passed to the pow function. 1

The function prototype (syntax) ftype fname(type1 param1, type2 param2,, typen paramn) local variable declarations executable statements return (exprn); ftype: The data type returned. If ftype = void, then the function does not return a value. fname: The function s name. (type1 param1, ): In parentheses, a list of parameters and their types separated by commas. Use void here if the function has no parameters. You can call or invoke a function. To do so, you may need to pass arguments. These arguments are evaluated, and their values are passed to the invoked function. The function parameters catch this information (i.e., these argument values) and use them to calculate and return a value. #include <iostream> using namespace std; int mult (int x, int y); // This prototype specifies that the function mult will accept 2 // arguments (both integers), and that it will return an integer. // The trailing semicolon indicates that this is a function declaration // Without the semicolon, the compiler will think you are actually // trying to write the definition of the function here. int main() int x, y; cout << Please input two numbers to be multiplied: cin >> x >> y; cout << The product of your two numbers is << mult(x, y); return 0; int mult (int x, int y) return x*y; // When you actually define the function, you begin with the same // prototype from above, MINUS the semicolon. Then there should // always be a brace before and after the code (just like main) // this function returns the value x*y 2

Notice how cout actually outputs what appears to be the mult function. What s really happening is that mult acts as a variable. Because this function returns a value, it s possible for the cout function to output the returned value. The mult function is defined below main. Because its prototype is above main, the compiler recognizes it as being defined. Hence, you will not get any errors about mult being undefined, even though its definition is below where it is used. Find the larger of two numbers. double bigger (double n1, double n2) double larger; // local variable declaration if (n1 > n2) larger = n1; else larger = n2; return (larger); Compute the factorial (n! = n factorial = n*(n-1)*(n-2)* * 2 * 1 ). int factorial (int n) int i; // local variable product = 1; for (i = n; i>1; i--) product *= i; return (product); Function Declarations A function declaration is terminated by a semicolon. int function1 (type1 param1, type 2 param2, ); int function1 (type1 param1, type 2 param2, ) // function DECLARATION // function DEFINITION The declaration of a function f1 must occur outside all other functions and before the first function that invokes f1 OR inside each function that invokes f1. A function declaration inside a function f2 serves as a declaration ONLY for f2. 3

The following program reads a midterm grade, final grade, and a weight; computes the weighted average, and assigns a course grade. #include <iostream> using namespace std; char grade (int exam1, int exam2, float exam1_weight); main() int ans, mid_term, final; float weight; char letter_grade; do cout << endl << Compute another grade (1 = Yes, 0 = No)? << endl; cin >> ans; if (ans == 1) cout << endl << Enter midterm, final, weight: << endl; cin >> mid_term>> final >> weight; letter_grade = grade (mid_term, final, weight); // calls/invokes function grade cout << Grade is: << letter_grade << endl; while (ans == 1); char grade (int exam1, int exam2, float exam1_weight) float average; // local variable average = exam1_weight * exam1 + (1.0 exam1_weight) * exam2; if (average > 7.0) return P ; else return F ; The main function This is where the flow begins, i.e., the program starts here. Execution never begins in a function; a function must be invoked or called. main usually invokes other functions. Some functions can invoke other functions. The program as a whole terminates when main does. 4

The return statement A function always returns to its invoker. When a function is invoked, the statements in its body begin executing until either a return statement or the last statement in its body is executed. If the function does not return a value, the return statement is optional. But if used, it can be written: return; return void; return (void); // all 3 statements are correct if no value is returned Return is the keyword used to force the function to return a value. A function that returns a value must have at least one return statement, which is written: return exprn; return (exprn); return 25 + num*3; return (25 + num*3); Arguments and parameters Arguments are enclosed in parenthesis and separated by commas if there are more than one. Arguments must match the parameters in number, data type, and order. (i.e., when you call a function, you must enter the correct number of arguments of the correct type listed in the order designated by the prototype). The value of the arguments represent information passed from the invoking function to the invoked function. When a function is invoked, all the functions arguments are evaluated before the control is passed to the invoked function. However, C++ does NOT guarantee the order of evaluation of the arguments. int num1 = 5; void fun (int i, int j); fun (++num1, ++num1); // declare function fun // invoke function fun The values passed to the function could be fun (6, 7) or fun (7, 6)??? 5