CS 103 Lab V for Vector

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

Working with Batches of Data

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:

CS 103 Lab - Party Like A Char Star

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:

Algorithms for Arrays Vectors Pointers CS 16: Solving Problems with Computers I Lecture #14

COP Programming Assignment #7

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

Variables. Data Types.

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

Lab 1: First Steps in C++ - Eclipse

Homework 5. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

CS 103 Unit 11. Linked Lists. Mark Redekopp

Computer Science II Lecture 1 Introduction and Background

Computer Science II Lecture 2 Strings, Vectors and Recursion

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

Vectors and Pointers CS 16: Solving Problems with Computers I Lecture #13

CS2255 HOMEWORK #1 Fall 2012

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

Computer Programming : C++

CS 103 Lab 6 - Party Like A Char Star

CPSC 427a: Object-Oriented Programming

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works

Programming. C++ Basics

School of Information Technology and Computer Science CSCI192 - Spring Session Revision

Chapter 4. Computation. Bjarne Stroustrup.

Chapter 4 Computation

Bruce Merry. IOI Training Dec 2013

CSCI-1200 Computer Science II Fall 2008 Lecture 15 Associative Containers (Maps), Part 2

Templates and Vectors

CSE 303: Concepts and Tools for Software Development

Ch. 17: Linked Lists. Introduction to Linked Lists

Functions, Pointers, and the Basics of C++ Classes

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

VARIABLES & ASSIGNMENTS

CS 103 Unit 11. Linked Lists. Mark Redekopp

Concurrent Data Structures in C++ CSInParallel Project

C++: Overview and Features

Unit 14. Passing Arrays & C++ Strings

2 nd Week Lecture Notes

Problem Solving with C++

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

21. Exceptions. Advanced Concepts: // exceptions #include <iostream> using namespace std;

Introduction to Programming using C++

Lab 8. Follow along with your TA as they demo GDB. Make sure you understand all of the commands, how and when to use them.

FORM 2 (Please put your name and form # on the scantron!!!!) CS 161 Exam II:

Number Systems. Binary Numbers. Appendix. Decimal notation represents numbers as powers of 10, for example

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

CSCI 104 Exceptions. Mark Redekopp David Kempe

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.

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

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

Introduction to Computer Science Midterm 3 Fall, Points

Due Date: See Blackboard

Test 2: CPS Owen Astrachan. November 17, Name: Honor code acknowledgement (signature)

Lab 7 (50 pts) Due Sunday, May 20)

Section Handout #4: Classes, Pointers, and Dynamic Memory

Study Guide for Test 2

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

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

CS 216 Exam 1 Fall SOLUTION

pointers + memory double x; string a; int x; main overhead int y; main overhead

CSCI-1200 Data Structures Spring 2015 Lecture 2 STL Strings & Vectors

REVIEW. The C++ Programming Language. CS 151 Review #2

Absolute C++ Walter Savitch

COMP322 - Introduction to C++ Lecture 01 - Introduction

Chapter 5. The Standard Template Library.

Project #2: FishNet Distance Vector Routing

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

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

CS93SI Handout 04 Spring 2006 Apr Review Answers

CS 455 Final Exam Fall 2012 [Bono] Dec. 17, 2012

Your first C++ program

Computer Science E-119 Fall Problem Set 3. Due before lecture on Wednesday, October 31

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

CSCE 110 PROGRAMMING FUNDAMENTALS

CS 211 Winter 2004 Sample Final Exam (Solutions)

CPSC 427: Object-Oriented Programming

CSCI 1370 APRIL 26, 2017

Programming Exercise 14: Inheritance and Polymorphism

CSCI 262 Data Structures. Recursive Function Analysis. Analyzing Power. Analyzing Power. Analyzing Power 3/31/2018

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

Sample Final Exam. 1) (24 points) Show what is printed by the following segments of code (assume all appropriate header files, etc.

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

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

CSCE Practice Midterm. Data Types

CIS 121 Data Structures and Algorithms with Java Spring 2018

EE 355 Lab 4 - Party Like A Char Star

6. Pointers, Structs, and Arrays. March 14 & 15, 2011

STL Containers, Part I

Slide Set 1. for ENEL 339 Fall 2014 Lecture Section 02. Steve Norman, PhD, PEng

Sixth lecture; classes, objects, reference operator.

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

CS103L FALL 2017 UNIT 1: TYPES, VARIABLES,EXPRESSIONS,C++ BASICS

PART I. Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++.

EAS230: Programming for Engineers Lab 1 Fall 2004

A First Program - Greeting.cpp

Patterns: Working with Arrays

vector<int> second (4,100); // four ints with value 100 vector<int> third (second.begin(),second.end()); // iterating through second

Exam 1 Practice CSE 232 Summer 2018 (1) DO NOT OPEN YOUR EXAM BOOKLET UNTIL YOU HAVE BEEN TOLD TO BEGIN.

Transcription:

1 Introduction As you know, each int in C++ can store up to 2 31-1, which is about 2 billion, and each long can store a number up to 2 63-1, which is about 9 quintillion. For mathematical and cryptographical applications, it is necessary to hold much larger numbers in memory. E.g., when you make a credit card transaction online, it is common to use numbers up to 2 2048 in size (about 617 decimal digits). You will write a class that can support such operations. In grade school, you learned how to add two numbers by long-hand arithmetic. You were forced to memorize the 10-by-10 addition table that tells you the sum of any two numbers between 0 and 9. But then, you learned an algorithm to compute any sum of an arbitrary pair of numbers! I.e., to be able to add 3-digit numbers, you didn t have to memorize a 1000-by-1000 table. Instead you used a sequence of operations that broke everything down into simple steps. For example, to add A = 243 and B = 85, you would write the numbers one on top of each other, and add up the columns from right to left, performing carries as needed: 10 2 place 10 1 place 10 0 place <- carry 2 4 3 <- A : 243 8 5 <- B : 85 <- sum First you added the 10 0 place, writing 8 (3+5) in the sum s 10 0 place. Then you added the 10 1 place, giving 12 (4+8); but since this is too big, you would write a 2 in the sum s 10 1 place, and carry the 1. Finally, in the 10 2 place, you added the 1 (carry), 2 (A), and 0 (B), giving 3, with the sum being 328: 10 2 place 10 1 place 10 0 place 1 <- carry 2 4 3 <- A : 243 8 5 <- B : 85 3 2 8 <- sum This algorithm works for any number of digits. You will implement it in C++ for this lab. Last Revised: 10/20/2017 1

2 What you will learn After completing this lab you should be able to: Utilize the string class and the vector template class Implement a simple numerical algorithm Understand the difference between public and private access in a class Understand the default copy constructor 3 Background Information and Notes The specific operations that we want you to implement are defined for you in the header bigint.h: class BigInt { public: BigInt(string s); // convert string to BigInt string to_string(); // get string representation void add(bigint b); // add another BigInt to this one private: // whatever you need }; For example, this sample program (test1.cpp) prints out 55 and 68: BigInt a( 13 ); BigInt b( 42 ); b.add(a); // increase b by a cout << b.to_string() << endl; // prints 55 b.add(a); // increase b by a cout << b.to_string() << endl; // prints 68 We want your library to support numbers that can be arbitrarily large. Therefore, you will represent each number as a long list of digits. E.g. BigInt a( 13 ) should be thought of as create a new BigInt that contains a sequence of two digits, 1 and 3. The number of digits in a BigInt can grow. (We ll only deal with positive numbers in this lab.) So it is extremely convenient to use the vector<t> class, which represents a list of values of any type T, which can also grow over time. The vector class has an extensive API that we encourage you to look up online. For this assignment you can get by with 4 operations: vector<t>() void vector.push_back(t t) T vector[int i] size_type vector.size() // default constructor: new empty vector // add element to end of the list // get the element at position i // current size (size_type is an unsigned int) 2 Last Revised: 10/20/2017

For future assignments, it can be useful to use other vector operations, so please skim the documentation online. You need to #include <vector> to use vectors. Here is a sample program using these operations: vector<string> words; // declare, construct words.push_back("hello"); // push_back: add to end words.push_back("world"); cout << words.size() << endl; // size: get size cout << words[0] << " " << words[1] << endl; // [i]: access As you can see, it builds up the vector from the beginning to the end. It prints out the number 2, then Hello World. What makes the most sense for our BigInt library is to use a vector<int> as the data member: this will permit the numerical operations involved to be as simple as possible. It is recommended that you use position 0 to represent the units digit, and position 1 to represent the tens digit, et cetera. So the label 10 K place on page 1 of this lab handout means index K of your vector. This will simplify the addition algorithm although it will complicate the constructor. If you follow this approach, the constructor BigInt(string s) will be responsible for: converting the digits (characters of s) to ints (elements of the vector) reversing the order (since a string representation of a number puts the units digit at the end, but we want it at the beginning) To convert a character to an int, a simple approach is to use the fact that the ASCII values of the ten digit characters, obtained by casting them to int, are as follows: char c 0 1 2 3 4 5 6 7 8 9 (int)c 48 49 50 51 52 53 54 55 56 57 So to convert a char that is a digit (e.g., 3 ) to an int of the same value (e.g., 3), first cast to int, and then subtract 48. (Or, just subtract 0.) Look up ASCII table online, or on page 494 of the textbook, to see more information about how different characters are represented. It is recommended that you get the constructor and to_string() function working first. Then this program (test0.cpp) should print out 103 : BigInt myint( 103 ); cout << myint.to_string() << endl; Last Revised: 10/20/2017 3

4 Procedure 4.1 Provided Code Download the files for this lab: the bigint.h header and some test programs. mkdir ~/lab-bigint cd ~/lab-bigint wget http://bytes.usc.edu/files/cs103/lab-bigint.tar tar xvf lab-bigint.tar 4.2 [3 pts.] constructor, to_string() Implement the constructor and print function for the BigInt class. We have provided bigint.h that is mostly complete: o add the necessary private data member to the definition. Create bigint.cpp and fill in the actual definitions for the constructor and the to_string() function. Run make test0 and./test0, which should print out 103. 4.3 [5 pts.] add() Implement the add() function. Before starting to code, write up pseudocode for how the addition should work. How many times should it loop? How will you represent the carried number? Does it use push_back(), which appends to the end of a vector? Note that inside of void BigInt::add(BigInt b), you are allowed to access the private variables of b. This is because your code is part of the definition of BigInt. Privacy prevents other classes from seeing inside, but not other objects of the same class. In order to get your numbers to line up, you might like to add some extra zeroes to one vector or the other. Note that inside of void BigInt::add(BigInt b), you are allowed to change the data members of b. This is safe because C++ uses pass-by-value, even with objects: you are only changing a copy of b. Run./test1, which should print 55 and 68. Create and run a test of your own design that checks whether your code is correct in other cases (carrying, different lengths, etc). Look at the other sample programs provided. 4 Last Revised: 10/20/2017

4.4 [2 pts.] Discussion Write a program badaccess.cpp that, when compiled (you can use make badaccess), generates this error message: error: '???' is a private member of 'BigInt' (The??? will depend on your implementation.) Then, change the data member visibility to public and make this error message go away, to confirm that was the source of the problems. Finally, change the visibility back to private (which is best practice). Show your TA that you are able to generate this error message. Demonstrate all of your work to your TA/CP. 4.5 [1 pts.] Extra Credit: All Your Base There is nothing special about the number 10, except that the median human has that many fingers. Add a new constructor BigInt(string s, int base) that creates a BigInt operating in the given base. Add a new data member if needed. Your newly extended class should work with any base between 2 and 36, using the digits 0, 1,, 9, A, B, C,, Z. For example: BigInt first( DADCAFE, 16); // hexadecimal BigInt second( AAABEEF, 16); first.add(second); cout << first.to_string(); // prints 185889ED To help the user, throw a runtime error when a user tries to add two different-base numbers. #include <stdexcept> using namespace std; void BigInt::add( ) { if( /* bases don't match */ ) throw runtime_error("error - different bases"); else { /* bases do match so perform the operation */ } } Last Revised: 10/20/2017 5