Announcements Midterm2 on April 18 th Monday at 19:40 This week recitations, we will solve sample midterm questions. I will also send previous years’ exams.

Slides:



Advertisements
Similar presentations
Computer Science 1620 Loops.
Advertisements

1 11/3/08CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
Computer Science 1620 Variables and Memory. Review Examples: write a program that calculates and displays the average of the numbers 45, 69, and 106.
Chapter 5: Loops and Files.
1 10/29/07CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
CS 1 Lesson 5 Loops and Files CS 1 -- John Cole.
1 10/25/06CS150 Introduction to Computer Science 1 Reading from and Writing to Files.
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
STREAMS AND FILES OVERVIEW.  Many programs are "data processing" applications  Read the input data  Perform sequence of operations on this data  Write.
Announcements 1st homework is due on July 16, next Wednesday, at 19:00 Submit to SUCourse About the homework: Add the following at the end of your code.
CS Class 13 Today  File I/O (reading from and writing to files)  Reading until EOF  Formatting output  Nested Loops Announcements  Programming.
Introduction to Programming (in C++) Algorithms on sequences. Reasoning about loops: Invariants. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Announcements HW3 grades will be announced this week HW4 is due this week Final exam on August 25, 2010, Wednesday at 09:00 Duration is about 140 minutes.
File I/O ifstreams and ofstreams Sections 11.1 &
Chapter 9 I/O Streams and Data Files
1 CS161 Introduction to Computer Science Topic #13.
File Input and Output in C++. Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) Keyboard Screen executing program input data.
Stream Processing and stream operations for I/O (Input / Output) We’ll see section 6.3 and 6.4 (some parts excluded) Different methods of word and number.
 Wednesday, 9/18/02, Slide #1 CS106 Introduction to CS1 Wednesday, 9/18/02  QUESTIONS?? HW #1 due today at 5!!  Today: Loops, and two new data types.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
Chapter 6 Looping CS185/09 - Introduction to Programming Caldwell College.
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University.
Introduction to C++ Version 1.1. Topics C++ Structure Primitive Data Types I/O Casting Strings Control Flow.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
CS101 Computer Programming I Chapter 4 Extra Examples.
Control Structures Repetition or Iteration or Looping Part II.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
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.
Before we get started…. First, a few things… Weighted Grading System Programming Style Submitting your assignments… The char and string variable types.
REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled.
Loops and Files. 5.1 The Increment and Decrement Operators.
Looping ROBERT REVAES. Logical Operators  && AND  Both have to be true for it to evaluate to be true.  || OR  One or the other has to be true for.
Calvin College Controlling Behavior The if, switch and for Statements.
CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.
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.
Input/Output CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
Input/Output. Objectives In this chapter you will: Learn what a stream is and examine input and output streams Explore how to use the input stream functions.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
CS162 External Data Files 1 Today in CS162 External Files What is an external file? How do we save data in a file?
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
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.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students File Input and Output Checking input for errors.
CHARACTER INPUT / OUTPUT AND INPUT VALIDATION. Introduction Input and output devices: keyboards, disk drives, mouse, monitors, printers. I/O functions.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
Announcements Extra Lecture Tuesday ( today ) 20 :40 for 1 hour Tuesday regular lecture at 16:40 for 1 hour You may see Midterm1 exam papers Wednesday.
Chapter 6 Looping. 2 l A loop is a repetition control structure. l it causes a single statement or block to be executed repeatedly What is a loop?
Loop Design What goes into coding a loop. Considerations for Loop Design ● There are basically two kinds of loops: ● Those that form some accumulated.
ifstreams and ofstreams
Announcements Midterm 2 is on 5th of December, Saturday, 10:00 – 12:00
Announcements HW6 due this Wednesday
Announcements Homework 5 is due on Wednesday, November 29th next week.
Chapter 2 part #3 C++ Input / Output
TOPIC 4: REPETITION CONTROL STRUCTURE
Programming Funamental slides
Alternate Version of STARTING OUT WITH C++ 4th Edition
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.
Today’s Lecture I/O Streams Tools for File I/O
Announcements HW6 due this Wednesday
Chapter 3 Input output.
Let’s all Repeat Together
Chapter 2 part #3 C++ Input / Output
Input Validation CSCE 121 Based on slides created by Carlos Soto.
Presentation transcript:

Announcements Midterm2 on April 18 th Monday at 19:40 This week recitations, we will solve sample midterm questions. I will also send previous years’ exams this week. Detailed about the midterm will also be sent today. Extra Recitations this week: 12 April Tuesday 14:40 – 16:30 in FENS L April Wednesday 10:40 – 12:30 in FENS L April Wednesday 12:40 – 14:30 in FENS L April Wednesday 15:40 – 17:30 in FENS L055

Announcements Homework 5 is due on Saturday, April 16 th this week Midterm2 on April 18 th Monday at 19:40 Midterm Classrooms: if (LastName <= "Çoruh") cout << " FENS G077 " << endl; else if ("Demir" <= LastName <= "Kantoğlu") cout << " FMAN 1099 " << endl; else if ("Kaplan" <= LastName <= "Örs") cout << " FASS G062 " << endl; else if ("Öz" <= LastName <= "Soylu") cout << " FENS L045 " << endl; else if ("Şahin" <= LastName <= "Tüysüz") cout << " FENS G032 " << endl; else if ("Uçar" <= LastName) cout << " FENS G035 " << endl;

Stream Processing and stream operations for I/O (Input / Output) We’ll see section 6.3 and 6.4 (some parts excluded) Different methods of word and number input processing simple application: counting words of an input stream (most famous example is cin) a text file different characteristics of cin (mostly not in the book) section 9.1, 9.2 (and maybe 9.3 in recitations) input and output operations on streams reading a full line into a string reading character by character Some stuff is not in the book.

What’s an I/O (Input/Output) Stream? A sequence of characters flowing between the I/O devices and programs therefore it is a buffer area for I/O We extract and insert using >> and << operators respectively cin is the standard input stream (i.e. keyboard) cout is the standard output stream (i.e. monitor) We also have file streams (for file I/O) that we will see later >> Ali Veli 45 Ahmet cs201 << John George 3 Mike Joe

Counting Words of Keyboard Input Problem: where to stop processing, if number of inputs is not known – 2 solutions until a sentinel value applicable to number processing as well (have seen before) until the end of input stream end-of-file indicator (Ctrl-Z in Windows) - we will see Sentinel based solution - See sentinel.cpp Input and count words until the sentinel value (in this example, "end") is entered. Input may be entered in different lines the sentinel value ("end") should not happen in the text of which you want to count words otherwise you do not count the rest can be applied to counting numbers as well without any change just enter numbers instead of words But it does not check whether the entered value is a valid number or not

Counting Words of Keyboard Input Non-sentinel version - See countw.cpp string word; int numWords = 0; while (cin >> word) { numWords++; } cout << "number of words read = "<< numWords << endl; Process until the end of stream Input may be entered in different lines end of stream is specified by end-of-file character Ctrl-Z Type Ctrl-Z (press Ctrl first and while it is pressed, type Z) as the first character on a new line when the program runs and waits for more words. That signals the end of input. you may need to press the “enter” key twice in Windows® Similar solutions can be applied to integer/real processing as well we will give examples later read one word and check if successfully read

Detailed Examination of cin The statement cin >> variable reads the value of variable, and returns the remaining stream for other data input cin >> num1 >> str >> mydouble actually works as (((cin >> num1) >> str) >> mydouble) (cin >> variable) results in A non-zero value (the remaining stream), if input operation is successful if there was data and data was of the correct type type is not a problem for strings since every input is string but for numeric data, type is a problem 0, if input operation is not successful (there is no data left – i.e. end of file is reached, or data is of wrong type) The resulting value can be used (interpreted) as a Boolean value (true/false) (e.g. as the condition of an if/while statement)

sum10nums.cpp revisited (not in book) Can we check whether the input is a valid integer before adding up? Yes, see sum10validnums.cpp (not in book) int num, sum, count; sum = 0; // initialize sum cout << "Please enter 10 integers to add up: "; for (count=1; count <= 10; count++) { if (cin >> num) { cout << num << " is a valid entry" << endl; sum += num; // add it to the sum if valid } else // else display a message { cout << "entry #" <<count<<"is invalid"<< endl; } cout << "the sum is: " << sum << endl; read the next number and checks if it is a valid integer

sum10nums.cpp revisited (not in book) This solution works for valid numbers but does not work for invalid numbers as intended actually does not read inputs after the first invalid entry reason is that once an invalid input is detected, some error flags are set automatically, and while they are set, cin does not work in the program you may clear the error flags by cin.clear() however you have to skip the invalid entry since the invalid entry is still in the stream, but how? There is no particular stream member function to skip the next data on the stream. You can skip data on stream by just reading it. Trying to read into an integer variable does not help either. A possible solution is to read it into a string variable. Every word can be read into strings. See sum10validnumsfixed.cpp (not in book) for the fixed program next slide

sum10nums.cpp revisited (not in book) int num, sum, count; string s; sum = 0; //initialize sum cout << "Please enter 10 integers to add up: "; for (count=1; count <= 10; count++) { if (cin >> num) { cout << num << " is a valid entry" << endl; sum += num; // add it to the sum if valid } else { cin.clear(); cin >> s; cout << "entry #" << count << "is invalid“ <<endl; } if input is not valid, clear the error flags and skip the invalid entry read the next number and checks if it is a valid integer

Finding Min/Max of input numbers Iterative search of all candidates if the current candidate is smaller/larger the min/max so far, then set the candidate as current min/max what is going to be the initial value of current min (or max)? for min: initialize to the possible maximum value for max: initialize to the possible minimum value Reason is to make the first input current min (max) Largest int and double values are found in and, respectively (or and ) you’ll need to #include them INT_MAX and INT_MIN are max and min int values DBL_MAX and DBL_MIN are max and min double values What happens if all input numbers are INT_MAX (INT_MIN)? no problem

Example Find min of input values until end-of-input or until an invalid input is entered see mindatainput.cpp (not in the book as is) Study yourselves Modify the program to discard invalid integers Find max repeat for double values

Streams for reading and writing files We’ve seen the standard input stream cin, and the standard output stream cout For reading from the keyboard, writing to the screen Accessible from Other streams let us read from files and write to files Why do we need such a file I/O? Because files are permanently stored; whereas the keyboard entry is for one time and screen output is volatile We can input the same data several times if we use file input Or we can modify the input file and re-run program using the modified data We can save the output for future reference

Streams for reading and writing files syntax for reading and writing is similar to cin and cout, because they are all streams To use a file stream, it must be opened first Opening binds the stream variable to a physical file After opening, I/O to/from this file can be performed. Should close file streams, but happens automatically for input streams when the program finishes. We need to close output streams as will be discussed later cin and cout are not opened and closed, because they are standard streams and compiler knows how to handle them Input files are generally text files that can easily be generated using Notepad.

Input file stream: Note similarity to cin string word; int numWords = 0; // # words read so far while (cin >> word) // while read succeeded read and { numWords++; // count } cout << "number of words read = " << numWords << endl; string word; int numWords = 0; ifstream input; // defining input file stream string filename; cin >> filename; // input the file name input.open(filename.c_str()); // open the file while (input >> word) // while read succeeded from file { numWords++; } cout << "number of words read = " << numWords << endl; See countwfile.cpp counting words from keyboard counting words of a file

Counting words in a file See countw2.cpp Idea is in the previous slide Enhancement: also finds the average word length add the word lengths up and at the end divide it by the word count Study for yourselves find the largest and smallest word in a file

Example (not in book) Find the longest word (max number of characters) in a file. Idea for algorithm/program Read every word, remember the longest word read so far Each time a word is read, compare to longest-so-far. If longer, then there’s a new longest-so-far See longestword.cpp (not in book) why did we initialize maxlength to 0? zero is the minimum possible word length initialization to any negative value would also work what happens if there are more than one words with the same max length in the file? finds the first one (finding all either requires processing the same file twice or requires some other tools that we will learn in a few weeks)

Example (not in book) Count the total number of integers in a file that may also contain non-integer values If you encounter a non-integer data in the file, skip it and continue until the end of the file We have to check the end of file using eof function because extraction ( >> operator) returns false both when end-of-file is reached and when the input is not an integer we have to differentiate between these two cases loop control is until the eof inside loop, check if the input is successful and count accordingly let’s see countintegers.cpp (not in the book)