Practice Problems CS2620 Advanced Programming, Spring 2003

Similar documents
Inheritance and Polymorphism

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

CS 1337 Computer Science II Page 1

Short Notes of CS201

CS 247: Software Engineering Principles. ADT Design

CS201 - Introduction to Programming Glossary By

Review Questions for Final Exam

Review: C++ Basic Concepts. Dr. Yingwu Zhu

! Search: find a given target item in an array, ! Linear Search: Very simple search method: ! Operators such as =, +, <, and others can be

Chapter 2. Procedural Programming

2. It is possible for a structure variable to be a member of another structure variable.

Function Overloading

Lecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47

pointers & references

CS2141 Software Development using C/C++ C++ Basics

CE221 Programming in C++ Part 1 Introduction

COEN244: Class & function templates

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

CS201 Latest Solved MCQs

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

AN OVERVIEW OF C++ 1

G52CPP C++ Programming Lecture 16

Lecture 7. Log into Linux New documents posted to course webpage

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

Instantiation of Template class

C/C++ Programming Lecture 18 Name:

! A class in C++ is similar to a structure. ! A class contains members: - variables AND. - public: accessible outside the class.

Fast Introduction to Object Oriented Programming and C++

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:

Templates and Vectors

CS2255 HOMEWORK #1 Fall 2012

CS3157: Advanced Programming. Outline

Programming in C++: Assignment Week 8

Polymorphism Part 1 1

Come and join us at WebLyceum

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

Lecture 12. Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 1

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

Chapter 15 - C++ As A "Better C"

Operator Overloading

Getting started with C++ (Part 2)

ADTs in C++ In C++, member functions can be defined as part of a struct

(6) The specification of a name with its type in a program. (7) Some memory that holds a value of a given type.

this Pointer, Constant Functions, Static Data Members, and Static Member Functions this Pointer (11.1) Example of this pointer

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

Lecture 10. Command line arguments Character handling library void* String manipulation (copying, searching, etc.)

III. Classes (Chap. 3)

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

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:

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

CS

The Class. Classes and Objects. Example class: Time class declaration with functions defined inline. Using Time class in a driver.

A Deeper Look at Classes

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

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

Copying Data. Contents. Steven J. Zeil. November 13, Destructors 2

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

Topics. bool and string types input/output library functions comments memory allocation templates classes

Overloading Operators in C++

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

Lab 2: ADT Design & Implementation

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

Introduction to Programming EC-105. Lecture 2

More About Classes. Gaddis Ch. 14, CS 2308 :: Fall 2015 Molly O'Neil

l A class in C++ is similar to a structure. l A class contains members: - variables AND - public: accessible outside the class.

Due Date: See Blackboard

Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

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

Reference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that

Motivation for Templates. Class and Function Templates. One Way to Look at Templates...

Class and Function Templates

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

IV. Stacks. A. Introduction 1. Consider the 4 problems on pp (1) Model the discard pile in a card game. (2) Model a railroad switching yard

Distributed Real-Time Control Systems. Lecture 14 Intro to C++ Part III

Review Questions for Final Exam KEY

CS201 Some Important Definitions

Introduction to C++ Friends, Nesting, Static Members, and Templates Topic #7

Introduction to Programming using C++

Exam 3 Chapters 7 & 9

C++ Programming Fundamentals

Constructor - example

Motivation for Templates

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #1 Examination 12:30 noon, Tuesday, February 14, 2012

Unit 1: Preliminaries Part 4: Introduction to the Standard Template Library

Fundamentals of Programming CS-110. Lecture 2

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

Part I: Short Answer (12 questions, 65 points total)

CSCI-1200 Data Structures Fall 2017 Lecture 9 Iterators & STL Lists

CS 2604 Homework 1 C++ Review Summer I 2003

Starting Savitch Chapter 10. A class is a data type whose variables are objects. Some pre-defined classes in C++ include int,

1 Short Answer (5 Points Each)

Object-Oriented Design (OOD) and C++

CS11 Intro C++ Spring 2018 Lecture 3

Makefiles Makefiles should begin with a comment section of the following form and with the following information filled in:

Wentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. C++ Kitchen Sink. Lecture 14.

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A.

Transcription:

Practice Problems CS2620 Advanced Programming, Spring 2003 April 9, 2003 1. Explain the results of each vector definition: string pals[] = "pooh", "tigger", "piglet", "eeyore", "kanga" a) vector<string> svec1(pals, pals+5); Solution: svec1 is a vector of string that has been initialized with the content of the array of string pals. b) vector<int> ivec1(10); Solution: ivec1 is a vector of 10 ints. c) vector<int> ivec2(10, 10); Solution: ivec2 is a vector of 10 ints, each initialized with the value 10 d) vector<string> svec2(svec1); Solution: svec2 is a vector of string that is a copy of the vector svec1 2. A type/subtype inheritance relationship, in general, reflects an Is-A relationship e.g., a book is a kind of librarymaterial. Which of the following pairs reflects an Is-A relationship and which one does not? Explain. (a) Member function is-a kind of function Solution: This reflects an Is-A relationship. A member function is a specialized instance of function. Both have a return type, a name, a parameter list, and a definition. In addition, a member function belongs to a particular class, may or may not be a virtual, const, or static member function, and so on. Inheritance correctly models this relationship. (b) Journal Is-A kind of library Solution: This does not reflects an Is-A relationship. A journal is an item that a library may contain. A journal is not a specialize instance of library. The relationship is an example of a Has-A relationship. 1

3. The following function provides absolutely no checking of the possible failure of an operation or the validity of data. int *allocateandinit( const string& filename) ifstream infile(filename.c_str()); int elementcount; infile >> elementcount; // read the number of ints contained in // the file // allocatearray(elementcount) allocates elementcount integers from the // free store and returns a pointer to the beginning of the allocated storage int *pi = allocatearray(elementcount); int elt; int index = 0; while (cin >> elt) // read data pi[ index++ ] = elt; // sortarray(pi, elementcount) sorts an array of // elementcount ints sortarray(pi, elementcount); return pi; (a) Write the prototype declarations for the functions allocatearray() and sortarray() from the information given above. Solution: Prototype declarations: int *allocate_array(int); void sortarray(int *, int); (b) Identify what might possibly go wrong within the function. Solution: The following might possibly go wrong within the function filename could be an empty string The ifstream constructor may not be able to open the file even if filename is a valid string elementcount receives an incorrect value: too large, zero, or a negative value allocatearray() fails to allocate space for elementcount elements The while loop depends on encountering EOF (or failing to read an int) to terminate the loop, and it does not take into account the size of the array that pi points to. 4. Rewrite the following class definition to make it a class template: class C 2

C(); // default constructor C(int *par, int sz); // construct from an int array of sz elements // the data members minm and maxm are computed // from the array par int& operator[]( int index); //overloaded operator []: return element at //position index bool operator==(const C&) const; // Overloaded operator == : return true // on equality, and false otherwise bool insert(int elt); // insert elt at the back int min() const return minm; // Return the minimum element int max() const return maxm; // return the maximum element int size; // Number of elements in the array int* parray; // Actual array int minm; // minimum value of the array elements int maxm; // maximum value of the array elements void min(double); // compute the minimum void max(double); // compute the maximum Solution: To transform the above class definition into a template, we must identify and factor out each dependent data type. size, for example, is of type int. Might that vary with different user-specified instances of C? Not really. size is an invariant data member that holds a count of the elements addressed by parray. parray, however, may address elements of varying types: int, double, float, string, etc. We want to parameterize the data types of members parray, minm, maxm, as well as return type and signature of the appropriate member functions. template <class T> class C C(); // default constructor C(const T *par, int sz); // construct from an int array of sz elements // the data members minm and maxm are computed // from the array par T& operator[]( int index); //overloaded operator []: return element at //position index bool operator==(const C&) const; // Overloaded operator == : return true // on equality, and false otherwise bool insert(const T& elt); // insert elt at the back T min() const return minm; // Return the minimum element 3

T max() const return maxm; // return the maximum element T size; // Number of elements in the array T* parray; // Actual array T minm; // minimum value of the array elements T maxm; // maximum value of the array elements 5. We can make the Bubble sort implementation (refer to lecture notes) slightly efficient by terminating the outer for loop early, i.e., as soon as we detect that the remaining elements are sorted. Implement the early termination version of bubble sort algorithm. (Note: Although this modification can make the algorithm run faster for nearly sorted data, the worst-case time complexity does not change). Solution: If no swapping is performed in an outer for loop iteration (bubbling phase), the elements are sorted. On the other hand, a single swap during the bubbling phase implies unsorted data. We can explicitly test for this condition and terminate the loop when the condition is true. template<class T> void bubblesort(vector<t>& elts) bool sorted = false; //assume the list is unsorted int numelts = elts.size(); int pass = 0; while ((pass < numelts-1) &&!sorted) // the while loop // replaces the for loop sorted = true; //may be that the remaining elements are sorted for (int j = 0; j < numelts-pass-1; j++) if (elts[j] > elts[j+1]) swap(&elts[j], &elts[j+1]); sorted = false; // a swap implies unsorted data //end_if // end_for pass++; //end_while //end_bubblesort 6. Explain why the stream extraction and insertion operators are typically implemented as nonmember functions for user-defined classes. Solution: The input and output operators are not defined global because the left operand of each operator is a stream instead of a user-defined class object. An operator member function will be called only if the left operand is an object of the class type for which the operator is being overloaded. 7. The conversion constructors can be a potential source of hard-to-find bugs. Explain what might go wrong. 4

Solution: Refer to Lecture Note. 8. Consider the following Clock class. // A simple Clock class interface specification. Keeps time in Hour, Minute, // and Second // File: clock.h // Date: 2000/11/03 #ifndef CLOCK_H #define CLOCK_H //Prevent multiple inclusions class Clock // Member functions // Default constructor with the default value of // Midnight: 0 hour, 0 minute and, 0 second Clock(int hr=0, int mnt=0, int sec=0); // Inspectors (get methods) // Declared const as they do not modify the invoking // object s state; also necessary to be able to process // const objects. These functions are ideal candidate for // inline specification! // If the function body is included, the functions // becomes inline automatically -- i.e., explicit // inline keyword is not necessary int gethour() const; // Return Hour int getminute() const; // Return Minute int getsecond() const; // Return Second // Mutators (set methods) // setclock() will set an existing clock with the supplied // values: hr,mnt,sec where 0<= hr <= 23, 0<= mnt <= 59, // and 0 <= sec <= 59 // If the supplied values are illegal then nothing is changed // // Note reference return to the object itself as we need to make // cascaded calls. Clock& setclock(int hr, int mnt, int sec); // Perform one clock tick() -- advance the clock by one second. // A reference return will enable cascaded call: obj.tick().tick(). 5

Clock& tick(); // Utility functions // Print the current value of clock void display() const; protected: // Data members int Hour; // Hour value: 0 <= Hour <= 23 int Minute;// Minute value: 0 <= Minute <= 59 int Second; // Second Value: 0 <= Second <= 59 // Helpers // Check data for validity bool validtime(int hr, int mnt, int sec) const; // Internal method to set time void settime(int hr, int mint, int sec); #endif An alarm clock is a clock with the following additional functionalities. An alarm can be set at a particular time, and can be deactivated in which case the alarm will not ring at the set time. Define and implement the class alarmclock with software reuse in mind. You may assume that the clock class has already been implemented and available to you. Solution: Try Yourself. 9. Which class definition is likely to need a copy constructor? Explain. (a) A complex number representation containing two floating point numbers. Solution: An explicit copy constructor is not needed since there are no data members that are pointers. (b) A word class containing a string object and vector object of line and column location pairs. Solution: A copy constructor is not required because the compiler will invoke the copy constructors for the data members of type string and vector 10. Determine the output of the following code. #include <iostream> 6

#include <string> using namespace std; class bclass bclass(string data = "bclassdata"):bs(data) virtual void Display() cout << "In bclass::display() "; cout << "bs = " << bs << endl; void Print() cout << "In bclass::print() "; cout << "bs = " << bs << endl; string bs; class dclassone : public bclass dclassone(string data = "dclassonedata"):d1s(data) virtual void Display() cout << " In dclassone::display()"; bclass::display(); cout << " d1s = " << d1s << endl; void Print() cout << " In dclassone::print()"; bclass::print(); cout << " d1s = " << d1s << endl; string d1s; class dclasstwo : public bclass dclasstwo(string ddata = " dclasstwodata ", string bdata= " bclassdatafromd2 ") :bclass(bdata), d2s(ddata) 7

virtual void Display(int i) cout << " In dclasstwo::display()"; bclass::display(); cout << " d2s = " << d2s << " i = " << i << string d2s; endl; void Output( bclass &R) R.Display(); int main() bclass A("Object A"); dclassone B("Object B"); dclasstwo C("Object C", "Object C ( ObjectC_A ) "); bclass *Ptr; Ptr = &B; Ptr->Display(); Output(A); Output(B); A = B; A.Display(); Ptr = &B; Ptr->Print(); C.Display(3); Ptr = &C; Ptr->Display(); return 0; 8