C++ crash course Class 3 designing C++ programs, classes, control structures.

Slides:



Advertisements
Similar presentations
Chapter 10.
Advertisements

Computer Science 1620 Loops.
Computer Science 1620 Variables and Memory. Review Examples: write a program that calculates and displays the average of the numbers 45, 69, and 106.
1 Lecture-4 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
Chapter 5: Loops and Files.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
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.
1 Array, Pointer and Reference ( I ) Ying Wu Electrical Engineering and Computer Science Northwestern University EECS 230 Lectures.
Chapter 8: Introduction to High-level Language Programming Invitation to Computer Science, C++ Version, Third Edition.
Computer Science II Exam I Review Monday, February 6, 2006.
Introduction to C++CS-2303, C-Term Introduction to C++ CS-2303 System Programming Concepts (Slides include materials from The C Programming Language,
Computer Science 1620 Strings. Programs are often called upon to store and manipulate text word processors chat databases webpages etc.
Standard library types Practical session # 3 Software Engineering
CSE 332: C++ program structure and development environment C++ Program Structure (and tools) Today we’ll talk generally about C++ development (plus a few.
Input & Output: Console
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
Chapter 9 Defining New Types. Objectives Explore the use of member functions when creating a struct. Introduce some of the concepts behind object-oriented.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
CS1 Lesson 2 Introduction to C++ CS1 Lesson 2 -- John Cole1.
Chapter 1 Working with strings. Objectives Understand simple programs using character strings and the string library. Get acquainted with declarations,
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation.
Defining New Types Lecture 21 Hartmut Kaiser
1 C++ Syntax and Semantics, and the Program Development Process.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems.
1 CS161 Introduction to Computer Science Topic #13.
Array, Pointer and Reference ( I ) Ying Wu Electrical & Computer Engineering Northwestern University ECE230 Lectures Series.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Introduction to C++ Version 1.1. Topics C++ Structure Primitive Data Types I/O Casting Strings Control Flow.
Working with Batches of Data Lecture 4 Hartmut Kaiser
Looping and Counting Lecture 3 Hartmut Kaiser
An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Introduction Arrays Declaring Arrays Examples Using Arrays.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Chapter 3 Working with Batches of Data. Objectives Understand vector class and how it can be used to collect, store and manipulate data. Become familiar.
C++ / G4MICE Course Session 1 - Introduction Edit text files in a UNIX environment. Use the g++ compiler to compile a single C++ file. Understand the C++
C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Loops and Files. 5.1 The Increment and Decrement Operators.
1 What is a Named Constant? A named constant is a location in memory that we can refer to by an identifier, and in which a data value that cannot be changed.
Manipulator example #include int main (void) { double x = ; streamsize prec = cout.precision(); cout
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Std Library of C++ Part 2. vector vector is a collection of objects of a single type vector is a collection of objects of a single type Each object in.
1 ENERGY 211 / CME 211 Lecture 7 October 6, 2008.
 2003 Prentice Hall, Inc. All rights reserved Basics of a Typical C++ Environment C++ systems –Program-development environment –Language –C++
Chapter 2 Creating a C++ Program. Elements of a C++ Program Four basic ways of structuring a program Four basic ways of structuring a program 1.Sequencing.
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
CSE 232: Moving Data Within a C++ Program Moving Data Within a C++ Program Input –Getting data from the command line (we’ve looked at this) –Getting data.
CSCE Introduction to Program Design and Concepts J. Michael Moore Spring 2015 Set 6: Miscellaneous 1 Based on slides created by Bjarne Stroustrup.
1 ENERGY 211 / CME 211 Lecture 3 September 26, 2008.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Working with Batches of Data
Chapter 1.2 Introduction to C++ Programming
Introduction to C++ (Extensions to C)
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Introduction to C++ Programming
Chapter 2: Introduction to C++
Working with Strings Lecture 2 Hartmut Kaiser
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.
Working with Strings Lecture 2 Hartmut Kaiser
Introduction to C++ Programming
Chapter 2: Introduction to C++.
Capitolo 1 – Introduction C++ Programming
Std Library of C++.
An Introduction to STL.
Presentation transcript:

C++ crash course Class 3 designing C++ programs, classes, control structures

Types Last time: basic types and variables Today: – structure of a C++ program – defining complex types – strings, vectors, iterators – quick intro: arrays and pointers

Bookstore Example Bookstore keeps a file of transactions Each transaction records the sale of a particular book – ISBN (International Standard Book Number) – number of copies sold – price at which each copy was sold ex: X

Bookstore: Problem Definition Bookstore owner wants to know: – number of copies of each title sold – total revenue from each book – average sales price of a book

Bookstore: Designing the Solution We need to get input, and produce output We want to define a data structure to hold this data We want to be able to test if two records are the same (ISBN) We want to look at every transaction in the input

Bookstore: Designing the Solution How do we get the average sales price? Done manually… – look at all transactions with the same ISBN but how will we know when we can stop reading in transaction information? – do a weighted average: for each ISBN: – sum of copies sold * price / total number of copies sold How can we do it in C++? – Need: new data types, if statements, loops

Control Structures if statements loops – for – while – do-while

if statements if (condition) if_body; Performs if_body only in the case when condition is true // sum from 0-10, even numbers only int sum=0; for(int ctr=0;ctr<=10;ctr++) { if(ctr % 2 == 0) { sum+=ctr; }

Loops for while do-while

for loop for(init-statement; condition; expression) for_body; Repeats for_body until condition is false, performing expression after each iteration int sum = 0; for(int ctr=0; ctr <= 10; ctr++) { sum += ctr; }

while loop while (condition) while_body_statement ; Repeatedly tests condition, and then executes the while_body_statement until condition is false int ctr = 0, sum_to_ten = 0; while(ctr <= 10) { sum_to_ten += ctr; ++ctr; // ++ increments ctr } also: do { sum_to_ten += ctr; ++ctr; } while(ctr <= 10);

I/O: A Closer Look I/O is shorthand for input/output You’ve seen this already: – std::cin, std::cout What’s going on here? I/O happens in C++ as part of the standard library (std), specifically the iostream library Standard library must be implemented by every C++ compiler The preprocessor directive #include or #include …tells the C++ preprocessor to use the iostream library

I/O: A Closer Look iostream defines four IO objects – “standard input” istream std::cin – “standard output” ostream std::cout – “standard error” ostream std::cerr – “see-log” ostream std::clog Why streams? – istream and ostream objects can also be created for getting input and output out of files

I/O: A Closer Look UNIX interlude: “standard input”, “standard output” and “standard error” are UNIX concepts You can redirect output of a program into a file depending on which stream it’s in:stdout:./a.out 1> out_file stderr:./a.out 2> err_file stdout and stderr:./a.out > outerr_file You can also use a file as user input similarly: stdin:./a.out < in_file

I/O: A Closer Look When you see the line: std::cout << “Enter two numbers:” << std::endl; …the << is actually the output operator, which is a binary operator producing an ostream object (std::cout) std::endl is a manipulator – in this case flushes the buffer to the standard output

Creating Classes Moving beyond primitive types: – class types are complex types Need to know: – what is the name of a class? – where is it defined? – what operations can it do?

Bookstore redux: Classes We have a Sales_item stores ISBN keeps track of: – number of copies sold – revenue – average sales price Lives in Sales_item.h – header file storing the class definition

Sales_item class Operations: – Use addition operator + to add two Sales_items – Use input operator << to read a Sales_item – Use output operator >> to write a Sales_item – Use assignment operator = to assign one Sales_item to another – Call same_isbn function to see if two Sales_items are the same book

Sales_item class #include #include “Sales_item.h” int main() { Sales_item book; // read ISBN, number of copies sold, and sales price std::cin >> book; // write ISBN, number of copies sold, total revenue, and average price std::cout << book << std::endl; return 0; }

Sales_item class Input: X Output: X

Sales_item class #include #include “Sales_item.h” int main() { Sales_item item1, item2; // read two transactions std::cin >> item1 >> item2; // print their sum std::cout << item1 + item2 << std::endl; return 0; }

Sales_item class Input: X X Output: X

Sales_item class #include #include “Sales_item.h” int main() { Sales_item item1, item2; // read two transactions std::cin >> item1 >> item2; // print their sum, if the same isbn: if(item1.same_isbn(item2)) { std::cout << item1 + item2 << std::endl; return 0; // success! } else { std::cerr << “Data must refer to same ISBN” << std::endl; return -1; // failure }

Bookstore: Putting it together Now we have all of the components to write our bookstore program!

Class Types We can define an empty class for Sales_item: class Sales_item { public: // operations on Sales_item objects will go here private: std::string isbn; unsigned units_sold; double revenue; }; Don’t forget the semicolon!

Class Types We could also have defined Sales_item as a struct: struct Sales_item { // struct members are by default public // operations on Sales_item objects private: std::string isbn; unsigned units_sold; double revenue; }; Only difference from class: struct members are by default public; class members are by default private

Writing Header Files Class definitions go into a header file (extension.h) Implementation for the definitions goes elsewhere Sales_item.h: definition for Sales_item Implementation goes in a separate source file Every file that uses Sales_item must #include “Sales_item.h”

Writing Header Files Headers contain: – class definitions – extern variable declarations – function declarations Headers should NOT define variables and objects, only declare them (extern keyword) Headers sometimes must #include other header files – Sales_item.h needs string.h, since it uses std::string – This means you need to be careful not to #include a header more than once!

Writing Header Files To keep this from happening: – more preprocessor directives #ifndef SALESITEM_H #define SALESITEM_H // definition of Sales_item and related goes here #endif

Setting aside Bookstore Enough about bookstore for now; let’s talk about library types We’ll get back to the detailed implementation of how to make Sales_item a reality

Library Types We talked briefly about the standard library std::cout meaning: std is the namespace, :: is the scope operator, cout is an object in the namespace You’ve seen some code that just uses cout by itself Need to declare the namespace first: using namespace std;

Library Types We can accomplish the same thing to bring specific objects into the namespace like so: using std::cin;

Strings Strings! Memory interlude: the term “string” comes from shorthand for character string, which is what strings are in just about any language (we’ll see what this means when we talk about arrays and pointers) In C++: std::string, like many string implementations, has more functionality than a plain character string To make a string, we need to: #include using std::string;

Strings Initializing a string: – string s1; // s1 is the empty string (why is this initialized? it uses the default constructor – we’ll talk more about this later) – string s2(s1); // copies s1 into s2 – string s3(“value”); // initializes s3 as a copy of the // string literal – string s4(n, ‘c’); // initializes s4 with n copies of // ‘c’

Strings Initializing a string: – string s1; // s1 is the empty string (why is this initialized? it uses the default constructor – we’ll talk more about this later) – string s2(s1); // copies s1 into s2 – string s3(“value”); // initializes s3 as a copy of the // string literal – string s4(n, ‘c’); // initializes s4 with n copies of // ‘c’ Why are we doing it this way? copy-initialization vs. direct-initialization; related to memory

Strings Like Sales_item objects, we can read these off of istream objects, and print them to ostream objects string s; // note: this is initialized! cin >> s; cout << s << endl; Or we can use getline: string line; while (getline(cin, line)) cout << line << endl; Ordinarily the input operator (>>) only reads a word at a time (space-delimited)

Strings Operation s.empty() Returns true if s is empty; otherwise false s.size() Number of characters in s (Not an int! Instead, it’s string::size_type) s[n] Returns nth character of s (0-indexed) s1 + s2 Returns a string that concatenates s1 and s2 s1 = s2 Replaces all of the characters in s1 with a copy of s2 v1 == v2 Returns true if equal, otherwise false !=,, and >= Usual meanings

Strings String size: – string::size_type is either an unsigned int or unsigned long – companion type for the string type – If we used an int, this limits the length of strings to twice the size of an int – many files would easily exceed that and need to be held in a single variable String ordering: – Think alphabetical, where the alphabet is ASCII Subscripting: – Subscripting results in an lvalue, so we can change the middle of a string – Any integral type (char, bool, int) can be used for subscripting; we use string::size_type typically

Vectors A vector is a collection of objects of one type Indexed by integers Need to include and declare it: #include using std::vector; Class template: – Allow us to write a single class or function to hold a variety of types vector ivec; vector Sales_vec;

Vectors Initialization: – vector v1; // vector that holds objects // of type T – vector v2(v1); // v2 is a copy of v1 – vector v3(n, i); // v3 has n elements with // value i – vector v4(n); // v4 has n copies of a // value-initialized object

Vectors Vector initialization – vector ivec1; // ivec1 is an int vector – vector ivec2(ivec1); // OK – vector svec(ivec1); // BAD – vector svec(10, “hi!”); // 10 strings of “hi!”

Vectors Vectors grow dynamically; you can add elements at run-time Unlike arrays (from C or Java, and many other languages), you don’t need to know how big they’re going to be ahead of time Vectors will populate themselves by default at initialization with either the default constructor of the type, or an element initializer (0 in the case of int) for basic types

Vectors Which of these vector definitions are wrong? vector > ivec; vector svec = ivec; vector svec(10, “null”);

Vectors How many elements are there in each of these vectors? – vector ivec1; – vector ivec2(10); – vector ivec3(10, 42); – vector svec1; – vector svec2(10); – vector svec3(10, “hello”); What are the values of the elements for each?

Vectors Operations v.empty() Returns true if the vector is size 0 v.size() Returns the number of elements in v v.push_back(t) Increases size of v; adds value t to the end v[n] Returns element at position n in v v1 = v2 Replaces elements in v1 with a copy of elements in v2 v1 == v2 Tests if v1 and v2 are equal !=,, >= comparison is “alphabetical” You MUST use v.push_back(t) to put a new element in! Unlike in other languages, v[n] = t; is NOT valid unless n < v.size()

Iterating through Vectors We learned about for loops, let’s use them on vectors! vector ivec; for (vector ::size_type ix = 0; ix != 10; ++ix) ivec.push_back(ix);

Iterating through Vectors We can actually do this with another syntax Vector has a companion type, vector ::iterator Designed to move through every element in a vector vector ivec; vector ::iterator iter = ivec.begin(); iter now refers to ivec[0] (unless ivec was empty)

Iterating through Vectors There’s also an ivec.end(), but it doesn’t refer to an element in the vector – it tells us when we’re done (sentinel) In order to access elements through an iterator, we must dereference it *iter = 0; So our loop can now be written as: for (vector ::iterator iter=ivec.begin(); iter != ivec.end(); ++iter) *iter = 0; How would we use iterators to write this as a while loop?

Iterating through Vectors There’s also a const_iterator Used when we will only be reading from the vector, and not changing the elements A const_iterator is not a const iterator You can move iterators forward n elements as follows: iter = iter + n; iter = iter - n; You can also track two points in the vector with two iterators, and find out how far apart they are: iter1 – iter2; Mostly won’t need this, but it’s good to know =)

Arrays If you’ve programmed before, you’ve heard of these – (lists in Python) Like vectors, but must be a fixed size ahead of time Why? – Must allocate space in memory

Pointers: A quick introduction If you’ve done coding or been around computer science, you’ve probably heard about pointers Arrays in C++ (as well as C) are built on pointers A pointer is a variable that holds a memory location, rather than data

Pointers: A quick introduction We can create variables, then store their locations in pointer variables int var = 0; int *var_ptr = &var; * is the dereference operator from before Arrays are a series of memory locations Iterating through them involves moving the pointer forward

Tomorrow more on classes: how is Sales_item getting defined? arrays, pointers, and more, oh my!