Programming Abstractions

Slides:



Advertisements
Similar presentations
Chapter 10.
Advertisements

1 10/25/06CS150 Introduction to Computer Science 1 Reading from and Writing to Files.
CSE 332: C++ program structure and development environment C++ Program Structure (and tools) Today we’ll talk generally about C++ development (plus a few.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
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.
Working with Strings Lecture 2 Hartmut Kaiser
By Noorez Kassam Welcome to JNI. Why use JNI ? 1. You already have significantly large and tricky code written in another language and you would rather.
Creating your first C++ program
CS 106X – Programming Abstractions in C++ Cynthia Bailey Lee CS2 in C++ Peer Instruction Materials by Cynthia Bailey Lee is licensed under a Creative Commons.
3. The Nuts and Bolts of C++ Computer Programming 3. The Nuts and Bolts of C++ 1 Learning the C++ language 3. The Nuts and Bolts of C++
CPS120: Introduction to Computer Science Decision Making in Programs.
CPS120: Introduction to Computer Science Functions.
Chapter 0 Getting Started. Objectives Understand the basic structure of a C++ program including: – Comments – Preprocessor instructions – Main function.
TEXT FILES. CIN / COUT REVIEW  We are able to read data from the same line or multiple lines during successive calls.  Remember that the extraction.
Programming Abstractions Cynthia Lee CS106X. Today’s Topics Introducing C++ from the Java Programmer’s Perspective  Absolute value example, continued.
1 Cannon_Chapter9 Strings and the string Class. 2 Overview  Standards for Strings  String Declarations and Assignment  I/O with string Variables 
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Fundamental Programming Fundamental Programming Introduction to Functions.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
Programming Abstractions Cynthia Lee CS106B. Today’s Topics Introducing C++ from the Java Programmer’s Perspective  C++ strings and streams, continued.
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.
Strings. Using strings as abstract value A string is a sequence of characters e.g. “Hello, World!” Early version of C++ followed the older C language.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Week 13 - Friday.  What did we talk about last time?  Server communications on a socket  Function pointers.
STRUCTURED PROGRAMMING Complete C++ Program. Content 2  Main Function  Preprocessor directives  User comments  Escape characters  cout statement.
Lecture 3: Getting Started & Input / Output (I/O)
C++ First Steps.
Great way to learn is by example so fire up Visual Studios C (at home make sure you custom install with C++ - no longer default) by Deborah R. Fowler.
Introduction to C++ (Extensions to C)
Topic Pre-processor cout To output a message.
Chapter 1.2 Introduction to C++ Programming
Programming Abstractions
Computing and Statistical Data Analysis Lecture 2
Completing the Problem-Solving Process
Introduction to C++ Systems Programming.
Programming Abstractions
Working with Strings Lecture 2 Hartmut Kaiser
CompSci 230 Software Construction
Programming Abstractions in C++, Chapter 3 - 4
C++ Strings References: :" iomanip, sstream.
Programming Abstractions
Object Oriented Programming COP3330 / CGS5409
Programming Abstractions
Introduction to C++ Programming
Announcements General rules about homeworks
Announcements General rules about homeworks
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.
Learning Objectives String Class.
Working with Strings Lecture 2 Hartmut Kaiser
Building Java Programs
We’re moving on to more recap from other programming languages
Building Java Programs
Representation and Manipulation
Computing Fundamentals
CS150 Introduction to Computer Science 1
Announcements Homework 1 will be assigned this week,
C++ Programming Lecture 3 C++ Basics – Part I
A First Program.
COMS 261 Computer Science I
Reading from and Writing to Files
Announcements General rules about homeworks
Using string type variables
Std Library of C++.
Today’s Objectives 28-Jun-2006 Announcements
CS31 Discussion 1D Winter19: week 4
Introduction to Programming - 1
Chapter 1 c++ structure C++ Input / Output
Lecture 3 More on Flow Control, More on Functions,
Reading from and Writing to Files
Introduction to Classes and Objects
Presentation transcript:

Programming Abstractions CS106X Cynthia Lee

Today’s Topics Introducing C++ from the Java Programmer’s Perspective firstprogram.cpp Function prototypes <iostream> and cout "simpio.h" and getLine() Absolute value example C++ strings and streams

C++ from the Java Programmer’s Perspective (But it’s ok if you don’t know java!)

A first C++ program (Error) firstprogram.cpp #include <iostream> #include "console.h" using namespace std; int main(){ cout << "|-5| = " << absoluteValue(-5) << endl; return 0; } int absoluteValue(int n) { if (n<0){ return -n; return n; You don’t know what automata is, do you? SOON! -- firstprogram.cpp : unlike java, filename doesn’t have to match class! In fact, don’t need a class! -- instead of "import" we have "#include" – note some have "" some have <> -- .h extension means "header" interface information as opposed to .cpp for implementation code -- "using namespace" just don’t worry about why and use it (saves having to do ::) -- main returns type int, just return zero if everything went ok (ignore why) -- we use cout instead of System.out.println(), endl puts a newline

A first C++ program (Fixed #1) firstprogram.cpp #include <iostream> #include "console.h" using namespace std; int absoluteValue(int n) { if (n<0){ return -n; } return n; int main(){ cout << "|-5| = " << absoluteValue(-5) << endl; return 0; You don’t know what automata is, do you? SOON! -- firstprogram.cpp : unlike java, filename doesn’t have to match class! In fact, don’t need a class! -- instead of "import" we have "#include" – note some have "" some have <> -- .h extension means "header" interface information as opposed to .cpp for implementation code -- "using namespace" just don’t worry about why and use it (saves having to do ::) -- main returns type int, just return zero if everything went ok (ignore why) -- we use cout instead of System.out.println(), endl puts a newline

A first C++ program (Fixed #2) firstprogram.cpp #include <iostream> #include "console.h" using namespace std; int absoluteValue(int n); int main(){ cout << "|-5| = " << absoluteValue(-5) << endl; return 0; } int absoluteValue(int n) { if (n<0){ return -n; return n; You don’t know what automata is, do you? SOON! -- firstprogram.cpp : unlike java, filename doesn’t have to match class! In fact, don’t need a class! -- instead of "import" we have "#include" – note some have "" some have <> -- .h extension means "header" interface information as opposed to .cpp for implementation code -- "using namespace" just don’t worry about why and use it (saves having to do ::) -- main returns type int, just return zero if everything went ok (ignore why) -- we use cout instead of System.out.println(), endl puts a newline

Design Question: Why does C++ have the function prototype syntax? In other words, why not just have a rule that you must set up the ordering so you define your functions before using them, as in the "FIXED 1" example? C++ could have done that, but such a rule would be too cumbersome for programmers to follow. C++ could have done that, but good programming style dictates "top-down" approach that logically puts main() first and helper functions it calls to follow. C++ could not have done that, because sometimes there is no way to order the functions so that all functions are defined before being used. Other/none/more than one of the above

Design Question: Why does C++ have the function prototype syntax? (A) and (B) The rationales behind choices (A) and (B) (previous slide) are correct May or may not have been enough to compel the language designers to introduce the function prototype feature (C) is true—there are cases where you simply cannot rearrange the ordering of functions to avoid all cases of use before definition e.g., mutual recursion

Which came first, the chicken or the egg Which came first, the chicken or the egg? (this code is just for fun, for now—we’ll cover recursion in depth in a few weeks!) #include<iostream> #include "console.h" using namespace std; void go(int n); void stanford(int n); int main(){ int n = 5; go(n); return 0; } void go(int n) { if (n == 0) return; cout << "Go!" << endl; stanford(n-1); void stanford(int n) { cout << "Stanford!" << endl;

Go Stanford Modifications Code Demo: What did we just see? You can read in input with: cin (<iostream>) getInteger(), getLine(), etc (“simpio.h”) You can use getLine() as a way of pausing the program to wait for you to hit Enter before exiting (so you can see what happened!) (depending on operating system and Qt configuration, may not be necessary) cin and cout use the >> and << operators, respectively Remember: the arrows point in the way the data is “flowing” These aren’t like HTML tags <b> or Java/C++ parentheses () or curly braces {} in that they don’t need to “match”

Parameters What is printed? |-5| = 5 |-5| = -5 int main(){ int n = -5; absoluteValue(n); cout << "|-5| = " << n << endl; return 0; } void absoluteValue(int n) { if (n<0){ n = -n; What is printed? |-5| = 5 |-5| = -5 Other/none/more than one of the above You don’t know what automata is, do you? SOON! -- firstprogram.cpp : unlike java, filename doesn’t have to match class! In fact, don’t need a class! -- instead of "import" we have "#include" – note some have "" some have <> -- .h extension means "header" interface information as opposed to .cpp for implementation code -- "using namespace" just don’t worry about why and use it (saves having to do ::) -- main returns type int, just return zero if everything went ok (ignore why) -- we use cout instead of System.out.println(), endl puts a newline

"Pass by reference" What is printed? |-5| = 5 |-5| = -5 int main(){ int n = -5; absoluteValue(n); cout << "|-5| = " << n << endl; return 0; } void absoluteValue(int& n) { if (n<0){ n = -n; What is printed? |-5| = 5 |-5| = -5 Other/none/more than one of the above You don’t know what automata is, do you? SOON! -- firstprogram.cpp : unlike java, filename doesn’t have to match class! In fact, don’t need a class! -- instead of "import" we have "#include" – note some have "" some have <> -- .h extension means "header" interface information as opposed to .cpp for implementation code -- "using namespace" just don’t worry about why and use it (saves having to do ::) -- main returns type int, just return zero if everything went ok (ignore why) -- we use cout instead of System.out.println(), endl puts a newline

"Pass by value" (default behavior of parameters) int main(){ int n = -5; absoluteValue(n); cout << "|-5| = " << n << endl; return 0; } void absoluteValue(int n) { if (n<0){ n = -n; What is printed? |-5| = 5 |-5| = -5 Other/none/more than one of the above You don’t know what automata is, do you? SOON! -- firstprogram.cpp : unlike java, filename doesn’t have to match class! In fact, don’t need a class! -- instead of "import" we have "#include" – note some have "" some have <> -- .h extension means "header" interface information as opposed to .cpp for implementation code -- "using namespace" just don’t worry about why and use it (saves having to do ::) -- main returns type int, just return zero if everything went ok (ignore why) -- we use cout instead of System.out.println(), endl puts a newline

Often used when you would want to return several values from a function (but there is only one return value allowed) #include "random.h" void pickLotto(int& first, int& second, int& third); int main(){ int first, second, third; pickLotto(first, second, third); cout << first << " " << second << " " << third << endl; return 0; } void pickLotto(int& first, int& second, int& third) { first = randomInteger(0,10); second = randomInteger(0,10); third = randomInteger(0,10); You don’t know what automata is, do you? SOON! -- firstprogram.cpp : unlike java, filename doesn’t have to match class! In fact, don’t need a class! -- instead of "import" we have "#include" – note some have "" some have <> -- .h extension means "header" interface information as opposed to .cpp for implementation code -- "using namespace" just don’t worry about why and use it (saves having to do ::) -- main returns type int, just return zero if everything went ok (ignore why) -- we use cout instead of System.out.println(), endl puts a newline

Pass by reference benefits of reference parameters: a useful way to be able to 'return' more than one value often used with large structures and objects, to avoid making bulky copies when passing (more on this in next lectures) downsides of reference parameters: hard to tell from call whether it is ref; can't tell if it will be changed foo(a, b, c); // will foo change a, b, or c?? :-/ can't pass a literal value to a ref parameter grow(39); // error

Strings in C++ String literal vs string class Concatenation String class methods

Using cout and strings This prints |-5| = 5 int main(){ int n = absoluteValue(-5); string s = "|-5|"; s += " = "; cout << s << n << endl; return 0; } int absoluteValue(int n) { if (n<0){ n = -n; return n; This prints |-5| = 5 The + operator concatenates strings, and += works in the way you’d expect. You don’t know what automata is, do you? SOON! -- firstprogram.cpp : unlike java, filename doesn’t have to match class! In fact, don’t need a class! -- instead of "import" we have "#include" – note some have "" some have <> -- .h extension means "header" interface information as opposed to .cpp for implementation code -- "using namespace" just don’t worry about why and use it (saves having to do ::) -- main returns type int, just return zero if everything went ok (ignore why) -- we use cout instead of System.out.println(), endl puts a newline

Using cout and strings But SURPRISE!…this one doesn’t work. int main(){ int n = absoluteValue(-5); string s = "|-5|" + " = "; cout << s << n << endl; return 0; } int absoluteValue(int n) { if (n<0){ n = -n; return n; But SURPRISE!…this one doesn’t work. You don’t know what automata is, do you? SOON! -- firstprogram.cpp : unlike java, filename doesn’t have to match class! In fact, don’t need a class! -- instead of "import" we have "#include" – note some have "" some have <> -- .h extension means "header" interface information as opposed to .cpp for implementation code -- "using namespace" just don’t worry about why and use it (saves having to do ::) -- main returns type int, just return zero if everything went ok (ignore why) -- we use cout instead of System.out.println(), endl puts a newline

C++ string objects and string literals In this class, we will interact with two types of strings: String literals are just hard-coded string values: "hello!" "1234" "#nailedit" They have no methods that do things for us Think of them like integer literals: you can’t do "4.add(5);" //no String objects are objects with lots of helpful methods and operators: string s; string piece = s.substr(0,3); s.append(t); //or, equivalently: s+= t;

String object member functions (3.2) Member function name Description s.append(str) add text to the end of a string s.compare(str) return -1, 0, or 1 depending on relative ordering s.erase(index, length) delete text from a string starting at given index s.find(str) s.rfind(str) first or last index where the start of str appears in this string (returns string::npos if not found) s.insert(index, str) add text into a string at a given index s.length() or s.size() number of characters in this string s.replace(index, len, str) replaces len chars at given index with new text s.substr(start, length) or s.substr(start) the next length characters beginning at start (inclusive); if length omitted, grabs till end of string string name = "Donald Knuth"; if (name.find("Knu") != string::npos) { name.erase(7, 5); // "Donald" }

Aside: Donald Knuth Emeritus (i.e., retired) faculty in our dept. Legend of computer science If you’re lucky, you’ll still see him around campus from time to time

Recap: C++ string objects and string literals Even though they are different types, you can mix them as long as there is a string object around to be the "brains" of the operation: Yes: string s; s = "hello!" //string knows how to convert literal s = s + "1234"; //string has + defined as concatenation char ch = ‘A’; //a single ASCII character with ‘ not " s += ch; //string knows how to interact with char s += ‘A’; //and char literal No: "hello!" + " " + "bye!"; //literal not 'smart' enough to //do concat with + "hello!".substr(0); //literal has no methods

Practice: C++ strings How many of these lines would NOT compile? 1 2 3 1 2 3 More than 3 When discussing: Make sure you are not only on how many but which Talk about the "why" for each int main(){ string s = "hello,"; s += "dolly!"; s += s + "why," + "hello,dolly!"; s.append("hello"); s.append("dolly!"); cout << s + '5' << endl; cout << "hello" + '5' << endl; return 0; } You don’t know what automata is, do you? SOON! -- firstprogram.cpp : unlike java, filename doesn’t have to match class! In fact, don’t need a class! -- instead of "import" we have "#include" – note some have "" some have <> -- .h extension means "header" interface information as opposed to .cpp for implementation code -- "using namespace" just don’t worry about why and use it (saves having to do ::) -- main returns type int, just return zero if everything went ok (ignore why) -- we use cout instead of System.out.println(), endl puts a newline

Stanford library (3.7) #include "strlib.h" Unlike the previous ones, these take the string as a parameter. if (startsWith(name, "Mr.")) { name += integerToString(age) + " years old"; } Function name Description endsWith(str, suffix) startsWith(str, prefix) returns true if the given string begins or ends with the given prefix/suffix text integerToString(int) realToString(double) stringToInteger(str) stringToReal(str) returns a conversion between numbers and strings equalsIgnoreCase(s1, s2) true if s1 and s2 have same chars, ignoring casing toLowerCase(str) toUpperCase(str) returns an upper/lowercase version of a string trim(str) returns string with surrounding whitespace removed