Fondamenti di C++ - Cay Horstmann 1



Similar documents
D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

CISC 181 Project 3 Designing Classes for Bank Accounts

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Passing 1D arrays to functions.

C++ Language Tutorial

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

CSCI-B 565 DATA MINING Project Report for K-means Clustering algorithm Computer Science Core Fall 2012 Indiana University

Answers to Review Questions Chapter 7

Moving from CS 61A Scheme to CS 61B Java

Integrating the C++ Standard Template Library Into the Undergraduate Computer Science Curriculum

Object Oriented Software Design II

D06 PROGRAMMING with JAVA

C++ INTERVIEW QUESTIONS

Illustration 1: Diagram of program function and data flow

Answers to Selected Exercises

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

D06 PROGRAMMING with JAVA

ICOM 4015: Advanced Programming

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Variables, Constants, and Data Types

7.7 Case Study: Calculating Depreciation

D06 PROGRAMMING with JAVA

C++ Input/Output: Streams

Inheritance, overloading and overriding

Moving from C++ to VBA

Binary storage of graphs and related data

Basics of I/O Streams and File I/O

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output

Chapter One Introduction to Programming

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

5 Arrays and Pointers

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Chapter 9, More SQL: Assertions, Views, and Programming Techniques

Stacks. Linear data structures

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Logging. Working with the POCO logging framework.

Comp151. Definitions & Declarations

Member Functions of the istream Class

Curriculum Map. Discipline: Computer Science Course: C++

An Incomplete C++ Primer. University of Wyoming MA 5310

Computer Programming I

13 Classes & Objects with Constructors/Destructors

7.1 Our Current Model

Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct

It has a parameter list Account(String n, double b) in the creation of an instance of this class.

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

Outline Basic concepts of Python language

Recursion. Slides. Programming in C++ Computer Science Dept Va Tech Aug., Barnette ND, McQuain WD

Unit Testing & JUnit

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure

Object Oriented Software Design II

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

SIF Validation Tool. Wages Protection System Qatar Central Bank& Ministry of Labour And Social Affairs. End User Guide

Introduction to Java Lecture Notes. Ryan Dougherty

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

This section describes how LabVIEW stores data in memory for controls, indicators, wires, and other objects.

COMMMUNICATING COOPERATING PROCESSES

Iteration CHAPTER 6. Topic Summary

While Loop. 6. Iteration

Cours de C++ Utilisations des conteneurs

CS106A, Stanford Handout #38. Strings and Chars

C Strings and Pointers

A Grammar for the C- Programming Language (Version S16) March 12, 2016

Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved.

Last not not Last Last Next! Next! Line Line Forms Forms Here Here Last In, First Out Last In, First Out not Last Next! Call stack: Worst line ever!

1 Abstract Data Types Information Hiding

D06 PROGRAMMING with JAVA

Pemrograman Dasar. Basic Elements Of Java

Coding conventions and C++-style

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

Java Interview Questions and Answers

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

COMPUTER SCIENCE 1999 (Delhi Board)

J a v a Quiz (Unit 3, Test 0 Practice)

The University of Alabama in Huntsville Electrical and Computer Engineering CPE Test #4 November 20, True or False (2 points each)

The While Loop. Objectives. Textbook. WHILE Loops

Syllabus OBJECT ORIENTED PROGRAMMING C++

TivaWare Utilities Library

Module 816. File Management in C. M. Campbell 1993 Deakin University

CUDA Programming. Week 4. Shared memory and register

5 CLASSES CHAPTER. 5.1 Object-Oriented and Procedural Programming. 5.2 Classes and Objects 5.3 Sample Application: A Clock Class

! " # $ %& %' ( ) ) *%%+, -..*/ *%%+ - 0 ) 1 2 1

Exceptions in MIPS. know the exception mechanism in MIPS be able to write a simple exception handler for a MIPS machine

El Dorado Union High School District Educational Services

Chapter 13 - Inheritance

3 Pillars of Object-oriented Programming. Industrial Programming Systems Programming & Scripting. Extending the Example.

Sources: On the Web: Slides will be available on:

7th Marathon of Parallel Programming WSCAD-SSC/SBAC-PAD-2012

A list of data types appears at the bottom of this document. String datetimestamp = new java.sql.timestamp(system.currenttimemillis()).

Affdex SDK for Windows!

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Transcription:

Fondamenti di C++ - Cay Horstmann 1 Review Exercises R10.1 Line 2: Can't assign int to int* Line 4: Can't assign Employee* to Employee Line 6: Can't apply -> to object Line 7: Can't delete object Line 10: Explicit parameter of seconds_from must be an object, not a pointer Line 11: Can't delete object Line 14: Can't apply dot operator to pointer Line 16: Need parentheses (*t2).get_minutes() R10.3 a) You reach the object to which the pointer points b) It depends. The object may appear to be valid for some time, but it iscorrupted eventually c) The program dies with a segmentation or general protection fault d) It depends. There may appear to be an object at the random memory location,or the program may die. R10.5 The program prints 35000 45000 45000 45000 The first two values are separate objects. Thus, raising the salary of onedoesn't affect the other. The second pair of values are pointers to a shared object. R10.7 The computation p[i] reaches the value that starts at address of p + i *sizeof(int) and is sizeof(int) bytes long. Since sizeof(int)!= sizeof(double),those values are just memory blocks consisting of some of the bytes of floating-pointdata. They are meaningless when considered as integers. R10.9 a) The second storage location in the array b) A pointer to that location c) The same as a) d) The fifth storage location in the array e) A pointer to the sixth storage location in the array f) 3

Fondamenti di C++ - Cay Horstmann 2 R10.11 You cannot return the array as the function result. Therefore, you must passin the array as a parameter: void minmax(double values[], double result[]) R10.13 a) A pointer set to 0 b) A pointer set to point to an array that contains a single 0 byte c) An array that contains a single 0 byte R10.15 Both functions append to an existing memory array instead of returning anew string that contains the concatenation. Generally, returning a new stringis more convenient, but it is impossible if you work with character arrays. The strcat function does not check whether it exceeds the target array'scapacity. The strncat function can be used instead, but it is cumbersometo compute the maximum number of characters to copy, and even more cumbersometo deal with the 0 terminator. The + operator simply allocates a string ofthe correct size. Programming Exercises P10.1 #include <string> #include <iomanip> #include <vector> using namespace std; class Person public: Constructs a person with a given name @param n the name Person(string n); Gets the name of this person. @return the name string get_name() const; Sets the best friend of this person @param p a pointer to the best friend void set_best_friend(person* p); Gets the best friend of this person. @return a pointer to the best friend

Fondamenti di C++ - Cay Horstmann 3 Person* get_best_friend() const; Adjusts the popularity counter of this person. @param d +1 or -1 void adjust_popularity(int d); Gets the popularity counter of this person. @return the popularity counter int get_popularity() const; private: string name; Person* best_friend; int popularity; ; Person::Person(string n) name = n; best_friend = NULL; popularity = 0; void Person::set_best_friend(Person* p) if (best_friend!= NULL) best_friend->adjust_popularity(-1); best_friend = p; if (best_friend!= NULL) best_friend->adjust_popularity(1); Person* Person::get_best_friend() const return best_friend; void Person::adjust_popularity(int d) popularity = popularity + d; int Person::get_popularity() const return popularity; string Person::get_name() const return name; vector<person*> people; bool more = true; while (more)

Fondamenti di C++ - Cay Horstmann 4 cout << "Enter name, q to quit: "; string name; getline(cin, name); if (name == "q") more = false; else people.push_back(new Person(name)); for (int i = 0; i < people.size(); i++) cout << "Who is the best friend of " << people[i]->get_name() << "? "; string name; getline(cin, name); for (int j = 0; j < people.size(); j++) if (people[j]->get_name() == name) people[i]->set_best_friend(people[j]); for (int i = 0; i < people.size(); i++) cout << setw(20) << people[i]->get_name() << "best friend=" << setw(20) << people[i]->get_best_friend()- >get_name() << "popularity=" << setw(10) << people[i]->get_popularity() << "\n"; P10.3 #include <string> #include <vector> class BankAccount public: Constructs a bank account with a zero balance. BankAccount(); Deposits money into this account. @param amount the amount to deposit. void deposit(double amount); Withdraws money from this account. @param amount the amount to withdraw. void withdraw(double amount); Gets the balance of this account. @return the balance double get_balance() const;

Fondamenti di C++ - Cay Horstmann 5 private: double balance; ; class Employee public: Constructs an employee with a given name, salary, and bank account. @param n the name @param s the annual salary @param a a pointer to the bank account Employee(string n, double s, BankAccount* a); Deposits one month's salary into the bank account. void deposit_monthly_salary(); Prints this employee's information to cout. void print() const; private: string name; double salary; BankAccount* account; ; BankAccount::BankAccount() balance = 0; void BankAccount::deposit(double amount) balance = balance + amount; void BankAccount::withdraw(double amount) balance = balance - amount; double BankAccount::get_balance() const return balance; Employee::Employee(string n, double s, BankAccount* a) name = n; salary = s; account = a; void Employee::deposit_monthly_salary()

Fondamenti di C++ - Cay Horstmann 6 const int MONTHS_PER_YEAR = 12; account->deposit(salary / MONTHS_PER_YEAR); void Employee::print() const cout << "Employee[name=" << name << ",salary=" << salary << ",account balance=" << account->get_balance() << "]\n"; vector<employee> staff; bool more = true; string previous_lname = "q"; BankAccount* previous_account = NULL; while (more) string lname; cout << "Enter last name, q to quit: "; getline(cin, lname); if (lname == "q") more = false; else string fname; cout << "Enter first name: "; getline(cin, fname); cout << "Enter salary: "; double salary; cin >> salary; string dummy; getline(cin, dummy); if (lname!= previous_lname) previous_account = new BankAccount(); previous_lname = lname; staff.push_back(employee(lname + ", " + fname, salary, previous_account)); for (int i = 0; i < staff.size(); i++) staff[i].deposit_monthly_salary(); for (int i = 0; i < staff.size(); i++) staff[i].print(); P10.5 Computes the average of the values in an array @param a the array

Fondamenti di C++ - Cay Horstmann 7 @param a_size the number of elements in the array @return the average, or 0 if the array is empty double average(double a[], int a_size) double sum = 0; double* p = a; for (int i = 0; i < a_size; i++) sum = sum + *p; p++; if (a_size == 0) else return sum / a_size; double data[] = 1, 4, 9, 16, 25 ; cout << average(data, 5) << "\n"; P10.7 Reverses the values in an array @param a the array void reverse(double a[], int a_size) double* p = a; double* q = a + a_size - 1; while (p < q) double temp = *p; *p = *q; *q = temp; p++; q--; double data[] = 1, 4, 9, 16, 25 ; reverse(data, 5); for (int i = 0; i < 5; i++) cout << data[i] << "\n"; P10.9

Fondamenti di C++ - Cay Horstmann 8 Computes the length of the prefix of a string that is composed of characters in a given set. @param s the string whose maximum prefix is to be found @param t the string whose characters are to be contained in the prefix @return the length of the prefix of s consisting of characters of t (in any order) int strspn(const char s[], const char t[]) int n = 0; while (*s!= '\0') const char* p = t; while (*p!= *s && *p!= '\0') p++; if (*p == 0) // no match return n; n++; s++; return n; cout << strspn("mississippi", "ims") << "\n"; P10.11 #include <cstring> Concatenates two character arrays into a result array. @param a the first character array @param b the second character array @param result the array to hold the concatenation @param result_maxlength the maximum length of the result (not counting the '\0' terminator) void concat(const char a[], const char b[], char result[], int result_maxlength) int n = strlen(a); strncpy(result, a, result_maxlength); if (n < result_maxlength) strncat(result + n, b, result_maxlength - n); result[result_maxlength] = '\0'; char a[] = "Woozle"; char b[] = "Heffalump"; char c[5];

Fondamenti di C++ - Cay Horstmann 9 char d[10]; char e[20]; concat(a, b, c, 5); concat(a, b, d, 10); concat(a, b, e, 20); cout << c << "\n"; cout << d << "\n"; cout << e << "\n"; P10.13 using namespace std; const int BUFFER_CAPACITY = 1000; const int LINES_CAPACITY = 100; char buffer[buffer_capacity]; char* lines[lines_capacity]; int buffer_size = 0; int lines_size = 0; bool more = true; bool newline = true; while (more) char c = cin.get(); if (cin.fail()) more = false; else if (buffer_size >= BUFFER_CAPACITY) more = false; if (newline) if (lines_size < LINES_CAPACITY) lines[lines_size] = buffer + buffer_size; lines_size++; newline = false; else more = false; if (more) if (c == '\n') buffer[buffer_size] = '\0'; buffer_size++; newline = true; else buffer[buffer_size] = c; buffer_size++;

Fondamenti di C++ - Cay Horstmann 10 buffer[buffer_capacity - 1] = '\0'; for (int i = lines_size - 1; i >= 0; i--) cout << lines[i] << "\n"; P10.15 using namespace std; int buffer_capacity = 1000; int lines_capacity = 100; char* buffer = new char[buffer_capacity]; char** lines = new char*[lines_capacity]; int buffer_size = 0; int lines_size = 0; bool more = true; bool newline = true; while (more) char c = cin.get(); if (cin.fail()) more = false; else if (buffer_size >= buffer_capacity) char* new_buffer = new char[2 * buffer_capacity]; for (int i = 0; i < buffer_capacity; i++) new_buffer[i] = buffer[i]; for (int i = 0; i < lines_size; i++) lines[i] = new_buffer + (lines[i] - buffer); buffer = new_buffer; buffer_capacity = 2 * buffer_capacity; if (newline) if (lines_size >= lines_capacity) char** new_lines = new char*[2 * lines_capacity]; for (int i = 0; i < lines_capacity; i++) new_lines[i] = lines[i]; lines = new_lines; lines_capacity = 2 * lines_capacity; lines[lines_size] = buffer + buffer_size; lines_size++; newline = false; if (c == '\n') buffer[buffer_size] = '\0';

Fondamenti di C++ - Cay Horstmann 11 buffer_size++; newline = true; else buffer[buffer_size] = c; buffer_size++; for (int i = lines_size - 1; i >= 0; i--) cout << lines[i] << "\n";