Programming Abstractions Cynthia Lee CS106X. Today’s Topics Introducing C++ from the Java Programmer’s Perspective  Absolute value example, continued.

Slides:



Advertisements
Similar presentations
Hope Is the Thing with Feathers
Advertisements

Dialogue 2 “The Penguin and the Flamingo”. “Hope”-Emily Dickenson Narrator 4: Hope is the thing with feathers that perches in the soul, and sings the.
“Hope” is the thing with feathers -
Chapter 10.
CS31: Introduction to Computer Science I Discussion 1A 5/7/2010 Sungwon Yang
CS31: Introduction to Computer Science I Discussion 1A 4/2/2010 Sungwon Yang
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
Emily Dickinson By: Kadie Mullinax. Hope is the Thing with Feathers “Hope” is the thing with feathers - That perches in the soul - And sings the tune.
CS 31 Discussion, Week 6 Faisal Alquaddoomi, Office Hours: BH 2432, W 4:30-6:30pm, F 12:30-1:30pm.
Word Choice Spice up your poetry!. WORD CHOICE Recap: USE LANGUAGE THAT IS NATURAL AND NOT OVERDONE AVOID REPETITION USE WORDS CORRECTLY USE POWERFUL.
Intro to Generic Programming Templates and Vectors.
Please complete your paper with the information from the following slides!
High-Level Programming Languages: C++
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.
Strings Representation and Manipulation. Objects Objects : Code entities uniting data and behavior – Built from primitive data types.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
CSC 107 – Programming For Science. Announcements  Textbook available from library’s closed reserve.
IT253: Computer Organization Lecture 3: Memory and Bit Operations Tonga Institute of Higher Education.
Arrays Part 9 dbg. Arrays An array is a fixed number of contiguous memory locations, all containing data of the same type, identified by one variable.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Templates An introduction. Simple Template Functions template T max(T x, T y) { if (x > y) { return x; } else { return y; } } int main(void) { int x =
Copyright © Curt Hill Generic Classes Template Classes or Container Classes.
CPS120: Introduction to Computer Science Decision Making in Programs.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Current Assignments Start Reading Chapter 6 Project 3 – Due Thursday, July 24 Contact List Program Homework 6 – Due Sunday, July 20 First part easy true/false.
Gets a Makeover. Time to Envision your Name in Lights…
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
Looping and Counting Lecture 3 Hartmut Kaiser
1 Fencepost loops suggested reading: The fencepost problem Problem: Write a static method named printNumbers that prints each number from 1 to a.
C++ Basics. Compilation What does compilation do? g++ hello.cpp g++ -o hello.cpp hello.
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++
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.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Preprocessor Midterm Review Lecture 7 Feb 17, 2004.
CSC 143A 1 CSC 143 Introduction to C++ [Appendix A]
General Computer Science for Engineers CISC 106 Lecture 12 James Atlas Computer and Information Sciences 08/03/2009.
Chapter 11 Standard C++ Strings and File I/O Dept of Computer Engineering Khon Kaen University.
“Hope is the thing with feathers”
How to write a literary essay
Extended Metaphor Definition: A metaphor that continues over multiple sentences, and that is sometimes extended throughout an entire work. Why Writers.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
Programming Abstractions Cynthia Lee CS106B. Today’s Topics Introducing C++ from the Java Programmer’s Perspective  C++ strings and streams, continued.
Programming Abstractions Cynthia Lee CS106B. Today’s Topics ADTs  Map › Example: counting words in text  Containers within containers › Example: reference.
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.
Programming Abstractions
Building Java Programs
Introduction to Computer Science / Procedural – 67130
Programming Abstractions
C Programming Tutorial – Part I
Semester 1 2nd 9 Weeks Week 1 Daily Warm Ups.
Primitive Data, Variables, Loops (Maybe)
Programming Abstractions in C++, Chapter 3 - 4
C++ Strings References: :" iomanip, sstream.
Programming Abstractions
Programming Abstractions
Wednesdays words September 20, 2017.
Pointers, Dynamic Data, and Reference Types
Arrays Kingdom of Saudi Arabia
Definitions gale = (n.) strong wind storm
Building Java Programs
Representation and Manipulation
A First Program.
Arrays Arrays A few types Structures of related data items
Introduction to Computer Science
Today’s Objectives 28-Jun-2006 Announcements
Please Pick Up Your Journal
Templates An introduction.
Wednesdays words September 20, 2017.
4.1 Introduction Arrays A few types Structures of related data items
Presentation transcript:

Programming Abstractions Cynthia Lee CS106X

Today’s Topics Introducing C++ from the Java Programmer’s Perspective  Absolute value example, continued › C++ strings and streams ADTs: Abstract Data Types  Introduction: What are ADTs?  Queen safety example › Grid data structure › Passing objects by reference const reference parameters › Loop over “neighbors” in a grid

Strings in C++ STRING LITERAL VS STRING CLASS CONCATENATION STRING CLASS METHODS

Using cout and strings 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; } 4 This prints |-5| = 5 The + operator concatenates strings, and += works in the way you’d expect.

Using cout and strings 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; } 5 But SURPRISE!…this one doesn’t work.

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) string name = "Donald Knuth"; if (name.find("Knu") != string::npos) { name.erase(7, 5); // "Donald" } Member function nameDescription 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

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 ' smar t' enough to //do concat with + "hello!".substr(0); //literal has no methods

Practice: C++ strings 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; } 10 How many of these lines would NOT compile? A. 0 B. 1 C. 2 D. 3 E. More than 3 When discussing: Make sure you agree not only on how many but which Talk about the "why" for each

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 nameDescription 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

ADTs VECTOR, GRID, STACK

ADTs  Programming language independent models of common containers  They encompass not only the nature of the data, but ways of accessing it  They form a rich vocabulary of nouns and verbs, often drawing on analogies to make their use intuitive, and to give code written in them a certain literary quality

"Hope" is the thing with feathers BY EMILY DICKENSON “Hope” is the thing with feathers - That perches in the soul - And sings the tune without the words - And never stops - at all - And sweetest - in the Gale - is heard - And sore must be the storm - That could abash the little Bird That kept so many warm - I’ve heard it in the chillest land - And on the strangest Sea - Yet - never - in Extremity, It asked a crumb - of me.

Vector  ADT abstraction similar to an array  Many languages have a version of this › (remember, ADTs are conceptual abstractions that are language- independent)  In C++ we declare one like this:  This syntax is called template syntax › Vectors can hold many things, but they all have to be the same type › The type goes in the after the class name Vector Vector assignment3Scores; Vector measurementsData; Vector > allAssignmentScores; Vector lines;

Code example: Queen safety Download full code from the website to see an example of what we consider good coding style for your assignment!

Handy loop idiom: iterating over “neighbors” in a Grid static bool isSafe(Grid & board, int row, int col) { for (int drow = -1; drow <= 1; drow++) { for (int dcol = -1; dcol <= 1; dcol++) { if (!isDirectionSafe(board, row, col, drow, dcol)) { return false; } return true; } These nested for loops generate all the pairs in the cross product {-1,0,1} x {-1,0,1}, and we can add these as offsets to a (row,col) coordinate to generate all the neighbors (note: often want to test for and exclude the (0,0) offset, which is “self” not a neighbor) R -1 C -1 R -1 C +0 R -1 C +1 R +0 C -1 R +0 C +0 R +0 C +1 R +1 C -1 R +1 C +0 R +1 C +1

QT Creator A FEW WARNINGS & TIPS

If your code doesn’t compile and gives an error about unknown function Main() (note capital M):  There is more than one reason this could arise, but the most common by far is that QT lost its ability to find the path to our Stanford library includes (which define a fake Main()), because you put your code in a directory/folder that is deeply nested on your drive.  For example, C:\Documents and Settings\Documents\classes\Stanf ord\2015\Summer\CS106B\assign ments\C++\Assignment1\...  You need to move the assignment directory closer to C:\ (or on mac, the root directory)

If your code doesn’t compile and gives you “multiple definition” errors for all the functions you have:  This can arise if you add new files to your code inside QT creator using its handy “Add New…” feature.  NOT HANDY! Do not use this feature. It breaks the.pro file.

If it’s too late and you already used the “Add New” feature 1.QUIT: Close QT Creator 2.CLEAN UP BROKEN FILES: Delete the.pro and.pro.user files in your code directory 3.GRAB REPLACEMENT: Download/unzip the assignment bundle again, and get a fresh copy of the project file (the one that ends in.pro) and put it in place of the one you deleted. 4.ALL BETTER! Re-open QT Creator (it will make a new.pro.user)