A Computer Science Tapestry 1 Announcements l Midterm 1 is on November 25, 2006, 10:40 – 12:20 l Homework 3 is due November 8, 2006, 21:00 ä Robot application.

Slides:



Advertisements
Similar presentations
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Advertisements

CS201 – Introduction to Computing – Sabancı University 1 First Midterm Exam l November 22, 2008, Saturday, 10:40 – 12:20, max 100 minutes l One A4 size.
Chapter 10.
Computer Science 1620 Loops.
Chapter 6: User-Defined Functions I
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
CS31: Introduction to Computer Science I Discussion 1A 4/2/2010 Sungwon Yang
1 September 6, 2005CS150 Introduction to Computer Science I What Actions Do We Have Part 1 CS150 Introduction to Computer Science I.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
Admin Office hours 2:45-3:15 today due to department meeting if you change addresses during the semester, please unsubscribe the old one from the.
Section 2 - More Basics. The char Data Type Data type of a single character Example char letter; letter = 'C';
Agenda Review Compiling Review Data Types Integer Division Composition C++ Mathematical Functions User Input Reading: , 8.11 Homework #3.
Computer Science 1000 Spreadsheets II Permission to redistribute these slides is strictly prohibited without permission.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
A Computer Science Tapestry 4.1 Control, Functions, Classes We’ve used built-in types like int and double as well as the standard class string and the.
CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
CSE 131 Computer Science 1 Module 1: (basics of Java)
Announcements Final NEXT WEEK (August 13 th Thursday at 16:00) Recitations will be held on August 12 th Wednesday We will solve sample final questions.
Summary of what we learned yesterday Basics of C++ Format of a program Syntax of literals, keywords, symbols, variables Simple data types and arithmetic.
CPS120: Introduction to Computer Science Decision Making in Programs.
USER-DEFINED FUNCTIONS. STANDARD (PREDEFINED) FUNCTIONS  In college algebra a function is defined as a rule or correspondence between values called the.
Current Assignments Homework 2 is available and is due in three days (June 19th). Project 1 due in 6 days (June 23 rd ) Write a binomial root solver using.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
C++ Basics C++ is a high-level, general purpose, object-oriented programming language.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 6 User-Defined Functions I. Objectives Standard (predefined) functions What are they, and How to use them User-Defined Functions Value returning.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
CS Class 08 Today  Exercises  Nested loops  for statement  Built-in functions Announcements  Homework #3, group solution to in-class.
Control Structures (B) Topics to cover here: Sequencing in C++ language.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
Functions Overview Functions are sequence of statements with its own local variables supports modularity, reduces code duplication Data transfer between.
String Class. C-style and C++ string Classes C-style strings, called C-strings, consist of characters stored in an array ( we’ll look at them later) C++
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
String Class Mohamed Shehata 1020: Introduction to Programming.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
CS Class 19 Today  Practice with classes Announcements  Turn in algorithm for Project 5 in class today  Project 5 due 11/11 by midnight – .
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 3: User-Defined Functions I
Selection Executing Statements Selectively. Review We’ve seen that the C++ if statement permits a Statement to be executed selectively: if (Expression)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Intro to Classes via the C++ String Class November 18, 2002 CSE103 - Penn State University Online at
Fundamental Programming Fundamental Programming More Expressions and Data Types.
CS201 Introduction to Sabancı University 1 Chapter 2 Writing and Understanding C++ l Writing programs in any language requires understanding.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
A Computer Science Tapestry 4.1 Control, Functions, Classes We’ve used built-in types like int and double as well as the standard class string and the.
Announcements HW2 is due on Wednesday this week. HW3 will be assigned this week, will be due next week.
Announcements Midterm2 on April 18 th Monday at 19:40 This week recitations, we will solve sample midterm questions. I will also send previous years’ exams.
Chapter 7 User-Defined Methods.
User-Defined Functions
Announcements 2nd homework is due this week Wednesday (October 18)
Announcements General rules about homeworks
Announcements General rules about homeworks
Summary of what we learned so far
Programming Funamental slides
Announcements 3rd homework is due this week Wednesday (March 15)
Announcements Homework 1 will be assigned this week,
Chapter 6: User-Defined Functions I
Summary of what we learned yesterday
Introduction to Computer Science
Announcements General rules about homeworks
Announcements HW1 is due TODAY.
Presentation transcript:

A Computer Science Tapestry 1 Announcements l Midterm 1 is on November 25, 2006, 10:40 – 12:20 l Homework 3 is due November 8, 2006, 21:00 ä Robot application. I hope you attended recitations before the week. ä Be careful where and how you create the robots Each robot must be created only once within the main Examine example robot programs of previous week recitations ä Scope rules say that each identifier can be used only in the compound block in which it is declared If you receive an “undeclared identifier” error for robots even you declare them, check where you declare and use them! ä One mistake in the sample exe and another mistake in the pdf file are corrected and webct is updated

A Computer Science Tapestry 2 In this ppt file l Mostly Sections 4.5 and 4.6 ä Functions that return values ä math library functions ä string as a class string constructors string member functions and string processing ä date class (4.6.3) will be covered later

A Computer Science Tapestry 3 Functions that return values Functions we’ve written so far are void functions ä They do some job and returns back, but without a value ä Parameters are used for one-way data transfer into the function to be called ä What can you do to transfer a computed value out of a function? to the main program or to other function (whatever the caller one) ä Parameters that we have seen and used until now are not enough  Void function call is not used in an expression, i.e. no value is associated with a void function Head(); DoThat(); Verse("cow", "moo"); l Non-void functions can return values of any type ä function call becomes an expression when the function finishes, the function call is replaced by the returned value

A Computer Science Tapestry 4 Functions that return values Example (see area_func_return.cpp): suppose circlearea function takes the radius as parameter and returns the area. In the program we call circlearea as an expression (you have to use the returned value somewhere) area = circlearea(r); cout << circlearea(12) << endl; if (circlearea(r/2) >= 100) cout << “large circle” << endl; circlearea(r); // syntax ok, but meaningless function call // returned value is not used

A Computer Science Tapestry 5 Math library functions l Mathematical functions like square root, logarithm, sin, cos, etc. l prototypes in header file cmath #include l Full list is in page 758 (Table F.1) – partial list is in table 4.5.  correction in Table F.1: int abs (int x) l Note them on your cheat-sheet for the exam Example use of function sqrt ä see usemath.cpp  how did we use sqrt function? in cout as an expression  could we use sqrt in assignment? How? yes, let’s do it.  what happens if value is negative? try and see! we can add some if statements to display an error message in case of negative value

A Computer Science Tapestry 6 Anatomy of a function Function to calculate volume of a sphere double SphereVol (double radius) { return 4.0*radius*radius*radius*acos(-1)/3; } l Function heading/prototype shows return type.  return type can be any type (incl. string )  theoretically return type may be Robot too, but in practice Robot class is not designed to be used as the return type you do not see any syntax error, but execution may be problematic. So do not return a Robot from a function l Function body may have several statements in it return statement is used to determine the value returned from function, so the expression after it must be of the return type  Function body should include at least one return statement  The return statement causes the function to exit immediately and to return the value after return  A function can have more than one return statements, but only one is executed when the function is called (see next example) return type function name function body parameters

A Computer Science Tapestry 7 Functions can return strings string WeekDay(int day) // precondition: 0<= day <= 6 // postcondition: return "Sunday" for 0, // "Monday" for 1, … "Saturday" for 6 { if (0 == day) return "Sunday"; else if (1 == day) return "Monday"; else if (2 == day) return "Tuesday"; else if (3 == day) return "Wednesday"; else if (4 == day) return "Thursday"; else if (5 == day) return "Friday"; else if (6 == day) return "Saturday"; } l A program piece that uses that function string dayName; int dayNum; cout << " enter day (0-6): " ; cin >> dayNum; dayName = WeekDay(dayNum); Which is/are correct use of WeekDay function? Why? cout << WeekDay(5)<< endl; int j = WeekDay(0); cout << WeekDay(2.1)<< endl; string s = WeekDay(22); WeekDay(3);

A Computer Science Tapestry 8 Function documentation l Functions usually have a precondition ä What properties (e.g., of parameters) must be true for function to work as intended? ä If there are no parameters, sometimes no precondition ä Some functions work for every parameter value no precondition l Functions always have a postcondition ä If precondition is satisfied what does the function do? What does the function return?

A Computer Science Tapestry 9 Example – Compare cost of pizza sizes l Problem: Calculate and compare price per square inch of large and small size pizzas l Solution  a function, say cost, that takes the pizza radius and price as parameters and returns price per square inch  In the main() input radiuses and prices of large and small pizzas calculate the per square inch costs by calling the cost function display the results on screen compare the unit costs to find out which one is best value l See pizza2.cpp

A Computer Science Tapestry 10 Example - When is a year a leap year? l Every year divisible by four is a leap year ä Except years divisible by 100 are not Except years divisible by 400 are l Alternatively: ä Every year divisible by 400 is a leap year ä Otherwise, years divisible by 100 are not leap years ä Otherwise, years divisible by 4 are leap years ä Otherwise, not a leap year l Boolean function bool IsLeapYear(int year); // pre: year > 0 // post: return true if year is a leap year

A Computer Science Tapestry 11 Implementation and use of leap year function bool IsLeapYear(int year) // precondition: year > 0 // postcondition: returns true if year is a leap year, else returns false { if (year % 400 == 0) // divisible by 400 { return true; } else if (year % 100 == 0) // divisible by 100 { return false; } else if (year % 4 == 0) // divisible by 4 { return true; } return false; } int main() { int year; cout << "enter a year "; cin >> year; if (IsLeapYear(year)) { cout << year << " has 366 days, it is a leap year" << endl; } else { cout << year << " has 365 days, it is NOT a leap year" << endl; } return 0; } See isleap.cpp

A Computer Science Tapestry 12 There’s more than one way l No if/else necessary in the function body bool IsLeapYear(int year) // precondition: year > 0 // post: return true if year is a leap year { return ( year % 400 == 0 ) || ( year % 4 == 0 && year % 100 != 0); } l How does this work? l Is this version more efficient? l Are these two versions different from user perspective?

A Computer Science Tapestry 13 Functions that return values from the Robot Class l Robot class has several member functions ä Move, TurnRight and SetColor are void functions ä Robot class also has member functions that return values. Some are below. bool Blocked () ä is the robot blocked? bool FacingEast () ä Is the robot facing east? l See RobotWorld.pdf file for the complete list of those functions.

A Computer Science Tapestry 14 Free functions and member functions The functions in are free functions, they aren’t part of a class ä C++ is a hybrid language, some functions belong to a class, others do not ä Java is a pure object-oriented language, every function belongs to a class Similarly, IsLeapYear is also free function l Actually any function that does not operate on an object is free functions However, Move, TurnRight are functions for Robots class ä they are not free, they operate on robots only ä that is why they are called member functions

A Computer Science Tapestry 15 string as a class string is a class ä String variables are objects, they’re instances of the class ä A class is a collection having members that have common attributes strings share some properties, but have different values l A string is a sequence of characters ä first char is at position 0 first index is 0 ä last valid index (position of the last character): string’s length -1 l Constructors ä without initialization string mystr, s; ä with initialization string s = " Hello World " ; string otherstring = s; or string otherstring(s); ä You may use functions and operators that return strings in initialization string s = " Hello " + " World " //concatenation operator

A Computer Science Tapestry 16 string member functions The function length() returns the number of characters string s = "hello"; int len = s.length(); // value of len is 5 s = "";// s is null string len = s.length(); // value of len is 0 l Member functions are applied to objects using dot notation ä Cannot use length() without an object to apply it to  Not valid int x = length(s);  Not valid int x = string.length()  Valid? double y = sqrt(s.length());

A Computer Science Tapestry 17 string member functions int length() // postcondition: returns the number of characters string substr(int pos, int len) // precondition: 0 <= pos, and pos < length of the string object // postcondition: returns substring of len characters beginning at position // pos. Returns as many characters as possible if len is too large, but // causes error if pos is out of range (>= length of the string object) int find(string s) // postcondition: returns first position/index at which substring s begins in // string object– returns string::npos if s does not occur l More details in “how to C” in Tapestry

A Computer Science Tapestry 18 Extracting substrings A substring is part of a string, substrings can be extracted from a string using member function substr string s = "theater"; int len = s.length(); // value of len is 7 string t = s.substr(0,3); // t is "the", s is “theater” t = s.substr(1,4); // t is now “heat” s = s.substr(3,3); // s is “ate” t is still “heat” s = “cinema”; t = s.substr(4,8); // t is “ma” t = s.substr(8,2); // run-time error See strdemo.cpp which is a sample program that uses length and substr functions

A Computer Science Tapestry 19 Finding substrings within strings: find and rfind String member function find looks for an occurrence of one string (which is a parameter) in another (which is the object string), returns position of start of first occurrence  If no occurrence, then string::npos is returned largest unsigned integer (4,294,967,295) string s = "I am the eggman, he is too"; int k = s.find("I"); // k is 0 k = s.find("he"); // k is 6 k = s.find("egg"); // k is 9 k = s.find("a"); // k is 2 cout << s.find("cat"); // output is k = s.find("cat"); // k is –1 since it is signed rfind is same as find, but searches backwards, returns the last occurrence k = s.rfind("he"); // k is 17 k = s.rfind("egg"); // k is 9 See strfind.cpp which is a sample program on find function

A Computer Science Tapestry 20 More on strings l You can append one string to the end of another  using operator + string s = "cs201"; s = s + " is easy"; // s is now "cs201 is easy" You can change or extract one character of a string using at member function ä parameter of at must be between 0 and string’s length - 1, otherwise a run-time error occurs string s = "Hello World"; s.at(4) = '!'; // s is now "Hell! World" cout << s.at(1); // displays e on screen s.at(20) = 'a'; //run-time error

A Computer Science Tapestry 21 More on strings l We already know how to compare strings l See “How to C” insert and replace functions l String functions and operators we have seen so far are from standard C++ library l Tapestry also has some classes and utility functions ä we will see and use them in time l strutils.h and strutils.cpp ä Tapestry string utilities ä include strutils.h at the beginning of the program ä add strutils.cpp to your project ä see “How to G” (page 776)

A Computer Science Tapestry 22 Example (See stringremove.cpp) l Write a function that takes two string parameters (say s1 and s2). Function removes first occurrence of s2 in s1 and returns the resulting string. ä In the main program, test the function by removing some input strings from “Today is Monday” string remove(string s1, string s2) // post: removes first occurrence of s2 from s1 and returns the // resulting string. Returns s1 if s2 does not occur any. { unsigned int location; location = s1.find(s2); if (location != string::npos) { return s1.substr(0, location) + s1.substr(location+s2.length(), s1.length()); } return s1; }

A Computer Science Tapestry 23 The class Date l A Tapestry class l we will see later