CMPE 180-92 Data Structures and Algorithms in C++ September 9 Class Meeting Department of Computer Engineering San Jose State University Fall 2016 Instructor:

Slides:



Advertisements
Similar presentations
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Advertisements

Chapter 12 Streams and File I/O Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Chapter 12 Streams and File I/O. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  I/O Streams  File I/O  Character.
I/O Streams as an Introduction to Objects and Classes
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
Chapter 3: Input/Output
Basic Elements of C++ Chapter 2.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 6 I/O Streams as an Introduction to Objects and Classes.
Chapter 12 Streams and File I/O. Learning Objectives I/O Streams – File I/O – Character I/O Tools for Stream I/O – File names as input – Formatting output,
CSE 232: C++ Input/Output Manipulation Built-In and Simple User Defined Types in C++ int, long, short, char (signed, integer division) –unsigned versions.
C++ Programming: Basic Elements of C++.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
File I/O ifstreams and ofstreams Sections 11.1 &
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
I/O and Data Formatting Introduction to Class Concepts INFSY 307 Spring 2003 Lecture 3.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 6 I/O Streams as an Introduction to Objects and Classes.
Copyright © 2002, Department of Systems and Computer Engineering, Carleton University CONTROL STRUCTURES Simple If: if (boolean exp) { statements.
1 Cannon_Chapter9 Strings and the string Class. 2 Overview  Standards for Strings  String Declarations and Assignment  I/O with string Variables 
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 6 I/O Streams as an Introduction to Objects and Classes.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Today’s Lecture  I/O Streams  Console I/O  File I/O  Tools for File I/O  Sequential.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
EC-111 Algorithms & Computing Lecture #10 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME NUST.
I/O Streams as an Introduction to Objects and Classes
Introduction to C++ (Extensions to C)
C++ Basic Input and Output (I/O)
ifstreams and ofstreams
Chapter Topics The Basics of a C++ Program Data Types
Chapter 8 Strings and Vectors
CMPE Data Structures and Algorithms in C++ September 14 Class Meeting
© 2016 Pearson Education, Ltd. All rights reserved.
CMPE Data Structures and Algorithms in C++ September 7 Class Meeting
CPS120: Introduction to Computer Science
CPS120: Introduction to Computer Science
Basic Elements of C++.
COMP 2710 Software Construction File I/O
Copyright © 2003 Pearson Education, Inc.
Chapter 2 part #3 C++ Input / Output
Basic Elements of C++ Chapter 2.
String in C++ A string is an array of characters which contains a non-printing null character ‘\0’ ( with ASCII value 0 ) marking its end. A string.
Chapter 6 I/O Streams as an Introduction to Objects and Classes 1.
7 Arrays.
Arrays Kingdom of Saudi Arabia
Week 9 – Lesson 1 Arrays – Character Strings
10.1 Character Testing.
Today’s Lecture I/O Streams Tools for File I/O
Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
String What it is Why it’s useful
Engineering Problem Solving with C++, Etter
Chapter 2: Introduction to C++.
7 Arrays.
CS 144 Advanced C++ Programming February 7 Class Meeting
CS 144 Advanced C++ Programming February 5 Class Meeting
Arrays Arrays A few types Structures of related data items
CS 144 Advanced C++ Programming February 12 Class Meeting
Chapter 2 part #3 C++ Input / Output
CS 144 Advanced C++ Programming January 29 Class Meeting
ifstreams and ofstreams
CS 144 Advanced C++ Programming February 12 Class Meeting
Today’s Objectives 28-Jun-2006 Announcements
Data Structure(s) A way of storing and organizing data in a computer so that it can be used efficiently. e.g. Arrays Linked Lists stacks Queues Trees.
Lecture 3 More on Flow Control, More on Functions,
8.3 Vectors Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 1.
4.1 Introduction Arrays A few types Structures of related data items
Presentation transcript:

CMPE Data Structures and Algorithms in C++ September 9 Class Meeting Department of Computer Engineering San Jose State University Fall 2016 Instructor: Ron Mak

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak Assignment #1.b: Sample Solution 2 #include using namespace std; const string INPUT_FILE_NAME = "GettysburgAddress.txt"; int main() { string line; int line_count = 0; int character_count = 0; int word_count = 0; int lower_count = 0; int upper_count = 0; int space_count = 0; int punctuation_count = 0; bool saw_letter = false;

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak Assignment #1.b: Sample Solution, cont’d 3 ifstream input; input.open(INPUT_FILE_NAME); if (input.fail()) { cout << "Failed to open " << INPUT_FILE_NAME << endl; return -1; } cout << "Statistics for file " << INPUT_FILE_NAME << ":" << endl; cout << endl;

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak Assignment #1.b: Sample Solution, cont’d 4 // Loop once per line of the input file. while (getline(input, line)) { ++line_count; // Loop once per character of the line. // Count a word if a letter is followed // a space, punctuation, or end of line. for (int i = 0; i < line.length(); i++) { char ch = line[i]; ++character_count; if ((ch >= 'a') && (ch <= 'z')) { ++lower_count; saw_letter = true; }

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak Assignment #1.b: Sample Solution, cont’d 5 else if ((ch >= 'A') && (ch <= 'Z')) { ++upper_count; saw_letter = true; } else if (ch == ' ') { ++space_count; if (saw_letter) // letter followed by space? { ++word_count; saw_letter = false; }

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak Assignment #1.b: Sample Solution, cont’d 6 else { ++punctuation_count; if (saw_letter) // letter followed by punctuation? { ++word_count; saw_letter = false; } if (saw_letter) // letter followed by end of line? { ++word_count; saw_letter = false; } end of for loop end of while loop

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak Assignment #1.b: Sample Solution, cont’d 7 input.close(); cout << "Lines: " << line_count << endl; cout << "Characters: " << character_count << endl; cout << "Words: " << word_count << endl; cout << "Lower-case letters: " << lower_count << endl; cout << "Upper-case letters: " << upper_count << endl; cout << "Spaces: " << space_count << endl; cout << "Punctuation marks: " << punctuation_count << endl; return 0; }

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak Streams  I/O (input/output) for a program can be considered a stream of characters. Represented in a program by a stream variable.  An input stream into your program can be characters typed at the keyboard characters read from a file  An output stream from your program can be characters displayed on the screen characters written to a file 8

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak File I/O  In order for a program to read from a data file, it must first connect a stream variable to the file. 9 #include using namespace std;... ifstream in_stream; // input file stream variable ofstream out_stream; // output file stream variable... in_stream.open("infile.dat"); // connect to the input file out_stream.open("outfile.dat"); // connect to the output file... // Read three integer values from the input file. int value1, value2, value3; in_stream >> value1 >> value2 >> value3; // Write to the output file. out_stream << "Value #1 is " << value1 << " and Value #2 is " << value2 << endl;

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak File I/O, cont’d  Close a stream when you’re done with reading or writing it.  Closing a stream releases the associated file for use by another program. 10 in_stream.close(); out_stream.close();

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak Stream Name vs. File Name  Do not confuse the name of a program’s stream variable with the name of the file. The stream variable’s name is internal to the program. The file’s name is external to the program.  Calling a stream’s open method connects the stream to the file.  A stream is an object. open and close are methods we can call on the object. 11 We’ll learn about C++ classes and objects later.

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak Formatting Output  Formatting a value that is being output includes determining the width of the output field deciding whether to write numbers in fixed-point notation or in scientific notation setting how many digits after the decimal point  To format output to cout, call its member functions: Use fixed-point notation instead of scientific notation. Always include the decimal point in the output. Only two significant digits are required in the output. 12 cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2);

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak Output Manipulators  Manipulator function setw sets the width of an output field.  Manipulator function setprecision sets the number of places after the decimal point.  Calls to manipulators are embedded in output statements. Examples: 13 #include using namespace std;... cout << "Value 1 = " << setw(10) << value1 << end; cout << "$" << setprecision(2) << amount << endl;

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak Passing Streams to Functions  Pass stream objects to functions only via call-by-reference. Example: 14 void copyFile(ifstream& source, ofstream& destination);

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak Character I/O  Recall that the operator >> used on cin skips blanks.  To read all characters from an input stream, including blanks, use the get method:  Use the put method to output any character to an output stream. 15 char ch;... cin.get(ch);

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak Predefined Character Functions  We could have used some of the following predefined character functions for our solution to the Gettysburg Address assignment. isupper(ch) islower(ch) isalpha(ch) isdigit(ch) isspace(ch) toupper(ch) tolower(ch) 16

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak The eof Function  Boolean function eof tests whether or not an input stream has read the entire file. eof = end of file Example:  Function eof returns true only after an attempt was made to read past the end of file. 17 if (in_stream.eof())...

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak Break 18

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak Arrays  An array variable can have multiple values.  All values must be the same data type.  Declare an array variable by indicating how many elements. Example:  Use subscripts to access array elements.  Subscript values for an array can range from 0... n -1 where n is equal to the number of elements in the array. 19 int a[6];

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak Initialize an Array  You can initialize an array when you declare it: If you initialize an array this way, you can leave off the array size.  You can initialize the array with assignments:  Or with a loop: 20 int ages[] = {12, 9, 7, 2}; int ages[4]; ages[0] = 12; ages[1] = 9; ages[2] = 7; ages[3] = 2; int ages[4]; for (int i = 0; i < 4; i++) ages[i] = 0;

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak Array Function Parameters  To pass an entire array to a function, indicate that a parameter is an array with []. Example:  Also pass the array size.  Arrays are implicitly passed by reference.  Make the array parameter const to indicate that the function does not change the array. Example: 21 void sort(double a[], int size); double average(const double a[], int size);

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak Multidimensional Arrays  A multidimensional array is an array of arrays. Example: A two-dimensional array: Each element of page is itself an array of 100 characters.  Use multiple subscripts to access an element of a multidimensional array. Example: page[i][j] to access the j th character of the i th row. What is page[k] ? 22 char page[30][100];

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak Assignment #3.b: Goldbach’s Conjecture  Goldbach’s Conjecture states that: It is one of the oldest unsolved problems in number theory. See  Write a C++ program to test the conjecture on even numbers from 4 through 100. For each even number, print all the pairs of primes whose sum is that number. 23 Every even integer greater than 2 is the sum of two prime numbers.

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak Assignment #3.b, cont’d  First, use the Sieve of Eratosthenes to generate an array of prime numbers under 100: See: Primes:

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak Assignment #3.b, cont’d  Then test the conjecture:  Due Friday, September Test of Goldbach's Conjecture: 4: 2 2 6: 3 3 8: : : : :

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak C Strings  Traditional C programs used arrays of characters to represent strings:  A C string is always terminated by the null character \0.  Therefore, the array size was one greater than the number of characters in the string. The greeting character array above has size char greeting[] = "Hello, world!";

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak C Strings, cont’d  You cannot assign a string value to a C string array variable: Illegal:  Instead, you use the strcpy (“string copy”) function: Warning: Do not copy past the end of the destination string! 27 greeting = "Good-bye!"; strcpy(greeting, "Good-bye!");

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak C Strings, cont’d  To compare two C strings, use the strcmp (“string compare”) function:  It returns: a negative value if str1 comes alphabetically before str2 zero if they contain the same characters a positive value if str1 comes alphabetically after str2. 28 strcmp(str1, str2);

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak The Standard string Class  C++ programs use the standard string class:  You can initialize string variables when you declare them:  You can assign to string variables: 29 #include using namespace std; string noun, s1, s2, s3; string verb("go"); noun = "computer";

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak The Standard string Class, cont’d  String concatenation:  String comparisons with == != >= Lexicographic comparisons as expected.  Strings automatically grow and shrink in size. A string keeps track of its own size.  Use the member function at to safely access a character of a string: s1.at(i) s1[i] is dangerous if you go beyond the length. 30 s1 = s2 + " and " + s3;

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak The Standard string Class, cont’d  Many useful member functions : str.length() str.at(i) str.substr(position, length) str.insert(pos, str2) str.erase(pos, length) str.find(str1) str.find(str1, pos) str.find_first_of(str1, pos) str.find_first_not_of(str1, pos) 31

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak Assignment #3.c: War and Peace  You are given the entire text of the great Russian novel, War and Peace.  Write a C++ program that inputs the novel and searches for the following names: Boris Drubetskoy Joseph Bazdeev Makar Alexeevich 32

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak Assignment #3.c, cont’d  As your program inputs the novel line by line, look for the names.  If it finds one of the names, print the line number, the position of the first character of the name, and the name itself. The first line is line 1. The first character of the line is at position 1.  Example output: 33 LINE POSITION NAME Boris Drubetskoy Makar Alexeevich Boris Drubetskoy Joseph Bazdeev

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak Assignment #3.c, cont’d  Note: A name may be split across two lines.  You must print the names in the order that they occur in the text.  Due Friday, September

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak Vectors  A vector is a kind of array whose length can dynamically grow and shrink. Vectors are part of the C++ Standard Template Library (STL).  Like an array, a vector has a base type, and all its elements are of that type.  Different declaration syntaxes from arrays: 35 vector salaries; vector truthTable(10); vector ages = {12, 9, 7, 2}; An array on steroids!

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak Vectors, cont’d  Index into a vector like an array: ages[2]  Use with a standard for loop:  Or with a ranged for loop: 36 for (int i = 0; i < ages.size(); i++) { cout << ages[i] << endl; } for (int age : ages) { cout << age << endl; }

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak Vectors, cont’d  Append new values to the end of a vector:  Vector assignment: v1 = v2 ; Element-by-element assignment of values. The size of v1 can change to match the size of v2. 37 salaries.push_back( ); salaries.push_back( ); salaries.push_back( ); salaries.push_back( );

Computer Engineering Dept. Fall 2016: September 9 CMPE : Data Structures and Algorithms in C++ © R. Mak Vectors, cont’d  Size of a vector: The current number of elements that the vector contains: v.size()  Capacity of a vector: The number of elements for which memory is currently allocated: v.capacity() Change the size: Explicitly set the capacity: Bump up the capacity by 10: 38 v.reserve(32) v.reserve(v.size() + 10) v.resize(24)