Programming Abstractions

Similar documents
Programming Abstractions

Programming Abstractions in C++

CS 106X, Lecture 2 C++ Functions and Strings

CS 106B Lecture 2: C++ Functions

C++ basics Getting started with, and Data Types.

A couple of decent C++ web resources you might want to bookmark:

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

what are strings today: strings strings: output strings: declaring and initializing what are strings and why to use them reading: textbook chapter 8

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:

C++ Support Classes (Data and Variables)

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

C++ For Science and Engineering Lecture 12

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:

CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12

Your First C++ Program. September 1, 2010

CS31 Discussion 1E. Jie(Jay) Wang Week5 Oct.27

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

CS106X Handout 04 Winter 2018 January 8 th, 2018 C++ Strings

Discussion 1H Notes (Week 4, April 22) TA: Brian Choi Section Webpage:

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

Streams. Ali Malik

CS 106B Lecture 5: Stacks and Queues

Character Functions & Manipulators Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10

Scientific Computing

Computer Science II Lecture 1 Introduction and Background

A SHORT COURSE ON C++

Assignment #1 Simple C++

Programming with C++ as a Second Language

Programming. Computer. Program. Programming Language. Execute sequence of simple (primitive) instructions What instructions should be provided?

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

Lab 8. Follow along with your TA as they demo GDB. Make sure you understand all of the commands, how and when to use them.

CS125 : Introduction to Computer Science. Lecture Notes #4 Type Checking, Input/Output, and Programming Style

11. Arrays. For example, an array containing 5 integer values of type int called foo could be represented as:

2 nd Week Lecture Notes

The C++ Language. Arizona State University 1

Understanding main() function Input/Output Streams

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Engineering Problem Solving with C++, Etter

LAB #8. GDB can do four main kinds of things (plus other things in support of these) to help you catch bugs in the act:

CS106X Handout 04 Autumn 2009 September 25 th, 2009 C++ Strings

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

Computer Programming

Chapter 4 - Notes Control Structures I (Selection)

Exercise 1.1 Hello world

Variables and literals

How to approach a computational problem

Chapter 7: User-Defined Simple Data Types, Namespaces, and the string Type

Sixth lecture; classes, objects, reference operator.

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

Lesson 1A - First Java Program HELLO WORLD With DEBUGGING examples. By John B. Owen All rights reserved 2011, revised 2015

Today in CS161. Week #3. Learn about. Writing our First Program. See example demo programs. Data types (char, int, float) Input and Output (cin, cout)

Working with Strings. Lecture 2. Hartmut Kaiser. hkaiser/spring_2015/csc1254.html

CS2141 Software Development using C/C++ C++ Basics

the gamedesigninitiative at cornell university Lecture 6 C++: Basics

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

Chapter 2 C++ Fundamentals

Introduction to Programming using C++

These are notes for the third lecture; if statements and loops.

CS 106B, Lecture 1 Introduction to C++

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

Name. CPTR246 Spring '17 (100 total points) Exam 2

Objectives. In this chapter, you will:

Getting started with C++ (Part 2)

LAB #8. Last Survey, I promise!!! Please fill out this really quick survey about paired programming and information about your declared major and CS.

Unit 14. Passing Arrays & C++ Strings

G52CPP C++ Programming Lecture 17

Lecture 10. Command line arguments Character handling library void* String manipulation (copying, searching, etc.)

Lecture 3 The character, string data Types Files

CS103L FALL 2017 UNIT 1: TYPES, VARIABLES,EXPRESSIONS,C++ BASICS

Definition Matching (10 Points)

CS106X Handout 03 Autumn 2012 September 24 th, 2012 Getting Started

Programming Fundamentals. With C++ Variable Declaration, Evaluation and Assignment 1

Lab: Supplying Inputs to Programs

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

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

Reading from and Writing to Files. Files (3.12) Steps to Using Files. Section 3.12 & 13.1 & Data stored in variables is temporary

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2

"Hello" " This " + "is String " + "concatenation"

Overloading Functions & Command Line Use in C++ CS 16: Solving Problems with Computers I Lecture #6

Bruce Merry. IOI Training Dec 2013

Engineering Problem Solving with C++, Etter/Ingber

Computer Programming

! A literal represents a constant value used in a. ! Numbers: 0, 34, , -1.8e12, etc. ! Characters: 'A', 'z', '!', '5', etc.

Chapter 1 - What s in a program?

Chapter 13. Recursion. Copyright 2016 Pearson, Inc. All rights reserved.

Honu. Version November 6, 2010

Python: common syntax

Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language. Dr. Amal Khalifa. Lecture Contents:

Today in CS161. Lecture #7. Learn about. Rewrite our First Program. Create new Graphics Demos. If and else statements. Using if and else statements

Programming in C++: Assignment Week 1

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

Characters, c-strings, and the string Class. CS 1: Problem Solving & Program Design Using C++

String Class in C++ When the above code is compiled and executed, it produces result something as follows: cin and strings

CHAPTER 3 BASIC INSTRUCTION OF C++

Computer Programming

More Examples Using Functions and Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #6

UNIT- 3 Introduction to C++

Chapter 2: Basic Elements of C++

Transcription:

Programming Abstractions C S 1 0 6 X 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 ( B U T I T S O K I F Y O U D O N T K N O W J A V A! )

A first C++ program (Error) firstprogram.cpp 4 #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;

A first C++ program (Fixed #1) firstprogram.cpp 5 #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;

A first C++ program (Fixed #2) firstprogram.cpp 6 #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;

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? A. C++ could have done that, but such a rule would be too cumbersome for programmers to follow. B. 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. 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. D. 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? (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(n);

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 11 int main(){ int n = -5; absolutevalue(n); cout << " -5 = " << n << endl; return 0; What is printed? A. -5 = 5 B. -5 = -5 C. Other/none/more than one of the above void absolutevalue(int n) { if (n<0){ n = -n;

"Pass by reference" 12 int main(){ int n = -5; absolutevalue(n); cout << " -5 = " << n << endl; return 0; What is printed? A. -5 = 5 B. -5 = -5 C. Other/none/more than one of the above void absolutevalue(int& n) { if (n<0){ n = -n;

"Pass by value" (default behavior of parameters) 13 int main(){ int n = -5; absolutevalue(n); cout << " -5 = " << n << endl; return 0; What is printed? A. -5 = 5 B. -5 = -5 C. Other/none/more than one of the above void absolutevalue(int n) { if (n<0){ n = -n;

14 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);

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++ S T R I N G L I T E R A L V S S T R I N G C L A S S C O N C A T E N A T I O N S T R I N G C L A S S M E T H O D S

Using cout and strings 17 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.

Using cout and strings 18 int main(){ int n = absolutevalue(-5); string s = " -5 " + " = "; cout << s << n << endl; return 0; But SURPRISE! this one doesn t work. int absolutevalue(int n) { if (n<0){ n = -n; return n;

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 s.append(str) s.compare(str) s.erase(index, length) s.find(str) s.rfind(str) s.insert(index, str) s.length() or s.size() s.replace(index, len, str) s.substr(start, length) or s.substr(start) Description add text to the end of a string return -1, 0, or 1 depending on relative ordering delete text from a string starting at given index first or last index where the start of str appears in this string (returns string::npos if not found) add text into a string at a given index number of characters in this string replaces len chars at given index with new text 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 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; How many of these lines would NOT compile? A. 0 B. 1 C. 2 D. 3 E. More than 3 23 When discussing: Make sure you are 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. Function name endswith(str, suffix) startswith(str, prefix) integertostring(int) realtostring(double) stringtointeger(str) stringtoreal(str) equalsignorecase(s1, s2) tolowercase(str) touppercase(str) trim(str) Description returns true if the given string begins or ends with the given prefix/suffix text returns a conversion between numbers and strings true if s1 and s2 have same chars, ignoring casing returns an upper/lowercase version of a string returns string with surrounding whitespace removed if (startswith(name, "Mr.")) { name += integertostring(age) + " years old";