CMPE Data Structures and Algorithms in C++ September 7 Class Meeting

Slides:



Advertisements
Similar presentations
I/O Streams as an Introduction to Objects and Classes
Advertisements

Chapter 9: Arrays and Strings
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 3: Input/Output.
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
Chapter 8 Arrays and Strings
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 3: Input/Output.
Chapter 3: Input/Output
CS 117 Spring 2002 Review for Exam 3 arrays strings files classes.
Chapter 8 Arrays and Strings
C++ Programming: Program Design Including Data Structures, Fifth Edition Chapter 3: Input/Output.
C++ Programming: Basic Elements of C++.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 3 Formatting Output.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 3: Input/Output.
I/O and Data Formatting Introduction to Class Concepts INFSY 307 Spring 2003 Lecture 3.
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
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.
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.
CMPE Data Structures and Algorithms in C++ September 9 Class Meeting Department of Computer Engineering San Jose State University Fall 2016 Instructor:
I/O Streams as an Introduction to Objects and Classes
Introduction Programs which manipulate character data don’t usually just deal with single characters, but instead with collections of them (e.g. words,
Topic 2 Input/Output.
Introduction to C++ (Extensions to C)
C++ Basic Input and Output (I/O)
Chapter 8 Strings and Vectors
EGR 2261 Unit 10 Two-dimensional Arrays
CMPE Data Structures and Algorithms in C++ September 14 Class Meeting
Computer Programming BCT 1113
© 2016 Pearson Education, Ltd. All rights reserved.
CPS120: Introduction to Computer Science
CPS120: Introduction to Computer Science
I/O Streams as an Introduction to Objects and Classes
Chapter 3: Expressions and Interactivity.
Copyright © 2003 Pearson Education, Inc.
CMPE 180A Data Structures and Algorithms in C++ February 15 Class Meeting Department of Computer Engineering San Jose State University Spring 2018 Instructor:
Chapter 2 part #3 C++ Input / Output
Standard Input/Output Streams
Standard Input/Output Streams
Chapter 6 I/O Streams as an Introduction to Objects and Classes 1.
7 Arrays.
Basic Input and Output C++ programs can read and write information using streams A simple input stream accepts typed data from a keyboard A simple output.
Arrays Kingdom of Saudi Arabia
Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Review of Strings which include file needs to be used for string manipulation? what using statement needs to be included for string manipulation? how is.
String What it is Why it’s useful
Chapter 3 Input output.
CSC 143 Stream I/O Classes and Files [A11-A15, A38-A50]
Chapter 3: Expressions and Interactivity
Engineering Problem Solving with C++, Etter
Formatted Input, Output & File Input, Output
7 Arrays.
CS 144 Advanced C++ Programming February 7 Class Meeting
CS 144 Advanced C++ Programming February 5 Class Meeting
CHAPTER 4 File Processing.
Arrays Arrays A few types Structures of related data items
Chapter 2 part #3 C++ Input / Output
Instructor: Dr. Michael Geiger Spring 2019 Lecture 13: Exam 1 Preview
CS 144 Advanced C++ Programming February 12 Class Meeting
CS31 Discussion 1H Fall18: week 6
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.
Dr. Khizar Hayat Associate Prof. of Computer Science
4.1 Introduction Arrays A few types Structures of related data items
Presentation transcript:

CMPE 180-92 Data Structures and Algorithms in C++ September 7 Class Meeting Department of Computer Engineering San Jose State University Fall 2017 Instructor: Ron Mak www.cs.sjsu.edu/~mak

Assignment #2: Sample Solution

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

File I/O In order for a program to read from a data file, it must first connect a stream variable to the file. #include <fstream> 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;

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. in_stream.close(); out_stream.close();

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 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 functions we can call on the object. We’ll learn about C++ classes and objects later.

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. cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2);

Output Manipulators Manipulator function setw sets the width of an output field. Manipulator function setprecision sets the number of places after the decimal point. Embed calls to manipulators in output statements. Examples: #include <iomanip> using namespace std; ... cout << "Value 1 = " << setw(10) << value1 << end; cout << "$" << setprecision(2) << amount << endl;

Passing Streams to Functions Pass stream objects to functions only via call-by-reference. Example: void copyFile(ifstream& source, ofstream& destination);

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. char ch; ... cin.get(ch);

Predefined Character Functions Some very useful Boolean functions that test a character: isupper(ch) islower(ch) isalpha(ch) isdigit(ch) isspace(ch) toupper(ch) tolower(ch)

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. if (in_stream.eof()) ...

Quiz

Break

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. int a[6];

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: 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;

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. void sort(double a[], int size); double average(const double a[], int size);

Assignment #3.a. Prime Numbers Use the Sieve of Eratosthenes to generate an array of prime numbers under 100: See: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes Primes: . 2 3 . 5 . 7 . . . 11 . 13 . . . 17 . 19 . . . 23 . . . . . 29 . 31 . . . . . 37 . . . 41 . 43 . . . 47 . . . . . 53 . . . . . 59 . 61 . . . . . 67 . . . 71 . 73 . . . . . 79 . . . 83 . . . . . 89 . . . . . . . 97 . . .

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 jth character of the ith row. What is page[k]? char page[30][100];

Assignment #3.b. Spirals Print a sequence of integers in a counter-clockwise spiral that is enclosed in a square matrix n-by-n. The 2-dimensional array has n rows and n columns. Start with a given value in the center of the matrix. The starting value is not necessarily 1. Arrange subsequent values in a counter-clockwise spiral that grows outward until it fills the matrix.

Assignment #3.b. Spirals, cont’d Example spirals Size 5, starting value 1: Size 9, starting value 11:   17  16  15  14  13   18   5   4   3  12   19   6   1   2  11   20   7   8   9  10   21  22  23  24  25   75  74  73  72  71  70  69  68  67   76  47  46  45  44  43  42  41  66   77  48  27  26  25  24  23  40  65   78  49  28  15  14  13  22  39  64   79  50  29  16  11  12  21  38  63   80  51  30  17  18  19  20  37  62   81  52  31  32  33  34  35  36  61   82  53  54  55  56  57  58  59  60   83  84  85  86  87  88  89  90  91

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 14. char greeting[] = "Hello, world!";

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! greeting = "Good-bye!"; strcpy(greeting, "Good-bye!");

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. strcmp(str1, str2);

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: #include <string> using namespace std; string noun, s1, s2, s3; string verb("go"); noun = "computer";

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. s1 = s2 + " and " + s3;

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)

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: An array on steroids! vector<double> salaries; vector<bool> truthTable(10); vector<int> ages = {12, 9, 7, 2};

Vectors, cont’d Index into a vector like an array: ages[2] Use with a standard for loop: Or with a ranged for loop: for (int i = 0; i < ages.size(); i++) { cout << ages[i] << endl; } for (int age : ages) { cout << age << endl; }

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. salaries.push_back(100000.0); salaries.push_back(75000.0); salaries.push_back(150000.0); salaries.push_back(200000.0);

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: v.resize(24) v.reserve(32) v.reserve(v.size() + 10)

Assignment #3.c. Prime Spirals Repeat Assignment #3.b, except use vectors instead of arrays. Instead of printing the numbers in the spiral, print dots and hashes instead. Print a hash (#) if the position corresponds to a prime number. Print a dot (.) if the position corresponds to a composite number. Curious patterns may emerge in the matrix!

Assignment #3.c. Prime Spirals, cont’d Example Size 25, starting at 11: #.........#.....#.#.....# .....#...#.......#....... ....#.......#...#........ .......#.............#... ........#.....#.....#.#.. .#.#.........#.#...#..... #...#.....#.#...........# .........#.#...#.#.#.#.#. ....#.#...#.#...#........ .#...#.#.#...#.#.....#... ..#...........#...#...#.. .............#...#.....#. #.#.....#.#.#.....#...... ...........#.#.#.....#.#. #...#.#...#.....#...#.#.. .#.#.....#.....#......... ........#.....#.....#...# ...#.........#...#.#...#. ....#.#.....#.....#...... .......#...#.#...#....... #...#.........#.......#.. ...#.....#.......#....... ..#.#.....#...#.....#...# .....#.#................. ..#...#.#...........#....

Assignment #3.c. Prime Spirals, cont’d Are there patterns in the prime numbers?