Fundamentals of Programming Session 25
|
|
- Austen Sharp
- 6 years ago
- Views:
Transcription
1 Fundamentals of Programming Session 25 Instructor: Reza Entezari-Maleki 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology
2 Outlines Default Memberwise Assignment Union Introducing enum File Processing Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File 2
3 Default Memberwise Assignment 3 Assigning objects Assignment operator (=) Can assign one object to another of same type Default: memberwise assignment Each right member assigned individually to left member Passing, returning objects Objects passed as function arguments Objects returned from functions Default: pass-by-value Copy of object passed, returned Copy constructor o Copy original values into new object
4 4 1 // Demonstrating that class objects can be assigned 2 // to each other using default memberwise assignment. 3 #include <iostream> 4 using std::cout; 5 using std::endl; 6 // class Date definition 7 class Date { 8 public: 9 Date( int = 1, int = 1, int = 1990 ); // default constructor 10 void print(); 11 private: 12 int month; 13 int day; 14 int year; 15 }; // end class Date
5 5 16 // Date constructor with no range checking 17 Date::Date( int m, int d, int y ) 18 { 19 month = m; 20 day = d; 21 year = y; 22 } // end Date constructor 23 // print Date in the format mm-dd-yyyy 24 void Date::print() 25 { 26 cout << month << '-' << day << '-' << year; 27 } // end function print 28 int main() 29 { 30 Date date1( 7, 4, 2002 ); 31 Date date2; // date2 defaults to 1/1/1990
6 32 cout << "date1 = "; 33 date1.print(); 34 cout << "\ndate2 = "; 35 date2.print(); 36 date2 = date1; // default memberwise assignment 37 cout << "\n\nafter default memberwise assignment, date2 = "; 38 date2.print(); 39 cout << endl; 40 return 0; 41 } // end main date1 = date2 = After default memberwise assignment, date2 =
7 Union Union Memory that contains a variety of objects Data members share space Only contains one data member at a time Only the last data member defined can be accessed Declaration same as class or struct union Number { }; int x; float y; Union myobject; 7
8 8 1 // Fig. 20.8: fig20_08.cpp 2 // An example of a union. 3 #include <iostream> 4 using std::cout; 5 using std::endl; 6 // define union Number 7 union Number { 8 int integer1; 9 double double1; 10 }; // end union Number 11 int main() 12 { 13 Number value; // union variable 14 value.integer1 = 100; // assign 100 to member integer1 15 cout << "Put a value in the integer member\n" 16 << "and print both members.\nint: " 17 << value.integer1 << "\ndouble: " << value.double1 18 << endl;
9 19 value.double1 = 100.0; // assign to member double1 20 cout << "Put a value in the floating member\n" 21 << "and print both members.\nint: " 22 << value.integer1 << "\ndouble: " << value.double1 23 << endl; 24 return 0; 25 } // end main 9 Put a value in the integer member and print both members. int: 100 double: e+061 Put a value in the floating member and print both members. int: 0 double: 100
10 10 1 // Fig. 20.9: fig20_09.cpp 2 // Using an anonymous union. 3 #include <iostream> 4 using std::cout; 5 using std::endl; 6 int main() 7 { 8 // declare an anonymous union 9 // members integer1, double1 and charptr share the same space 10 union { 11 int integer1; 12 double double1; 13 char *charptr; 14 }; // end anonymous union 15 // declare local variables 16 int integer2 = 1; 17 double double2 = 3.3; 18 char *char2ptr = "Anonymous";
11 19 // assign value to each union member 20 // successively and print each 21 cout << integer2 << ' '; 22 integer1 = 2; 23 cout << integer1 << endl; cout << double2 << ' '; 26 double1 = 4.4; 27 cout << double1 << endl; cout << char2ptr << ' '; 30 charptr = "union"; 31 cout << charptr << endl; 32 return 0; 33 } // end main Anonymous union
12 Introducing enum Enumeration Set of integers with identifiers enum typename {constant1, constant2 }; Constants start at 0 (default), incremented by 1 Constants need unique names Cannot assign integer to enumeration variable Must use a previously defined enumeration type Example enum Status {CONTINUE, WON, LOST}; Status enumvar; enumvar = WON; // cannot do enumvar = 1 12
13 Introducing enum 13 Enumeration constants can have preset values enum Months { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}; Starts at 1, increments by 1 Next: craps simulator Roll two dice 7 or 11 on first throw: player wins 2, 3, or 12 on first throw: player loses 4, 5, 6, 8, 9, 10 Value becomes player's "point" Player must roll his point before rolling 7 to win
14 14 1 // Fig. 3.10: fig03_10.cpp 2 // Craps. 3 #include <iostream> 4 using std::cout; 5 using std::endl; 6 // contains function prototypes for functions srand and rand 7 #include <cstdlib> 8 #include <ctime> // contains prototype for function time 9 int rolldice( void ); // function prototype 10 int main() 11 { 12 // enumeration constants represent game status 13 enum Status { CONTINUE, WON, LOST }; 14 int sum; 15 int mypoint; 16 Status gamestatus; // can contain CONTINUE, WON or LOST
15 15 17 // randomize random number generator using current time 18 srand( time( 0 ) ); 19 sum = rolldice(); // first roll of the dice 20 // determine game status and point based on sum of dice 21 switch ( sum ) { 22 // win on first roll 23 case 7: 24 case 11: 25 gamestatus = WON; 26 break; 27 // lose on first roll 28 case 2: 29 case 3: 30 case 12: 31 gamestatus = LOST; 32 break;
16 16 33 // remember point 34 default: 35 gamestatus = CONTINUE; 36 mypoint = sum; 37 cout << "Point is " << mypoint << endl; 38 break; // optional 39 } // end switch 40 // while game not complete while ( gamestatus == CONTINUE ) { 42 sum = rolldice(); // roll dice again 43 // determine game status 44 if ( sum == mypoint ) // win by making point 45 gamestatus = WON; 46 else 47 if ( sum == 7 ) // lose by rolling 7 48 gamestatus = LOST; 49 } // end while
17 17 50 // display won or lost message 51 if ( gamestatus == WON ) 52 cout << "Player wins" << endl; 53 else 54 cout << "Player loses" << endl; 55 return 0; // indicates successful termination 56 } // end main 57 // roll dice, calculate sum and display results 58 int rolldice( void ) 59 { 60 int die1; 61 int die2; 62 int worksum; 63 die1 = 1 + rand() % 6; // pick random die1 value 64 die2 = 1 + rand() % 6; // pick random die2 value 65 worksum = die1 + die2; // sum die1 and die2
18 66 // display results of this roll 67 cout << "Player rolled " << die1 << " + " << die2 68 << " = " << worksum << endl; 69 return worksum; // return sum of dice 70 } // end function rolldice Player rolled = 7 Player wins Player rolled = 12 Player loses Player rolled = 6 Point is 6 Player rolled = 8 Player rolled = 9 Player rolled = 3 Player rolled = 6 Player wins 18
19 Player rolled = 4 Point is 4 Player rolled = 10 Player rolled = 6 Player rolled = 10 Player rolled = 5 Player rolled = 6 Player rolled = 2 Player rolled = 8 Player rolled = 7 Player loses 19
20 File Processing Storage of data Arrays, variables are temporary Files are permanent Magnetic disk, optical disk, tapes 20
21 Data Hierarchy From smallest to largest Bit (binary digit) 1 or 0 Everything in computer ultimately represented as bits Cumbersome for humans to use Character set Digits, letters, symbols used to represent data Every character represented by 1's and 0's Byte: 8 bits Can store a character (char) 21
22 Data Hierarchy From smallest to largest (continued) Field: group of characters with some meaning Your name Record: group of related fields struct or class in C++ Each field associated with same employee Record key: field used to uniquely identify record File: group of related records Sequential file: records stored by key Database: group of related files 22
23 Data Hierarchy Sally Tom Judy Iris Randy Black Blue Green Orange Red File Judy Judy Green Field Byte (ASCII character J) Record 1 Bit 23
24 Files and Streams C++ views file as sequence of bytes Ends with end-of-file marker n-1... end-of-file marker When file opened Object created, stream associated with it cin, cout, etc. created when <iostream> included Communication between program and file/device 24
25 Files and Streams To perform file processing Include <iostream> and <fstream> Class templates basic_ifstream (input) basic_ofstream (output) basic_fstream (I/O) 25
26 Creating a Sequential-Access File C++ imposes no structure on file Concept of "record" must be implemented by programmer To open file, create objects Classes ifstream (input only) ofstream (output only) fstream (I/O) Constructors take file name and file-open mode ofstream outclientfile( "filename", fileopenmode ); To attach a file later Ofstream outclientfile; outclientfile.open( "filename", fileopenmode); 26
27 Creating a Sequential-Access File File-open modes Mode ios::app ios::in ios::out ios::binary Description Write all output to the end of the file. Open a file for input. Open a file for output. Open a file for binary (i.e., non-text) input or output. ofstream opened for output by default ofstream outclientfile( "clients.dat", ios::out ); ofstream outclientfile( "clients.dat"); 27
28 Creating a Sequential-Access File Operations Overloaded operator!!outclientfile Returns nonzero (true) if badbit or failbit set Opened non-existent file for reading, wrong permissions Operations Writing to file (just like cout) outclientfile << myvariable Closing file outclientfile.close() Automatically closed when destructor called 28
29 29 1 #include <iostream> 2 using std::cout; 3 using std::cin; 4 using std::ios; 5 using std::cerr; 6 using std::endl; 7 #include <fstream> 8 using std::ofstream; 9 #include <cstdlib> // exit prototype 10 int main() 11 { 12 // ofstream constructor opens file 13 ofstream outclientfile( "clients.dat", ios::out ); 14 // exit program if unable to create file 15 if (!outclientfile ) { // overloaded! operator 16 cerr << "File could not be opened" << endl; 17 exit( 1 ); 18 } // end if
30 30 19 cout << "Enter the account, name, and balance." << endl 20 << "Enter end-of-file to end input.\n? "; 21 int account; 22 char name[ 30 ]; 23 double balance; 24 // read account, name and balance from cin, then place in file 25 while ( cin >> account >> name >> balance ) { 26 outclientfile << account << ' ' << name << ' ' << balance 27 << endl; 28 cout << "? "; 29 } // end while 30 return 0; // ofstream destructor closes file 31 } // end main
31 Enter the account, name, and balance. Enter end-of-file to end input.? 100 Jones 24.98? 200 Doe ? 300 White 0.00? 400 Stone ? 500 Rich ? ^Z 31
32 Reading Data from a Sequential-Access File Reading files ifstream inclientfile( "filename", ios::in ); Overloaded!!inClientFile tests if file was opened properly while (inclientfile >> myvariable) Stops when EOF found (gets value 0) 32
33 33 1 #include <iostream> 2 using std::cout; 3 using std::cin; 4 using std::ios; 5 using std::cerr; 6 using std::endl; 7 using std::left; 8 using std::right; 9 using std::fixed; 10 using std::showpoint; 11 #include <fstream> 12 using std::ifstream; 13 #include <iomanip> 14 using std::setw; 15 using std::setprecision; 16 #include <cstdlib> // exit prototype 17 void outputline( int, const char * const, double );
34 34 18 int main() 19 { 20 // ifstream constructor opens the file 21 ifstream inclientfile( "clients.dat", ios::in ); 22 // exit program if ifstream could not open file 23 if (!inclientfile ) { 24 cerr << "File could not be opened" << endl; 25 exit( 1 ); 26 } // end if 27 int account; 28 char name[ 30 ]; 29 double balance; 30 cout << left << setw( 10 ) << "Account" << setw( 13 ) 31 << "Name" << "Balance" << endl << fixed << showpoint; 32 // display each record in file 33 while ( inclientfile >> account >> name >> balance ) 34 outputline( account, name, balance ); 35 return 0; // ifstream destructor closes the file 36 } // end main
35 37 // display single record from file 38 void outputline( int account, const char * const name, 39 double balance ) 40 { 41 cout << left << setw( 10 ) << account << setw( 13 ) << name 42 << setw( 7 ) << setprecision( 2 ) << right << balance 43 << endl; } // end function outputline Account Name Balance 100 Jones Doe White Stone Rich
Fundamentals of Programming Session 27
Fundamentals of Programming Session 27 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines
More informationIS 0020 Program Design and Software Tools
1 IS 0020 Program Design and Software Tools Stack/Queue - File Processing Lecture 10 March 29, 2005 Introduction 2 Storage of data Arrays, variables are temporary Files are permanent Magnetic disk, optical
More informationLecture 9. Introduction
Lecture 9 File Processing Streams Stream I/O template hierarchy Create, update, process files Sequential and random access Formatted and raw processing Namespaces Lec 9 Programming in C++ 1 Storage of
More informationChapter 8 File Processing
Chapter 8 File Processing Outline 1 Introduction 2 The Data Hierarchy 3 Files and Streams 4 Creating a Sequential Access File 5 Reading Data from a Sequential Access File 6 Updating Sequential Access Files
More informationFunctions and Recursion
Functions and Recursion 1 Outline Introduction Program Components in C++ Math Library Functions Functions Function Definitions Function Prototypes Header Files Random Number Generation Example: A Game
More informationFundamentals of Programming Session 28
Fundamentals of Programming Session 28 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2014 These slides have been created using Deitel s slides Sharif University of Technology Outlines
More informationChapter 3 - Functions
Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Progra m Components in C++ 3.3 Ma th Libra ry Func tions 3.4 Func tions 3.5 Func tion De finitions 3.6 Func tion Prototypes 3.7 He a de r File s 3.8
More informationChapter 3 - Functions
Chapter 3 - Functions 1 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number Generation
More informationChapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++
Chapter 3 - Functions 1 Chapter 3 - Functions 2 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3. Functions 3.5 Function Definitions 3.6 Function Prototypes 3. Header Files 3.8
More informationC++ Programming Lecture 10 File Processing
C++ Programming Lecture 10 File Processing By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department Outline Introduction. The Data Hierarchy. Files and Streams. Creating a Sequential
More informationTutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations
Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations Outline 12.1 Test-Driving the Craps Game Application 12.2 Random Number Generation 12.3 Using an enum in the Craps
More informationIS 0020 Program Design and Software Tools
1 IS 0020 Program Design and Software Tools Exception Handling, File Processing Lecture 11 March 30, 2004 Introduction 2 Exceptions Indicates problem occurred in program Not common An "exception" to a
More information6.5 Function Prototypes and Argument Coercion
6.5 Function Prototypes and Argument Coercion 32 Function prototype Also called a function declaration Indicates to the compiler: Name of the function Type of data returned by the function Parameters the
More informationEAS230: Programming for Engineers Lab 1 Fall 2004
Lab1: Introduction Visual C++ Objective The objective of this lab is to teach students: To work with the Microsoft Visual C++ 6.0 environment (referred to as VC++). C++ program structure and basic input
More informationC Functions. 5.2 Program Modules in C
1 5 C Functions 5.2 Program Modules in C 2 Functions Modules in C Programs combine user-defined functions with library functions - C standard library has a wide variety of functions Function calls Invoking
More informationChapter 15 - C++ As A "Better C"
Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference
More informationChapter 14 File Processing
Chapter 14 File Processing Outline 14.1 Introd uction 14.2 The Data Hie rarchy 14.3 File s and Stre am s 14.4 Cre ating a Se q ue ntialacce ss File 14.5 Re ad ing Data from a Se q ue ntialacce ss File
More informationIntroduction to Programming
Introduction to Programming session 5 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2010 These slides are created using Deitel s slides Sahrif University of Technology Outlines
More informationby Pearson Education, Inc. All Rights Reserved. 2
The C++ standard libraries provide an extensive set of input/output capabilities. C++ uses type-safe I/O. Each I/O operation is executed in a manner sensitive to the data type. If an I/O member function
More informationChapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types
Chapter 4 - Arrays 1 4.1 Introduction 4.2 Arrays 4.3 Declaring Arrays 4.4 Examples Using Arrays 4.5 Passing Arrays to Functions 4.6 Sorting Arrays 4.7 Case Study: Computing Mean, Median and Mode Using
More informationIntroduction to Programming
Introduction to Programming session 6 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Spring 2011 These slides are created using Deitel s slides Sharif University of Technology Outlines
More informationChapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program)
Chapter - Arrays 1.1 Introduction 2.1 Introduction.2 Arrays.3 Declaring Arrays. Examples Using Arrays.5 Passing Arrays to Functions.6 Sorting Arrays. Case Study: Computing Mean, Median and Mode Using Arrays.8
More informationPIC10B/1 Winter 2014 Exam I Study Guide
PIC10B/1 Winter 2014 Exam I Study Guide Suggested Study Order: 1. Lecture Notes (Lectures 1-8 inclusive) 2. Examples/Homework 3. Textbook The midterm will test 1. Your ability to read a program and understand
More informationFunctions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.
Functions Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2009 Fall Outline 5.1 Introduction 5.3 Math Library Functions 5.4 Functions 5.5
More informationThis chapter introduces the notion of namespace. We also describe how to manage input and output with C++ commands via the terminal or files.
C++ PROGRAMMING LANGUAGE: NAMESPACE AND MANGEMENT OF INPUT/OUTPUT WITH C++. CAAM 519, CHAPTER 15 This chapter introduces the notion of namespace. We also describe how to manage input and output with C++
More informationChapter 12 - C++ Stream Input/Output
Chapter 12 - C++ Stream Input/Output 1 12.1 Introduction 12.2 Streams 12.2.1 Classic Streams vs. Standard Streams 12.2.2 iostream Library Header Files 12.2.3 Stream Input/Output Classes and Objects 12.3
More informationC Legacy Code Topics. Objectives. In this appendix you ll:
cppfp2_appf_legacycode.fm Page 1 Monday, March 25, 2013 3:44 PM F C Legacy Code Topics Objectives In this appendix you ll: Redirect keyboard input to come from a file and redirect screen output to a file.
More informationC++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.
C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2013 Fall Outline 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.5
More informationOutline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.
Outline Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples. 1 Arrays I Array One type of data structures. Consecutive group of memory locations
More informationDr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)
Lecture 9 Functions Dr M Kasim A Jalil Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Objectives In this chapter, you will learn: To understand how to construct programs modularly
More informationCSE123. Program Design and Modular Programming Functions 1-1
CSE123 Program Design and Modular Programming Functions 1-1 5.1 Introduction A function in C is a small sub-program performs a particular task, supports the concept of modular programming design techniques.
More informationPiyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class
C++ IO C++ IO All I/O is in essence, done one character at a time For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Concept: I/O operations act on streams
More informationFunctions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.
Functions In general, functions are blocks of code that perform a number of pre-defined commands to accomplish something productive. You can either use the built-in library functions or you can create
More informationChapter 2 - Control Structures
Chapter 2 - Control Structures 1 Outline 2.1 Introduction 2.2 Algorithms 2.3 Pseudocode 2.4 Control Structures 2.5 if Selection Structure 2.6 if/else Selection Structure 2.7 while Repetition Structure
More informationBITG 1113: Files and Stream LECTURE 10
BITG 1113: Files and Stream LECTURE 10 1 LEARNING OUTCOMES At the end of this lecture, you should be able to: 1. Describe the fundamentals of input & output files. 2. Use data files for input & output
More informationChapter 3 - Functions
Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number
More informationfor (int i = 1; i <= 3; i++) { do { cout << "Enter a positive integer: "; cin >> n;
// Workshop 1 #include using namespace std; int main () int n, k; int sumdigits; for (int i = 1; i n; cin.clear (); cin.ignore (100,
More informationIntroduction to C++ Systems Programming
Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions
More informationIS 0020 Program Design and Software Tools
1 Introduction 2 IS 0020 Program Design and Software Tools File Processing, Standard Template Library Lecture 10 Storage of data Arrays, variables are temporary Files are permanent Magnetic disk, optical
More informationObjectivities. Experiment 1. Lab6 Array I. Description of the Problem. Problem-Solving Tips
Lab6 Array I Objectivities 1. Using rand to generate random numbers and using srand to seed the random-number generator. 2. Declaring, initializing and referencing arrays. 3. The follow-up questions and
More informationOperator Overloading in C++ Systems Programming
Operator Overloading in C++ Systems Programming Operator Overloading Fundamentals of Operator Overloading Restrictions on Operator Overloading Operator Functions as Class Members vs. Global Functions Overloading
More informationAdvanced I/O Concepts
Advanced Object Oriented Programming Advanced I/O Concepts Seokhee Jeon Department of Computer Engineering Kyung Hee University jeon@khu.ac.kr 1 1 Streams Diversity of input sources or output destinations
More informationFundamentals of Programming Session 24
Fundamentals of Programming Session 24 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines
More informationInput and Output File (Files and Stream )
Input and Output File (Files and Stream ) BITE 1513 Computer Game Programming Week 14 Scope Describe the fundamentals of input & output files. Use data files for input & output purposes. Files Normally,
More informationFunction Call Stack and Activation Records
71 Function Call Stack and Activation Records To understand how C performs function calls, we first need to consider a data structure (i.e., collection of related data items) known as a stack. Students
More informationChapter 14 Sequential Access Files
Chapter 14 Sequential Access Files Objectives Create file objects Open a sequential access file Determine whether a sequential access file was opened successfully Write data to a sequential access file
More informationData Types. 9. Types. a collection of values and the definition of one or more operations that can be performed on those values
Data Types 1 data type: a collection of values and the definition of one or more operations that can be performed on those values C++ includes a variety of built-in or base data types: short, int, long,
More informationCS201 Solved MCQs.
15.1 Answer each of the following: a. Input/output in C++ occurs as of bytes. b. The stream manipulators that format justification are, and. c. Member function can be used to set and reset format state.
More informationArrays. Week 4. Assylbek Jumagaliyev
Arrays Week 4 Assylbek Jumagaliyev a.jumagaliyev@iitu.kz Introduction Arrays Structures of related data items Static entity (same size throughout program) A few types Pointer-based arrays (C-like) Arrays
More informationChapter 2 - Control Structures
Chapter 2 - Control Structures 1 2.1 Introduction 2.2 Algorithms 2.3 Pseudocode 2.4 Control Structures 2.5 if Selection Structure 2.6 if/else Selection Structure 2.7 while Repetition Structure 2.8 Formulating
More informationChapter 2 - Control Structures
Chapter 2 - Control Structures 1 Outline 2.1 Introduction 2.2 Algorithms 2.3 Pseudocode 2.4 Control Structures 2.5 if Selection Structure 2.6 if/else Selection Structure 2.7 while Repetition Structure
More informationFall 2017 CISC/CMPE320 9/27/2017
Notices: CISC/CMPE320 Today File I/O Text, Random and Binary. Assignment 1 due next Friday at 7pm. The rest of the assignments will also be moved ahead a week. Teamwork: Let me know who the team leader
More informationCS2141 Software Development using C/C++ Stream I/O
CS2141 Software Development using C/C++ Stream I/O iostream Two libraries can be used for input and output: stdio and iostream The iostream library is newer and better: It is object oriented It can make
More informationA Deeper Look at Classes
A Deeper Look at Classes Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by
More information12/22/11. } Rolling a Six-Sided Die. } Fig 6.7: Rolling a Six-Sided Die 6,000,000 Times
} Rolling a Six-Sided Die face = 1 + randomnumbers.nextint( 6 ); The argument 6 called the scaling factor represents the number of unique values that nextint should produce (0 5) This is called scaling
More informationIntroduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts
Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter
More informationPointers and Strings Prentice Hall, Inc. All rights reserved.
Pointers and Strings 1 sizeof operator Pointer Expressions and Pointer Arithmetic Relationship Between Pointers and Arrays Arrays of Pointers Case Study: Card Shuffling and Dealing Simulation sizeof operator
More information1 // Fig. 6.13: time2.cpp 2 // Member-function definitions for class Time. 3 #include <iostream> Outline. 4 5 using std::cout; 6 7 #include <iomanip>
CISC11 Introduction to Computer Science Dr. McCoy Lecture 20 November, 2009. Using Default Arguments with Constructors Constructors Can specify default arguments Default constructors Defaults all arguments
More informationConvenient way to deal large quantities of data. Store data permanently (until file is deleted).
FILE HANDLING Why to use Files: Convenient way to deal large quantities of data. Store data permanently (until file is deleted). Avoid typing data into program multiple times. Share data between programs.
More informationStrings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts
Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter
More informationKingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS
Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 1 ARRAYS Arrays 2 Arrays Structures of related data items Static entity (same size
More informationObjects and streams and files CS427: Elements of Software Engineering
Objects and streams and files CS427: Elements of Software Engineering Lecture 6.2 (C++) 10am, 13 Feb 2012 CS427 Objects and streams and files 1/18 Today s topics 1 Recall...... Dynamic Memory Allocation...
More information57:017, Computers in Engineering C++ Classes
57:017, Computers in Engineering C++ Classes Copyright 1992 2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Introduction Object-oriented programming (OOP) Encapsulates
More informationIntroduction to Programming session 24
Introduction to Programming session 24 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2010 These slides are created using Deitel sslides Sharif Universityof Technology Outlines Introduction
More informationFile Operations. Lecture 16 COP 3014 Spring April 18, 2018
File Operations Lecture 16 COP 3014 Spring 2018 April 18, 2018 Input/Ouput to and from files File input and file output is an essential in programming. Most software involves more than keyboard input and
More informationCSC 138 Structured Programming CHAPTER 4: TEXT FILE [PART 1]
CSC 138 Structured Programming CHAPTER 4: TEXT FILE [PART 1] LEARNING OBJECTIVES Upon completion, you should be able to: o define C++ text files o explain the benefits of using I/O file processing o explain
More informationCHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad
CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING Dr. Shady Yehia Elmashad Outline 1. Introduction to C++ Programming 2. Comment 3. Variables and Constants 4. Basic C++ Data Types 5. Simple Program: Printing
More informationC++ How to Program, 9/e by Pearson Education, Inc. All Rights Reserved.
C++ How to Program, 9/e 1992-2014 by Pearson Education, Inc. Experience has shown that the best way to develop and maintain a large program is to construct it from small, simple pieces, or components.
More informationChapter 18 - C++ Operator Overloading
Chapter 18 - C++ Operator Overloading Outline 18.1 Introduction 18.2 Fundamentals of Operator Overloading 18.3 Restrictions on Operator Overloading 18.4 Operator Functions as Class Members vs. as friend
More informationFile I/O. File Names and Types. I/O Streams. Stream Extraction and Insertion. A file name should reflect its contents
File I/O 1 File Names and Types A file name should reflect its contents Payroll.dat Students.txt Grades.txt A file s extension indicates the kind of data the file holds.dat,.txt general program input or
More informationLecture 5 Files and Streams
Lecture 5 Files and Streams Introduction C programs can store results & information permanently on disk using file handling functions These functions let you write either text or binary data to a file,
More informationSystem Design and Programming II
System Design and Programming II CSCI 194 Section 01 CRN: 10968 Fall 2017 David L. Sylvester, Sr., Assistant Professor Chapter 12 Advanced File Operation File Operations A file is a collection of data
More informationCSc Introduc/on to Compu/ng. Lecture 19 Edgardo Molina Fall 2011 City College of New York
CSc 10200 Introduc/on to Compu/ng Lecture 19 Edgardo Molina Fall 2011 City College of New York 18 Standard Device Files Logical file object: Stream that connects a file of logically related data to a program
More informationby Pearson Education, Inc. All Rights Reserved. 2
In Fig. 17.4, the file is to be opened for output, so an ofstream object is created. Two arguments are passed to the object s constructor the filename and the file-open mode (line 12). For an ofstream
More informationChapter 2 - Control Structures
Chapter 2 - Control Structures 1 2.11 Assignment Operators 2.12 Increment and Decrement Operators 2.13 Essentials of Counter-Controlled Repetition 2.1 for Repetition Structure 2.15 Examples Using the for
More informationC++ Basics. Brian A. Malloy. References Data Expressions Control Structures Functions. Slide 1 of 24. Go Back. Full Screen. Quit.
C++ Basics January 19, 2012 Brian A. Malloy Slide 1 of 24 1. Many find Deitel quintessentially readable; most find Stroustrup inscrutable and overbearing: Slide 2 of 24 1.1. Meyers Texts Two excellent
More informationReview for COSC 120 8/31/2017. Review for COSC 120 Computer Systems. Review for COSC 120 Computer Structure
Computer Systems Computer System Computer Structure C++ Environment Imperative vs. object-oriented programming in C++ Input / Output Primitive data types Software Banking System Compiler Music Player Text
More information엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED
엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED Outline - Function Definitions - Function Prototypes - Data
More informationAn inline function is one in which the function code replaces the function call directly. Inline class member functions
Inline Functions An inline function is one in which the function code replaces the function call directly. Inline class member functions if they are defined as part of the class definition, implicit if
More informationArrays. Outline. Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays Prentice Hall, Inc. All rights reserved.
Arrays 1 Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays Multidimensional Arrays 2 Multiple subscripts a[ i ][ j ] Tables with rows and columns Specify row, then column
More informationFunctions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single
Functions in C++ Problem-Solving Procedure With Modular Design: Program development steps: Analyze the problem Develop a solution Code the solution Test/Debug the program C ++ Function Definition: A module
More information10/23/02 21:20:33 IO_Examples
1 Oct 22 22:07 2000 extractor1.c Page 1 istream &operator>>( istream &in, Point &p ){ char junk; in >> junk >> p.x >> junk >> p.y >> junk; return in; 2 Oct 22 22:07 2000 extractor2.c Page 1 istream &operator>>(
More informationThe Hong Kong Polytechnic University Faculty of Engineering
The Hong Kong Polytechnic University Faculty of Engineering Programme(s) : BEng(Hons) in Transportation Systems Engineering (41481, 41481SY) BSc(Hons) in Internet and Multimedia Technologies (42477) Higher
More informationWeek 3: File I/O and Formatting 3.7 Formatting Output
Week 3: File I/O and Formatting 3.7 Formatting Output Formatting: the way a value is printed: Gaddis: 3.7, 3.8, 5.11 CS 1428 Fall 2014 Jill Seaman spacing decimal points, fractional values, number of digits
More informationcs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.
cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... today: language basics: identifiers, data types, operators, type conversions, branching and looping, program structure
More informationWeek 5: Files and Streams
CS319: Scientific Computing (with C++) Week 5: and Streams 9am, Tuesday, 12 February 2019 1 Labs and stuff 2 ifstream and ofstream close a file open a file Reading from the file 3 Portable Bitmap Format
More informationAssignment Checklist. Prelab Activities. Lab Exercises. Labs Provided by Instructor. Postlab Activities. Section:
7 Arrays Now go, write it before them in a table, and note it in a book. Isaiah 30:8 To go beyond is as wrong as to fall short. Confucius Begin at the beginning, and go on till you come to the end: then
More informationCS201 Latest Solved MCQs
Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability
More informationIntroduction. Lecture 5 Files and Streams FILE * FILE *
Introduction Lecture Files and Streams C programs can store results & information permanently on disk using file handling functions These functions let you write either text or binary data to a file, and
More informationChapter 12. Streams and File I/O. Copyright 2010 Pearson Addison-Wesley. All rights reserved
Chapter 12 Streams and File I/O Copyright 2010 Pearson Addison-Wesley. All rights reserved Learning Objectives I/O Streams File I/O Character I/O Tools for Stream I/O File names as input Formatting output,
More informationCHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad
CHAPTER 3 ARRAYS Dr. Shady Yehia Elmashad Outline 1. Introduction 2. Arrays 3. Declaring Arrays 4. Examples Using Arrays 5. Multidimensional Arrays 6. Multidimensional Arrays Examples 7. Examples Using
More informationPreview 8/28/2018. Review for COSC 120 (File Processing: Reading Data From a File)
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
More informationChapter 12. Streams and File I/O. Copyright 2016 Pearson, Inc. All rights reserved.
Chapter 12 Streams and File I/O Copyright 2016 Pearson, Inc. All rights reserved. Learning Objectives I/O Streams File I/O Character I/O Tools for Stream I/O File names as input Formatting output, flag
More informationMore C++ Classes. Systems Programming
More C++ Classes Systems Programming C++ Classes Preprocessor Wrapper Time Class Case Study Class Scope and Assessing Class Members Using handles to access class members Access and Utility Functions Destructors
More informationChapter 12. Streams and File I/O
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, flag settings Introduction Streams Special objects Deliver
More informationCHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object
CHAPTER 1 Introduction to Computers and Programming 1 1.1 Why Program? 1 1.2 Computer Systems: Hardware and Software 2 1.3 Programs and Programming Languages 8 1.4 What is a Program Made of? 14 1.5 Input,
More informationStreams in C++ Stream concept. Reference information. Stream type declarations
Stream concept A stream represent a sequence of bytes arriving, being retrieved, being stored, or being sent, in order. A stream is continuos and offer sequential access to the data. Each byte can be read
More informationStreams. Rupesh Nasre.
Streams Rupesh Nasre. OOAIA January 2018 I/O Input stream istream cin Defaults to keyboard / stdin Output stream ostream cout std::string name; std::cout > name; std::cout
More informationNon-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.
, ean, arithmetic s s on acters Comp Sci 1570 Introduction to C++ Outline s s on acters 1 2 3 4 s s on acters Outline s s on acters 1 2 3 4 s s on acters ASCII s s on acters ASCII s s on acters Type: acter
More informationC++ Input/Output: Streams
C++ Input/Output: Streams Basic I/O 1 The basic data type for I/O in C++ is the stream. C++ incorporates a complex hierarchy of stream types. The most basic stream types are the standard input/output streams:
More information