Preview 8/28/2018. Review for COSC 120 (File Processing: Reading Data From a File)

Similar documents
Review for COSC 120 8/31/2017. Review for COSC 120 Computer Systems. Review for COSC 120 Computer Structure

CS2255 HOMEWORK #1 Fall 2012

C++ Quick Guide. Advertisements

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each):

5. Assuming gooddata is a Boolean variable, the following two tests are logically equivalent. if (gooddata == false) if (!

Introduction to Computer Science Midterm 3 Fall, Points

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Chapter 3: Input/Output

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

CSCE 206: Structured Programming in C++

Text File I/O. #include <iostream> #include <fstream> using namespace std; int main() {

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

Chapter 14 Sequential Access Files

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

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:

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:

Loops and Files. of do-while loop

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

C++ Input/Output Chapter 4 Topics

REPETITION CONTROL STRUCTURE LOGO

BITG 1233: Introduction to C++

DELHI PUBLIC SCHOOL TAPI

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

File Operations. Lecture 16 COP 3014 Spring April 18, 2018

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

CSCS 261 Programming Concepts Exam 1 Fall EXAM 1 VERSION 1 Fall Points. Absolutely no electronic devices may be used during this exam.

File I/O Christian Schumacher, Info1 D-MAVT 2013

Chapter 3 - Functions

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

Chapter 12. Streams and File I/O. Copyright 2016 Pearson, Inc. All rights reserved.

1) You want to determine whether time has run out. The following code correctly implements this:

VuZs Team's Work. CS201 Spring Solved by vuzs Team with Reference Written by Administrator Wednesday, 19 May :52

Chapter 5: Loops and Files

Come and join us at WebLyceum

C++ Programming: From Problem Analysis to Program Design, Third Edition

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

Course "Data Processing" Name: Master-1: Nuclear Energy Session /2018 Examen - Part A Page 1

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

File I/O. File Names and Types. I/O Streams. Stream Extraction and Insertion. A file name should reflect its contents

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Name Section: M/W T/TH Number Definition Matching (8 Points)

CS201 Latest Solved MCQs

Arithmetic Operators. Binary Arithmetic Operators. Arithmetic Operators. A Closer Look at the / Operator. A Closer Look at the % Operator

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Input/Output: Streams

Looping. Arizona State University 1

A SHORT COURSE ON C++

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

I/O streams

causing a set of statements (the body) to be executed repeatedly. C++ provides three control structures to support iteration (or looping).

Chapter 12. Streams and File I/O. Copyright 2010 Pearson Addison-Wesley. All rights reserved

C++ Programming: From Problem Analysis to Program Design, Third Edition

What we will learn about this week:

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

Why Is Repetition Needed?

Topics. Functions. Functions

Homework #3 CS2255 Fall 2012

CSCI 1061U Programming Workshop 2. C++ Basics

Name Section: M/W T/TH Number Definition Matching (6 Points)

CSC 138 Structured Programming CHAPTER 4: TEXT FILE [PART 1]

Fundamentals of Programming Session 27

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Functions and Recursion

Computer Programming : C++

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

6. User Defined Functions I

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

BITG 1113: Files and Stream LECTURE 10

C++ For Science and Engineering Lecture 12

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

Fundamentals of Programming Session 25

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

Absolute C++ Walter Savitch

Functions. Lecture 6 COP 3014 Spring February 11, 2018

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

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

Exam 3 Chapters 7 & 9

Chapter 4 - Notes Control Structures I (Selection)

Chapter 12. Streams and File I/O

120++: a C++ Subset Corresponding to A Project-Based Introduction to C++

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

This chapter introduces the notion of namespace. We also describe how to manage input and output with C++ commands via the terminal or files.

CS2141 Software Development using C/C++ Stream I/O

C++ Final Exam 2017/2018

Week 3: File I/O and Formatting 3.7 Formatting Output

Chapter 3. Numeric Types, Expressions, and Output

CHAPTER 3 Expressions, Functions, Output

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

CS201- Introduction to Programming Current Quizzes

CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

I/O Streams and Standard I/O Devices (cont d.)

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

Scientific Computing

Transcription:

Preview Relational operator If, if--if, nested if statement Logical operators Validating Inputs Compare two c-string Switch Statement Increment decrement operator While, Do-While, For Loop Break, Continue statement Function and Function prototype Local and global variable Parameter passing methods: Call by value, Call by reference 1 (File Processing: Reading Data From a File) Read data From a File 1. include the fstream header file; 2. declare a variable of type ifstream create object to handle a file 3. open the file by using the function open in ifstream object 4. check for an open file error 5. read from the file 6. after each read, check for end-of-file using the eof() member function 7. close the file when access is no longer needed 2 (File Processing: Reading Data From a File) (File Processing: Reading Data From a File more than one time) // This program reads values from the file 'outfile.txt' // and echoes them to the display until a negative value // is read. #include <fstream> #include <cstdlib> // for exit function ifstream indata; // create ifstream object to read a data int num; indata.open("outfile.txt, ios::in); // opens the file if(!indata) // checking whether outfile.txt can open or not cerr << "Error: file could not be opened" << endl; exit(1); indata >> num; while (!indata.eof()) // keep reading until end-of-file cout << "The next number is " << num << endl; indata >> num; // sets EOF flag if no value found indata.close(); //close the file 'outfile.txt' cout << "End-of-file reached.." << endl; Read data more than one time from the beginning of a File clear() seekg(0) Sequence of two function calls let file pointer move to the beginning of a file! 3 4 (File Processing: Reading Data From a File more than one time) (File Processing: Writing Data To a File) // reading a sequential access file example #include <iomanip> #include <fstream> int main() ifstream sequential; sequential.open("out.txt",ios::in); if (!sequential) cerr<<" File cannot be opened this time"<<endl; exit(1); int age; char name[20]; cout <<" List of Man"<<endl; cout <<"Name"<<setw(10)<<"Age \n"; cout <<"----"<<setw(10)<<"--- \n"; while (sequential >> age >>name) if (age > 18) cout <<name<<setw(10)<< age<<endl; sequential.clear(); sequential.seekg(0); cout <<" List of Children"<<endl; cout <<"Name"<<setw(10)<<"Age \n"; cout <<"----"<<setw(10)<<"--- \n"; while (sequential >> age >>name) if (age <= 18) cout <<name<<setw(10)<< age<<endl; return 0; Writing Data To a File 1. include the fstream header file; 2. declare a variable of type ofstream create ofstream object 3. open the file 4. check for an open file error 5. use the file 6. close the file when access is no longer needed 5 6 1

(File Processing: Writing Data To a File) // This program output values from an array // to a file named outfile.txt #include <fstream> #include <cstdlib> // for checking error for opening a file ofstream outdata; int i; int num[5] = 4, 3, 6, 7, 12; (Relational Operators) Relational operators are used to compare numerical values. A comparison result is or. Operator Name Relational Operators Syntax outdata.open("outfile.txt",ios::out);// create a file if(!outdata ) cerr << "Error: file could not be opened" << endl; exit(1); for (i=0; i<5; ++i) outdata << num[i] << endl; // write data to the file outdata.close(); // close file Less Than Less Than or Equal To Greater Than Greater Than or Equal To Not Equal To Equal To a < b a <= b a > b a >= b a!= b a == b 7 8 (The if Statement) (The if Statement) The if statement change the execution flow of a program based on the conditional expression. statement; If <condition> Careful with semicolon in a if statement Ex) if (<condition>); statement k ; statement 1 ; statement 2 ; statement n ; If <condition> is, execute empty statement since there is semicolon. Statement k always executed no matter what <condition> is 9 10 (The if- Statement) (The if--if Statement) ; Statement 2; Statement a1; Statement a2; Statement an; Statement b1; Statement b2; Statement bm; Statement 2 or Block 2 If <condition> if (<conditional expression1>) Statement1; (or block1) if (<conditional expression2>) Statement2; (or block2) Statement3; (or block3) Statement 3 or Block 3 <condition 2> I<condition 1> Statement 2 or Block 2 11 12 2

(The Nested if Statement) An if statement is appears inside another if statement, it is considered nested if statement. if <condition1> if <condition2> Statement1; (or block1) Statement2;(or block2) Statement3; (or block3) If <condition 2> If <condition 1> Statement 3 or Block 3 (Logical Operators) Logical operator connects two or more relational expression into one or reverses the logic of an expression. Operator Name Logical Operators Syntax Logical Negation!E Statement 2 or Block 2 Logical AND E 1 && E 2 Logical OR E 1 E 2 13 14 (Validating Inputs) Each input should be validated by the program. When a program gets an input, the program must validate it. If input is illegal, the program need to display message such as Illegal input! Please provide legal input, and ask a input again. (Compare Two Strings) Cannot compare two C strings (array of character) with the relational operator ==. Define a function to compare two strings Use strcmp function in <cstring> library 15 16 (Conditional Operator? :) (Switch Statement:) C++ & C provides the conditional operator? : It took three operands. The operands, together with the conditional operator, form a conditional expression /* if <condition> is execute statement1 take statement2 otherwise.*/ <condition>? <statement1> : <statement2> switch (expr) case c 1 : statement 1 ; // do statement 1 if expr == c 1 case c 2 : statement 2 ; // do statement 2 if expr == c 2 case c 3 : statement 3 ; // do statement 3 if expr == c 3 case c n : statement n ; // do statement n if expr == c n default: statement; // do statement otherwise 17 18 3

(Increment and Decrement Operators) ++ and are operators that add and subtract 1 from their operands. There are post and pre increment and decrement operators Pre increment: ++a Pre decrement: -- a Post increment a++ Post decrement a (Increment and Decrement Operators) // Pre increment and decrement example int score1 = 5; int score2 = 5 ; cout << ++score1 <<endl; //pre increment cout <<--score2 <<endl ; //pre decrement 19 20 (The while Loop: pre-test) (The do-while Loop: post-test) while (<conditional expression>) Statement; while (<conditional expression>) ; Statement 2 ; Statement n ; while<condition 1> Statement or Block False do statement1; Statement2; ; Statementn; while (<conditional expression>); Statement or Block while<condition 1> False next next 21 22 (The for Loop: free test) (The for Loop) for (startexpression; test_expression; updateexpression) statement; for (startexpression; testexpression; updateexpression) statement 1 ; statement 2 ; ; statement n ; The startexpression may be omitted from inside the for loop s parentheses if it has already been performed or no initialization in needed. // for loop example int count =1; for (; count <= 10; count++) cout << "Round: " << count << endl; 23 24 4

(The for Loop) The updateexpression may be omitted from inside the for loop s parentheses if it is being performed where in the loop or if none is needed. (The break Statement) //break statement inside a while loop int score = 0; // for loop example int count =1; for (; count <= 10; ) ++count ; cout << "Round: " << count << endl; while (score <= 60) cout << " What is your score?" << endl; cin >> score; if (score > 60) cout << " Sorry, You better retake this course!" << endl; cout <<" Congratulation! You finally passed"<<endl; 25 26 (The continue Statement) (User Defined Function) // continue statement The general form of a function definition in C++ is as follows: for (int num =0; num <= 10; num++) if ((num % 2)==0) continue; cout << num << " is odd number"<<endl; Return_type Function_Name (parameter_list ) Local variables declarations; Function_Implementation; 27 28 (The Function Prototype) (Local and Global Variables) One of the most important features of C++ is the function prototypes Function prototypes tells the compiler Name of function Return type Number of parameter list Type of each parameter The compiler use function prototypes to validate function calls. Function prototypes are usually saved in a header file which need to be included in a program. We call a variable as a local variable, if it is defined (declared) locally in a function. Since local variables are defined locally in a function, it can only be visible inside the function. We call a variable as global variable, if it is defined outside all the function in a program. It is visible in any location in the program. 29 30 5

(Parameter Passing in C ++: Call by Value and Call by Reference) // call-by-value and call-by-reference in c++ # include <iostream> int callbyvalue(int); void callbyreference(int &); int a = 10; int b = 10; int c; cout << "before call callbyvalue, a = " << a <<endl; c = callbyvalue(a); cout <<"after call callbyvalue, a = " << a << endl; cout << "before call callbyreference b = " << b <<endl; callbyreference(b); cout <<"after call callbyreference b =" << b << endl; int callbyvalue(int x) x = x + x; return x; void callbyreference(int &x) x += x; (The return Statement) The return statement stops execution and returns to the calling function. When a return statement is executed, the function is terminated immediately at that point, regardless of whether it's in the middle of a loop, etc. 31 32 (The Static Variables) (Default Arguments) Static Variable Defined locally One time initialization It only can be modified inside function, when the function is called It remains in memory until the end of the program It is possible to assign default arguments to function parameters. A default argument is passed to the parameter when the actual argument is left out of the function call. The default arguments are usually listed in the function prototype. 33 34 (Default Arguments) (Overloading Functions) // This program shows a example of default arguments #include <iomanip> // function prototype with default arguments void LunchSpecial (char []= "Sandwitch", char [] ="Toco"); LunchSpecial(); LunchSpecial("Hamsandwich"); LunchSpecial("Hamburger", "chiken"); void LunchSpecial (char x[], char y[]) cout << "Today's Lunch Special: " << x <<" and " << y <<endl; In function overloading, the function is said to be overloaded when same name is given to different functions. However, the functions will differ at least in any one of the these. The number of parameters, The data type of parameters, The order of appearance These three together are referred to as the function signature. 35 36 6

(Overloading Functions) (Overloading Functions) void print(int i) cout << " Here is int " << i << endl; void print(double f) cout << " Here is float " << f << endl;??? void print(char* c) cout << " Here is char* " << c << endl; print(10); print(10.10); print("ten"); 37 38 7