Abstract Data Type Fraction Example

Slides:



Advertisements
Similar presentations
Engineering Problem Solving With C++ An Object Based Approach Additional Topics Chapter 10 Programming with Classes.
Advertisements

Based on Java Software Development, 5th Ed. By Lewis &Loftus
Contents o Introduction o Characteristics of Constructor. o Types of constructor. - Default Constructor - Parameterized Constructor - Copy Constructor.
Programmer-defined classes Part 2. Topics Returning objects from methods The this keyword Overloading methods Class methods Packaging classes Javadoc.
C++ Classes & Data Abstraction
Operator Overloading Programming in C++ Fall 2008 Dr. David A. Gaitros
Abstract Data Types Development and Implementation JPC and JWD © 2002 McGraw-Hill, Inc.
J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. Abstract Data Types Development and Implementation.
1 CS2200 Software Development Lecture 27: More Testing A. O’Riordan, 2008 K. Brown,
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
Abstract Data Type. COMP104 Slide 2 Summary l A class can be used not only to combine data but also to combine data and functions into a single (compound)
CS 117 Spring 2002 Classes Hanly: Chapter 6 Freidman-Koffman: Chapter 10, intro in Chapter 3.7.
Wednesday, 10/9/02, Slide #1 CS 106 Intro to CS 1 Wednesday, 10/9/02  QUESTIONS ??  Today:  Discuss HW #02  Discuss test question types  Review 
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
CMSC 2021 Stream I/O Operators and Friend Functions.
Abstract Data Type (ADT). 2 An Abstract Data Type (ADT) is a data structure with a set of operations –Operations specify how the ADT behaves, but does.
Programmer-defined classes Part 3. A class for representing Fractions public class Fraction { private int numerator; private int denominator; public Fraction(int.
Introduction to C++ Programming
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Fractions Chapter Simplifying Fractions Restrictions Remember that you cannot divide by zero. You must restrict the variable by excluding any.
Chapter 6—Objects and Classes The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Objects and Classes C H A P T E R 6 To beautify.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 14. User Defined Classes.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
Computer Programming and Basic Software Engineering 9 Building Graphical User Interface Working with Unmanaged Code.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part R1. ADTs as Classes.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
Case Study - Fractions Timothy Budd Oregon State University.
Operatorsand Operators Overloading. Introduction C++ allows operators to be overloaded specifically for a user-defined class. Operator overloading offers.
Copyright  Hannu Laine C++-programming Part 1 Hannu Laine.
1 INTRODUCTION TO PROBLEM SOLVING AND PROGRAMMING.
1 Overloading Overloading allows a function or operator to have a different meaning depending on the type of objects it is used on. Examples: operator+
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
COMPUTER PROGRAMMING. variable What is variable? a portion of memory to store a determined value. Each variable needs an identifier that distinguishes.
CPSC 252 Operator Overloading and Convert Constructors Page 1 Operator overloading We would like to assign an element to a vector or retrieve an element.
Lecture #6 OPERATORS AND ITS TYPES By Shahid Naseem (Lecturer)
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private: //...
1 Programming for Engineers in Python Autumn Lecture 6: More Object Oriented Programming.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 9, 2005 Lecture Number: 6.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
CIS 270—Application Development II Chapter 8—Classes and Objects: A Deeper Look.
Classes & Objects Lecture-6. Classes and Objects A class is a 'blueprint' for all Objects of a certain type (defined by ADT) class defines the attributes.
By Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 13 More on Classes Chapter 8 Week 13 More on Classes Chapter 8.
CS Class 19 Today  Practice with classes Announcements  Turn in algorithm for Project 5 in class today  Project 5 due 11/11 by midnight – .
1 2/21/05CS250 Introduction to Computer Science II Destructors, Get and Set, and Default Memberwise Assignment.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
DCS 2133 Object Oriented Programming Defining Your Own Classes Part 2.
Programming Abstract Data Types. COMP104 Lecture 30 / Slide 2 Review: class l Name one reason why we need the class construct. l Why do we need "inspector.
72 4/11/98 CSE 143 Abstract Data Types [Sections , ]
Dale Roberts Object Oriented Programming using Java - Getters and Setters Dale Roberts, Lecturer Computer Science, IUPUI
1 Data Structures CSCI 132, Spring 2014 Lecture 2 Classes and Abstract Data Types Read Ch Read Style Guide (see course webpage)
Class Operations Creating New Types. Review Last time, we began building, a class to allow us to model temperatures: Last time, we began building Temperature,
1 Chapter 12 Classes and Abstraction. 2 Chapter 12 Topics Meaning of an Abstract Data Type Declaring and Using a class Data Type Using Separate Specification.
Chapter 12 Classes and Abstraction
COMPSCI 107 Computer Science Fundamentals
Topic 7 Introduction to Classes and Objects
Chapter 3: Using Methods, Classes, and Objects
CMPE Data Structures and Algorithms in C++ February 22 Class Meeting
Fraction Abstract Data Type
Department of Computer and Information Science, School of Science, IUPUI CSCI 265 Classes Dale Roberts, Lecturer Computer Science, IUPUI
Classes.
CS150 Introduction to Computer Science 1
CS150 Introduction to Computer Science 1
COMS 261 Computer Science I
Development and Implementation
CS 144 Advanced C++ Programming February 21 Class Meeting
Class rational part2.
Presentation transcript:

Abstract Data Type Fraction Example Department of Computer and Information Science, School of Science, IUPUI Abstract Data Type Fraction Example Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu

Abstract Data Types are Abstraction

Abstract Data Type Example An Abstract Data Type is a data type that is defined by the programmer, not the language. Like any data type, it is a set of values with operations that act on those values. Working with ADTs involves three different components: The public interface, or specification, defines the ADT and how it is used. The implementation, implements the ADT in code. The client uses the ADT to perform a task.

Defining an ADT Within C++, you define an ADTs public interface with a header file. #include “fraction.h” main() { Fraction x, y; … } User-defined ADTs are typically capitalized to distinguish them from intrinsic data types.

ADT Operations Several classes of operations are required in order to effectively used ADT. Constructors – used to create instances of the data type. Destructors – used to destroy an instance of the data type Accessors – used to access attributes of the data type. (Such as “get” functions) Modifiers – used to modify attributes of the data type. (Such as “set” functions) Object-oriented languages provide some of this functionality within the language. In C you must do it yourself.

Fraction ADT Specification The specification for the Fraction ADT requires a discussion of what operations are required. Constructors: Fraction() creates a new variable of type Fraction with the default value of 0/1. Fraction(int n, int d) creates a new variable of type Fraction with the default value of n/d. Note that you need to handle all combinations of positive and negative for n and d in order to determine the sign of the fraction.

Fraction ADT (Cont) Destructors: ~Fraction() – frees Fraction variable. Copy: Fraction g = f; – creates a new Fraction g, whose values are copied from f. C++ provides a default copy constructor, or you may write your own: Fraction(const Fraction &) Accessors: i = f.getNumerator(); i = f.getDenominator(); c = f.getSign(); You don’t need to provide you own copy constructor if you don’t use new.

Fraction ADT (cont) Modifiers: f.reduceFract() – reduces a fraction to lowest terms. Notice that this is a modifier, and cannot be used in an expression. setNumerator(int); setDenominator(int); setSign(char);

Fraction ADT Operations These Operations are designed to be used in an expression. They never modify their arguments. They always return type Fraction. f = Fraction::negateFract(f) // returns -f s = Fraction::addFract(f1,f2) // returns f1 + f2 d = Fraction::subFract(f1,f2) // returns f1 – f2 p = Fraction::mulFract(f1,f2) // returns f1 * f2 q = Fraction::divFract(f1,f2) // returns f1 / f2 i = Fraction::compareFract(f1,f2) // f1 < f2 returns -1, // f1 = f2 returns 0, // f1 > f2 returns 1

Fraction ADT I/O Input/Output: Fraction Fraction::getFract(istream, f) – return 1 if OK, 0 if invalid, EOF if end of file. int Fraction::putFract(ostream, f) – writes out fractions with correct sign, does not print denominator if 1

Design While we’ve defined an ADT interface, we can’t just start coding quite yet. There are more design decisions to be made before writing code for the implementation. A common error among programmers is to not place enough emphasis on the design step. This is the difference between a “programmer” and an “analyst”.

Fraction ADT Design: Data Data-centric analysis begins with the idea that all the operations will be acting on Fractions that have some internal representation. The representation shall be shared among all the operations. Each operation is responsible for maintaining your design rules regarding the representation of Fraction information. typedef enum{ POS, NEG } SignType; class Fraction { private: // data members int numerator; /* numerator and denominator are declared as */ int denominator; /* int to simplify the algorithms, but they */ SignType sign; /* will always be stored >= 0 */ public: // member functions would follow // utility functions would follow }; All operations must preserve these rules.

Fraction ADT Variables Now that we’ve decided how to represent the value of a fraction, how are we going to declare variables whose values are fractions? Fraction f1, f2;

Fraction ADT Algorithms You are responsible for designing algorithms that implement all the operations. What process must you follow to implement the operations? a c ad + bc  +  = b d bd Sum: then, reduce a c ac  *  =  b d bd Product: then, reduce Subtraction involves adding the opposite, and Division involves multiplying by the reciprocal.

Fraction ADT Algorithms Reducing a fraction involves finding the Greatest Common Divisor, and then dividing all the terms by that amount. Euclid’s Algorithm: if x < y, then swap x and y While y is not zero remainder = x mod y x = y y = remainder When you’re done, x is the GCD.

Fraction ADT Design Issues There are three special situations that require special handling. Negative fraction have sign = NEG. However, arithmetic expects the sign to be in the numerator. We’ll need to move back and forth between “arithmetic” representation of the sign and “standard”. Fractions may not have zero in the denominator. Dividing by zero is not allowed, even though 0/1 is valid. Different values of zero will not reduce using reduceFract(). Special coding is required to reduce 0/5 to 0/1.

ADT Specification In C++, the ADT Specification resides in a header file, names like fraction.h. /******** Constructors, Destructors, and Clone **********/ Fraction Fraction(); /* returns 0/1 */ Fraction Fraction( int n, int d ); /* returns n/d */ // void ~Fraction( Fraction f ); Implementation not needed // Fraction(const Fraction &); Implementation not needed

Accessors /*********** Accessors **************/ int getNumerator(); int getDenominator(); char getSign();

Modifiers /********** Modifiers ***********/ void setNumerator(int); void setDenominator(int); void setSign(char); void reduceFract();

Operations static Fraction negateFract( const Fraction &f1); /******** Fraction Operations **********/ static Fraction negateFract( const Fraction &f1); static Fraction addFract( const Fraction &f1, const Fraction &f2 ); static Fraction subFract( static Fraction mulFract( static Fraction divFract( static int compareFract( /* returns -1 if f1 < f2 0 if f1 == f2 +1 if f1 > f2 */

Input/Output /******************* I/O ********************/ static int getFract( istream &infile, Fraction &f); /* returns 1 if a valid fraction is read 0 if an invalid fraction is read EOF if end of file is detected */ static void putFract( ostream &outfile, const Fraction &f );

Allowing for multiple #includes #ifndef FRACTION_H #define FRACTION_H #include <iostream> … #endif

Sample Client - Declarations #include <iostream> #include "fraction.h" #include "boolean.h" using std::cout; using std::endl; int main() { Fraction f, g, half(1,2), sum, diff, prod, quotient, neg, answer; Boolean done = FALSE; int readResult, cmpResult; ... code would follow }

Sample Client – Creating Fractions cout << "Enter your first fraction > "; readResult = Fraction::getFract( cin, f ); if (readResult == 0 ) { cout << "Error entering fraction" << endl; } else if ( f.getNumerator() == 9999 ) done = TRUE; else cout << "Enter another fraction > "; readResult = Fraction::getFract(cin, g); if ( readResult == 0 ) cout << "Error enterering fraction" << endl; // Perform Calculations

Sample Client – Manipulating Fractions // Perform Calculations neg = Fraction::negateFract(f); sum = Fraction::addFract(f,g); diff = Fraction::subFract(f,g); prod = Fraction::mulFract(f,g); quotient = Fraction::divFract(f,g); cmpResult = Fraction::compareFract( f, g ); /* (f + g) - ( f * -(1/2) ) */ answer = Fraction::subFract( Fraction::addFract( f,g ), Fraction::mulFract( f,Fraction::negateFract(half)));

Sample Client – Displaying Output /* Display output */ cout << endl; cout << "F1 = "; Fraction::putFract(cout, f); cout << endl; cout << "F2 = "; Fraction::putFract(cout, g); cout << endl; cout << "Neg = "; Fraction::putFract(cout,neg); cout << endl; cout << "Sum = "; Fraction::putFract(cout,sum); cout << " Diff = "; Fraction::putFract(cout,diff); cout << " Prod = "; Fraction::putFract(cout,prod); cout << " Quot = "; Fraction::putFract(cout,quotient); cout << endl; if ( cmpResult == 0 ) cout << "equal" << endl; else if (cmpResult < 0 ) cout << "less" << endl; else cout << "Greater" << endl; cout << "Try one nested: " << endl; out << "(f + g) - ( f * -(1/2) ) = "; Fraction::putFract(cout,answer); cout << endl; cout << "==========================================" << endl;

Sample Client – Clean Up Unlike C, there is no requirement for cleanup when dealing with the Fractions. When Fractions go out of scope, they are automatically destroyed. There is no need to create and call a freeFract() function. Creating a Fraction does not require explicit use of a pointer or malloc(). You create a Fraction on the stack simply by declaring a Fraction variable. Using “new” to allocate a fraction on the heap is not required. int function(int x, y) { int z; z = x+y; return z; } // return is pass-by-value (copy) Fraction function(Fraction x, y) { Fraction z; z = fraction::addfract(x,y); return z; } // return is pass-by-value (copy)

Sample Execution To enter a fraction enter two integers separated by one space. To indicate end of data enter 9999 for the numerator of the first fraction. Use any denominator. Enter your first fraction > 5 6 Enter another fraction > 3 4 F1 = 5/6 F2 = 3/4 Neg = -5/6 Sum = 19/12 Diff = 1/12 Prod = 5/8 Quot = 10/9 Greater Try one nested: (f + g) - ( f * -(1/2) ) = 2

Acknowledgements The specification for this Fraction ADT comes from Fecteau & Kirchherr. The implementation is my own.