CS 144 Advanced C++ Programming January 31 Class Meeting

Slides:



Advertisements
Similar presentations
Modular Programming With Functions
Advertisements

1 ICS103 Programming in C Lecture 5: Introduction to Functions.
Functions Most useful programs are much larger than the programs that we have considered so far. To make large programs manageable, programmers modularize.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Computer Programming and Basic Software Engineering 4. Basic Software Engineering 1 Writing a Good Program 4. Basic Software Engineering 3 October 2007.
CS 201 Functions Debzani Deb.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Programming in C++ Language ( ) Lecture 5: Functions-Part1 Dr. Lubna Badri.
CPS120: Introduction to Computer Science Functions.
CPS120: Introduction to Computer Science Lecture 14 Functions.
CS221 Random Numbers. Random numbers are often very important in programming Suppose you are writing a program to play the game of roulette The numbers.
Modular Programming ELEC 206 Computer Applications for Electrical Engineers Dr. Ron Hayne.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a.
L what are predefined functions? l what is? n function name n argument(s) n return value n function call n function invocation n nested function call l.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 3: User-Defined Functions I
Think First, Code Second Understand the problem Work out step by step procedure for solving the problem (algorithm) top down design and stepwise refinement.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 4 Functions.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
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.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 23, 2005 Lecture Number: 11.
Methods.
Chapter 9: Value-Returning Functions
Chapter Topics The Basics of a C++ Program Data Types
User-Written Functions
Chapter 6: User-Defined Functions I
Chapter 6 CS 3370 – C++ Functions.
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Procedural Abstraction and Functions That Return a Value
Predefined Functions Revisited
C++ Programming: CS150 For.
Basic Elements of C++.
Iterative Constructs Review
Chapter 5 Function Basics
CMPT 201 Functions.
CSC113: Computer Programming (Theory = 03, Lab = 01)
CSCI 161: Introduction to Programming Function
CMPE Data Structures and Algorithms in C++ February 22 Class Meeting
Chapter 5 - Functions Outline 5.1 Introduction
User-Defined Functions
Basic Elements of C++ Chapter 2.
Chapter 5 - Functions Outline 5.1 Introduction
CMPE 180A Data Structures and Algorithms in C++ February 1 Class Meeting Department of Computer Engineering San Jose State University Spring 2018 Instructor:
توابع در C++ قسمت اول اصول كامپيوتر 1.
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.
6 Chapter Functions.
Iterative Constructs Review
Computing Fundamentals
Chapter 6: User-Defined Functions I
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
Function.
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Predefined Functions Revisited
Functions Imran Rashid CTO at ManiWeber Technologies.
C++ Programming Basics
CS 144 Advanced C++ Programming February 21 Class Meeting
6 Functions.
Instructor: Hidayah Elias Course: COMPUTER PROGRAMMING (BFC 2042)
Standard Version of Starting Out with C++, 4th Edition
 A function is a named sequence of statement(s) that performs a computation. It contains  line of code(s) that are executed sequentially from top.
Programming Fundamental
Presentation transcript:

CS 144 Advanced C++ Programming January 31 Class Meeting Department of Computer Engineering San Jose State University Spring 2019 Instructor: Ron Mak www.cs.sjsu.edu/~mak

Predefined Functions C++ includes predefined functions. AKA “built-in” functions Example: Math function sqrt Predefined functions are stored in libraries. Your program will need to include the appropriate library header files to enable the compiler to recognize the names of the predefined functions. Example: #include <cmath> in order to use predefined math functions like sqrt

Predefined Functions, cont’d

Random Numbers To generate (pseudo-) random numbers using the predefined functions, first include two library header files: “Seed” the random number generator: If you don’t seed, you’ll always get the same “random” sequence (which may be useful for debugging). #include <cstdlib> #include <ctime> srand(time(0));

Random Numbers, cont’d Each subsequent call returns a “random” number ≥ 0 and ≤ RAND_MAX. RAND_MAX is library-dependent but is guaranteed to be at least 32,767. Use + and % to scale to a desired number range. Example: Each execution of the expression returns a random number with the value 1, 2, 3, 4, 5, or 6. rand(); rand()%6 + 1

Type Casting Suppose integer variables i and j are initialized to 5 and 2, respectively. What is the value of the division i/j ? What if we wanted to have a quotient of type double? We want to keep the fraction.

Type Casting, cont’d One way is to convert one of the operands to double. Then the quotient will be type double. Why won’t the following work? double quotient = static_cast<double>(i)/j; double quotient = static_cast<double>(i/j);

Programmer-Defined Functions In addition to using the predefined functions, you can write your own functions. Programmer-defined functions are critical for good program design. In your C++ program, you can call a programmer-defined function only after the function has been declared or defined.

Function Declarations A function declaration specifies: The function name. The number, order, and data types of its formal parameters. The data type of its return value. Example: double total_cost(double unit_cost, int count);

Function Definitions After you’ve declared a function, you must define it. Write the code that is executed whenever the function is called. A return statement terminates execution of the function and returns a value to the caller. Example: double total_cost(double unit_cost, int count) { double total = count*unit_cost; return total; }

Function Calls Call a function that you wrote just as you would call a predefined function. Example: int how_many; double how_much; double spent; how_many = 5; how_much = 29.99; spent = total_cost(how_much, how_many);

Void Functions A void function performs some task but does not return a value. Therefore, its return statement terminates the function execution but does not include a value. A return statement is not necessary for a void function if the function terminates “naturally” after it finishes executing the last statement. Example void function definition: void print_TF(bool b) { if (b) cout << "T"; else cout << "F"; }

Void Functions, cont’d A call to a void function cannot be part of an expression, since the function doesn’t return a value. Instead, call a void function as a statement by itself. Example: bool flag = true; print_TF(flag);

Coding Convention with Functions First declare all your functions. Document each declaration with a comment that describes: What the function does. What is each function parameter. What is the return value. Define the main function. Define the functions. Now you only need to document each function’s internal operations.

Coding Convention with Functions, cont’d #include <iostream> using namespace std; /**  * Add two integers and return their sum.  * @param n1 the first integer  * @param n2 the second integer  * @return their sum.  */ int make_sum(int n1, int n2);  * Print an integer value;  * @param n the value to print. void print(int n); int main() {     int i = 5, j = 7;     int sum = make_sum(i, j);     print(sum); } The declarations tell you what the functions will do and provide the overall structure of the program without all the details. int make_sum(int n1, int n2) {     return n1 + n2;  // return their sum } void print(int n)     cout << "The value is " << n << endl;

Top-Down Design Top-down design is an important software engineering principle. Start with the “topmost subproblem” of a programming problem. Write a function that solves the topmost subproblem. Break each subproblem into smaller subproblems. Write a function that solves each subproblem. This process is called stepwise refinement.

Top-Down Design, cont’d The result is a hierarchical decomposition of the problem. AKA functional decomposition

Top-Down Design Example Write a program that inputs positive integer values up to 999,999 from the user and translates each value into words. Example: The user enters 482 The program writes “four hundred eighty-two” Repeat until the user enters a value ≤ 0.

Top-Down Design Example, cont’d What is the topmost problem? Read numbers entered by the user until the user enters a value ≤ 0. Translate each number to words. This is a high-level description of what the program is supposed to do.

Refinement 1 Loop to read and print the numbers. Call a translate function, but it doesn’t do anything yet.

Refinement 2 How to translate a number into words? Break the number into separate digits. Translate the digits into words such as one, two, ..., ten, eleven, twelve, ..., twenty, thirty, etc. Refine the translate function to handle some simple cases: Translate_ones: 1 through 9 Translate_teens: 11 through 19 These functions each returns one word.

Refinement 3 The translate function takes a 3-digit number and separates out the hundreds digit. Translate the hundreds digit. Translate_hundreds Do this simply by translating a hundreds digit as we did a ones digit, and append the word hundred.

Refinement 3, cont’d Translate the last two digits: We can already translate a teens number. Otherwise, break apart the two digits into a tens digit and a ones digit. Translate_tens: 10, 20, 30, ..., 90 We can already translate a ones digit.

Refinement 4 Add a hyphen between twenty, thirty, etc. and a ones word.

Refinement 5 Break a 6-digit number into a 3-digit first part and a 3-digit second part. Translate the first part and append the word thousand. Translate the second part.

Scope and Local Variables Any variable declared inside a function is local to that function. The scope of the variable is that function. Scope refers to the part of the program where the variable is accessible. The variable is not accessible from outside the function. A variable with the same name declared inside another function is a different variable. The same is true for any variable declared inside the main function.

Block Scope You can declare variables inside of a block. A block of code is delimited by { and }. The variables are local to the block. Example: if (x < y) { int i; ... }

Global Constants and Variables If a constant or a variable is declared outside of and before the main and the function definitions, then that constant or variable is global, and it is accessible by the main and any function. Global variables are not recommended. If a function modifies a global variable, that can affect other functions. Such “side effects” of a function can make a program error-prone and difficult to maintain.