Top Banner
Contents 1 Introduction 5 1.1 Binary Operations .......................................... 6 1.2 From Algorithm to Software ..................................... 9 2 Variables and Expressions 11 2.1 Example Programs for the Beginner ................................ 12 2.2 Variables ............................................... 15 2.3 Expressions .............................................. 16 2.4 Boolean Algebra ........................................... 19 3 Conditionals 21 3.1 If, If-Else, If-Elseif-Else ........................................ 22 3.2 Switch ................................................. 27 4 Loops and Control Flow 29 4.1 For-Loops ............................................... 30 4.2 While-Loops .............................................. 31 4.3 For-Loop Applications ........................................ 32 5 Nesting 41 5.1 Conditional Nesting ......................................... 42 5.2 Applications .............................................. 44 6 Algorithm Design and Analysis 49 6.1 Pseudocode Design .......................................... 50 1
243
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • Contents

    1 Introduction 51.1 Binary Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61.2 From Algorithm to Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

    2 Variables and Expressions 112.1 Example Programs for the Beginner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122.2 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152.3 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162.4 Boolean Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

    3 Conditionals 213.1 If, If-Else, If-Elseif-Else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223.2 Switch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

    4 Loops and Control Flow 294.1 For-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304.2 While-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314.3 For-Loop Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

    5 Nesting 415.1 Conditional Nesting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425.2 Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

    6 Algorithm Design and Analysis 496.1 Pseudocode Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

    1

  • CONTENTS CONTENTS

    6.2 Flowchart Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

    7 Functions 557.1 Function Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567.2 Function Prototypes, Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597.3 Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

    8 Files 718.1 Passing by Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 728.2 Input from a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 748.3 Output to a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 768.4 Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

    9 Libraries 85

    10 Arrays and Matrices 95

    11 Structs 109

    12 Recursion 113

    A Problem Sets 121A.1 Problem Set 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122A.2 Problem Set 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125A.3 Problem Set 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129A.4 Problem Set 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133

    B Self-Tests 141B.1 Chapter 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143B.2 Chapter 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144B.3 Chapter 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149B.4 Chapter 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152B.5 Chapter 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159B.6 Chapter 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162B.7 Chapter 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164B.8 Chapter 11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167B.9 Chapter 12 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168B.10 Pre-Test 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170B.11 Test 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175B.12 Pre-Final . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185B.13 Final . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187

    C Notation 205

    2

  • CONTENTS CONTENTS

    D Pseudocode 207

    E Algorithms 209E.1 Computer Science . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210E.2 Mathematics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213E.3 Physics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217E.4 Chemistry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218E.5 Biology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219E.6 Philosophy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220E.7 Psychology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222E.8 Linguistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224

    F Flowcharts 227F.1 Ball Throw . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228F.2 Boolean Switch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229F.3 Cross Product . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230F.4 De Morgans Truth Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231F.5 Double Summation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232F.6 For Creating Flowcharts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233F.7 Ideal Gas Equation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234F.8 Ionic Reaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235F.9 Manhattan Distance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236F.10 Transposing a Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237F.11 Dealing a Poker Hand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238F.12 For Writing Pseudocode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239F.13 Reversing the Boolean Switch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240F.14 Reversing a String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241F.15 Summation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242F.16 RNA Transcription . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243

    3

  • CONTENTS CONTENTS

    4

  • Chapter 1

    Introduction

    Contents1.1 Binary Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

    1.2 From Algorithm to Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

    5

  • 1.1. BINARY OPERATIONS CHAPTER 1. INTRODUCTION

    1.1 Binary Operations

    The formula for binary conversion is

    ni=0

    Bi2i (1.1)

    Where i is the ith digit of the binary number, starting from the right-most side. Alternatively, we couldrender the n-digit binary number as a vector and take its dot product against a length-n vector of powersof 2.

    To do binary conversion by hand:

    For each bit, write down the powers of 2 in increasing order starting with 20 = 1 at the right-most bit.

    For every bit which is set to 1, add the corresponding power of 2 to a running sum.

    Exercise. Convert 101011012 to decimal.

    Solution:

    128 64 32 16 8 4 2 11 0 1 0 1 1 0 1

    128 + 0 + 32 + 0 + 8 + 4 + 0 + 1 = 173

    Exercise. Convert 010100102 to decimal.

    Solution:

    128 64 32 16 8 4 2 10 1 0 1 0 0 1 0

    0 + 64 + 0 + 16 + 0 + 0 + 2 + 0 = 82

    6

  • CHAPTER 1. INTRODUCTION 1.1. BINARY OPERATIONS

    Notice that 101011012 and 010100102 are compliments of each other; that is, each bit of one is the oppositeof the other. Moreover, notice that the sum of their decimal equivalents, 173 + 82 = 255. Why?

    The rules for binary addition are simple:

    0 + 0 = 0.

    1 + 0 = 1.

    1 + 1 = 0, carry 1.

    To add numbers in binary, add them as you would in a decimal system. Instead of carrying when your sumexceeds 9 (the highest single digit in decimal), carry when it exceeds 1 (the highest single digit in binary).

    Exercise: Add 101010102 + 010010012.

    Solution:

    10101010 -> 10101010 -> 10101010 -> 10101010 ->01001001 01001001 01001001 01001001________ ________ ________ ________

    1 11 011

    1 1 110101010 -> 10101010 -> 10101010 -> 10101010 ->01001001 01001001 01001001 01001001________ ________ ________ ________

    0011 10011 110011 1110011

    1010101001001001________11110011

    111100112 is 24310. Since 101010102 is 17010, 010010012 is 7310, and since 170 + 73 = 243, this is correct.

    7

  • 1.1. BINARY OPERATIONS CHAPTER 1. INTRODUCTION

    Exercise: Add 010101012 + 110110112.

    Solution:

    1 11 11101010101 -> 01010101 -> 01010101 -> 01010101 ->11011011 11011011 11011011 11011011________ ________ ________ ________

    0 00 000

    1111 11111 11111 1 1111101010101 -> 01010101 -> 01010101 -> 01010101 ->11011011 11011011 11011011 11011011________ ________ ________ ________

    0000 10000 110000 0110000

    11 11111 1 11111101010101 -> 0101010111011011 11011011________ ________00110000 100110000

    Since 010101012 = 8510, 110110112 = 21910, 1001100002 = 30410 and 85 + 219 = 304, this answer is correct.

    8

  • CHAPTER 1. INTRODUCTION 1.2. FROM ALGORITHM TO SOFTWARE

    1.2 From Algorithm to Software

    Here is the process by which a program is made.

    First an algorithm is developed. An algorithm is a set of instructions for performing a task. The study ofalgorithmics concerns the design of efficient data structures and algorithms for accomplishing various tasks(searching, sorting, etc.). The universal language of algorithmics is pseudocode; it is a language which allcomputer scientists can read and write.

    Given a task, a computer scientist develops an algorithm, or set of instructions, for solving it, and expressesit in pseudocode. Often this involves solving sample cases of the problem, then self-examining how theproblem was solved. With knowledge of a programming language, the programmer translates the algorithmpseudocode into source code for that language. This source code is referred to as an implementation ofthe algorithm.

    If the language in questionis an interpreted language,a program called an inter-preter runs the instructionsin the source code as theyare read in. If the languageis an compiled language, aprogram called a compilertranslates the source codeinto object code. Objectcode is illegible to humans,but contains instructions exe-cutable by the machine. Ob-jects are linked by a linkerinto an executable whichcontains machine codethat is, RISC-compatible in-structions which may thenbe executed by the machine.This final product is typicallywhat we call the program.

    Definitions

    algorithm set of instructions for achieving a task

    algorithmics study of developing efficient data structures & al-gorithms

    compiler program which translates source code into machinecode

    executable final product; a standalone executable program

    implementation language-dependent rendering of an algorithm

    interpreter program which dynamically executes source code

    linker program which links object files with libraries tocreate executable

    machine code code executable by a machine

    object code pieces of compiled (machine-language-translated)source code

    pseudocode universal language of algorithmics

    source code instructional code for an algorithm written in a pro-gramming language

    Figure 1.1: The process of program creation from an algorithm

    9

  • 1.2. FROM ALGORITHM TO SOFTWARE CHAPTER 1. INTRODUCTION

    10

  • Chapter 2

    Variables and Expressions

    Contents2.1 Example Programs for the Beginner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

    2.2 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

    2.3 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

    2.4 Boolean Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

    11

  • CHAPTER 2. VARIABLES AND EXPRESSIONS

    2.1 Example Programs for the Beginner

    Hello, world!

    Code 2.1-1: Hello World

    1 #include 2 using namespace std;3

    4 int main() {5 cout

  • CHAPTER 2. VARIABLES AND EXPRESSIONS

    following:

    Code 2.1-2: Hello World

    1 #include 2

    3 int main() {4 std::cout radius;8 cout

  • CHAPTER 2. VARIABLES AND EXPRESSIONS

    the input stream operator for inputting data from standard input into variables (or other streams).

    Lines 8-12 output the area along with a message. Of particular interest is Line 9, cout : think of the data (for example, 3.14*radius*radius) goinginto the monitor (cout), hence radius;8 cout

  • CHAPTER 2. VARIABLES AND EXPRESSIONS

    2.2 Variables

    Introduction to Variables

    Data Types and CapacitiesAbbreviation Long Forms Bytes Rangebool 1 bit 2*short short int 2 bytes 65,536*int long int 4 bytes 4,294,967,295*long long long long int 8 bytes 18,446,744,073,709,551,615float 4 bytes 3.4E-38double 8 bytes 1.7E308long double >=8 bytes 1.7E308

    Figure 2.1: The * indicates an integer type which may be signed or unsigned (that is, lack a minus sign)with the unsigned keyword preceding the type upon declaration.

    The following code illustrates the use of the most common data types, variable declaration the unsignedkeyword, and def:variable]variable assignment. Lines 5-7 are integer variable declarations. Line 5 declaresa short named seconds. Line 6 declares an unsigned int named height, which means its value cannot beassigned to a negative number.

    Line 8 declares a floating-point number, that is a number with a decimal, called pi, and sets it equal tothe value to the number pi truncated past the 6th decimal place. Likewise on Line 9, a double e has beeninitialized to an approximation of Eulers number. Assignment always happens across an = sign. Theassignee is always placed on the left-hand-side, and the value or expression to be assigned always on theright-hand-side.

    Line 10 declares a charthat is, a character literalcalled day and sets its value equal to the characterliteral M. A character literal is any of the numbers, letters, and special characters found on the keyboard;however in the case of numbers, they are treated as if they were characters (e.g. a serial code 9 as opposedto the number 9). Character literals are represented as binary or decimal numbers according to the ASCIIcode: American Standard Code for Information Interchange. See an ASCII table on-line for conversion.

    Lines 11 and 12 assign the previously-declared variables seconds and height to the values -36 and 5 respec-tively. Since they were previously declared, their data types do not need to be specified upon assignment.

    15

  • CHAPTER 2. VARIABLES AND EXPRESSIONS

    Code 2.2-5: Aesthetic Variable Declaration

    1 #include 2 using namespace std;3

    4 int main() {5

    6 short seconds;7 unsigned int height;8 unsigned long num_particles;9

    10 float pi = 3.141592;11 double e = 2.718281828;12 char day = M;13

    14 seconds = -36;15 height = 5;16

    17 return 0;18

    19 }

    2.3 Expressions

    Operators and Expressions

    Arithmetic OperatorsOperator Operation Example+ Addition sum = augend + addend;* Multiplication product = multiplicand * multiplier;/ Division quotient = dividend / divisor;- Subtraction difference = minuend - subtrahend;% Modulus remainder = dividend % divisor

    To some extent, you are already familiar with the notion of an operator: *, /, +, - are some arithmeticoperators you have used since elementary school studies. An operator is a symbol that stands for anoperation which to take place among one or more quantities. The arithmetic operators are types of binaryoperators, since they require two quantities to make sense. They take a left-hand-side expression and aright-hand-side expression; we apply the operator left-to-right to produce a result.

    All binary expressions have the form left hand side operator right hand side , where operator is oneof *, /, +, -, or %. Expressions can be chained together, as in a = 5 + 3 * 2;. In this case, DMAS orderis followed: division, multiplication, addition, subtraction. Therefore the expression 3 * 2 is computed firstto 6, which is then added to 5 to give 11. Associativity is left-to-right; so a = 2 + 3 - 5 first evaluates 2+ 3, then takes that result and subtracts 5.

    16

  • CHAPTER 2. VARIABLES AND EXPRESSIONS

    Expressions can be grouped with parentheses to change the order of operations. For example, in a = (5 +3) * 2, the 5 + 3 is evaluated first to produce 8, which is then multiplied by 2 to yield 16. As in arithmetic,our interpretation of the order of operations affects the result.

    The modulo operator % is of particular interest to computer science. It finds the remainder of an integerdivision. Recall dividing integers in grade school and reporting the remainder as a whole number; for example5/2 would be reported as 2r1, or 2 with a remainder of 1. This is equivalently 2 12 . So the modulus expression5 % 2 evaluates to 1, the remainder of integer division.

    For exponentiation, there is no operator. Instead we use a function known as pow, short for power. Thefunction pow is called as pow(base, exponent ). base and exponent are of type double, as is the returntype of pow. So, for example, pow(2.0, 4.0) is 24 and thus evaluates to 16.0.

    Truncation and Division by Zero

    Division by integer divisor has an interesting side effect called truncation. For example 5 / 2 does notevaluate to 2.5 as we might expect; instead it returns 2. This is because 5 and 2 are integers; the result ofany binary operation on two integers returns an integer. Integers (being integers) do not hold the exponentdata required to represent decimals. It can hold the integer portion of the quotient, i.e. 2. In any integerdivision that would otherwise result in a number of the form X.Y , the .Y will be truncated, leaving only theinteger X.

    Truncation happens even if we declare a variable of type float and store the result in it. However, ifwe re-write the expression as 5.0 / 2.0, where the numbers are clearly floating-point, they evaluate to afloating-point number. In fact, 5.0 / 2 also works, as well as 5 / 2.0. The less-conservative data type isselected as the type of the expression.

    Also beware of division by zero. For example, the following 1.0/0 will give a floating-point error at run-timesince division by zero is impossible.

    Typecasting

    Code 2.3-6: Typecasting

    1 #include 2 using namespace std;3

    4 int main() {5 cout

  • CHAPTER 2. VARIABLES AND EXPRESSIONS

    Compound Operators

    Compound OperatorsOperator Operation Usage Equivalent+= Addition x += addend; x = x + addend;*= Multiplication x *= multiplier; x = x * multiplier;/= Division x /= divisor; x = x / divisor;-= Subtraction x -= subtrahend; x = x - subtrahend;%= Modulus x %= divisor; x = x % divisor;++ Increment x++; x = x + 1;-- Decrement x--; x = x - 1;

    A compound operation is an operation that is performed on a variable and written back to that samevariable. An example is x = x + 2. Suppose x was 3 to begin with; then the expression is 3 + 2, which isevaluates to 5. Thus x + 2 evaluates to 5. However, this result is written back to x because x is assigned tothe value of the expression x + 2. So x then becomes 5, overwriting the old value 3.

    Similar examples are x = x - 5, where 5 is subtracted from x and then stored in it; or x = x * 10, and soforth. Shorthand forms are given in the table above. Two particular shorthand forms are of interest, namelythe increment and decrement operators. The increment operator ++ increases the value of a given variableby 1, and is the namesake of C++. The decrement operator likewise decreases the value of a variable by1.

    18

  • CHAPTER 2. VARIABLES AND EXPRESSIONS

    2.4 Boolean Algebra

    Comparison OperatorsOperator Operation Example== equality x == y! = inequality x != y> greater than x > y>= greater than or equal x >= y< less than x < y

  • CHAPTER 2. VARIABLES AND EXPRESSIONS

    Boolean expressions can be chained. Boolean operators and and or follow what are called truth tables forevaluating expressions.

    Value And Or0 1 0 1

    0 0 0 0 11 0 1 1 1

    20

  • Chapter 3

    Conditionals

    Contents3.1 If, If-Else, If-Elseif-Else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

    3.2 Switch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

    21

  • 3.1. IF, IF-ELSE, IF-ELSEIF-ELSE CHAPTER 3. CONDITIONALS

    3.1 If, If-Else, If-Elseif-Else

    Code 3.1-1: If-Construct

    1 #include 2 using namespace std;3

    4 int main() {5 bool rain = 1;6 if (rain) {7 cout

  • CHAPTER 3. CONDITIONALS 3.1. IF, IF-ELSE, IF-ELSEIF-ELSE

    Code 3.1-2: If-Construct

    1 #include 2 using namespace std;3

    4 int main() {5 bool rain;6 bool sunshine;7 cout > rain;9 cout > sunshine;11 if (rain && sunshine) {12 cout

  • 3.1. IF, IF-ELSE, IF-ELSEIF-ELSE CHAPTER 3. CONDITIONALS

    Code 3.1-3: If-Else

    1 #include 2 using namespace std;3

    4 int main() {5 bool rain = 1;6 if (rain) {7 cout

  • CHAPTER 3. CONDITIONALS 3.1. IF, IF-ELSE, IF-ELSEIF-ELSE

    Code 3.1-5: Taxes using Three Ifs

    1 #include 2 using namespace std;3

    4 int main() {5 float income , factor;6 cout > income;8 if (income < 9075) {9 factor = .1;10 }11 if (( income >= 9075) && (income 36900) {15 factor = .25;16 }17 cout

  • 3.1. IF, IF-ELSE, IF-ELSEIF-ELSE CHAPTER 3. CONDITIONALS

    In the top code on Line 5, income and factor are declared. The variable factor represents a factor bywhich income is multiplied to yield a tax amount. We prompt for income on Lines 6-7, then perform threeseparate tests on it to determine factor.

    If income is less than or equal to 9075, let factor be .1.

    If income is less than or equal to 36900 but greater than 9075, let factor be .15.

    In all other cases (that is, when income is greater than 36900), let factor be .25.

    Following the tests on Lines 8-16, we print out income*factor, that is the income we were originally givenmultiplied by the newly-assigned factor, the value of which is based upon income.

    In the top code, three conditionals need to be evaluated. Even if the first conditional is true (that is if anincome of less than 9075 is entered) and factor is assigned a value, the two conditionals afterward are stillevaluated (to false). As a result, factor does not change from its initial assignment of .1. This additionaltesting is an unfortunate waste of clock time, since we assigned factor already.

    To improve this situation, we introduce the if-elseif-else construct. This allows us to chain together mutuallyexclusive if-statements. A set of conditionals is mutually exclusive if only one of the conditionals in theset may be true. If-elseif-else constructs are useful for when the code inside it should be executed in amutually-exclusive fashion, for example, assigning a letter grade based upon a score.

    The bottom code achieves the equivalent result of the top code and on average, tests fewer conditionals. Ifincome < 9075 is evaluated to true, the code block within is executed and the total construct is exited;no others need to be tested because the conditionals are mutually exclusive. If income < 9075 is false,then income 9075 && income >= 36900; if theprocessor arrives at the conditional income =9075.

    Likewise the else-clause tests income > 36900, based upon the fact that neither of the previous conditionalscould have been true if the program arrived at the else. The variable factor is guaranteed to be assigneda value, since by the mutually-exclusive nature of if-elseif-else, all possible conditional cases are covered.

    26

  • CHAPTER 3. CONDITIONALS 3.2. SWITCH

    3.2 Switch

    Code 3.2-7: Grade Baseline Curving with Switch

    1 #include 2 using namespace std;3

    4 int main() {5 char grade;6 int baseline;7 cout > grade;9 switch (grade) {10 case A:11 baseline = 90;12 break;13 case B:14 baseline = 80;15 break;16 case C:17 baseline = 70;18 break;19 case D:20 baseline = 60;21 break;22 case F:23 baseline = 50;24 break;25 default:26 cout

  • 3.2. SWITCH CHAPTER 3. CONDITIONALS

    does not equal any of the given values covered by other cases, the default case block will be executed.

    28

  • Chapter 4

    Loops and Control Flow

    Contents4.1 For-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

    4.2 While-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

    4.3 For-Loop Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

    29

  • 4.1. FOR-LOOPS CHAPTER 4. LOOPS AND CONTROL FLOW

    4.1 For-Loops

    Code 4.1-1: For-Loop

    1 #include 2 using namespace std;3

    4 int main() {5 int i, n;6 cin >> n;7 for (i=1; i

  • CHAPTER 4. LOOPS AND CONTROL FLOW 4.2. WHILE-LOOPS

    4.2 While-Loops

    Code 4.2-2: While Loop

    1 #include 2 using namespace std;3

    4 int main() {5 int i=0;6 while (i < 10) {7 cout

  • 4.3. FOR-LOOP APPLICATIONS CHAPTER 4. LOOPS AND CONTROL FLOW

    4.3 For-Loop Applications

    Code 4.3-4: Sequence

    1 #include 2 #include 3 #include 4 using namespace std;5

    6 int main() {7 int i;8 for (i=1; i

  • CHAPTER 4. LOOPS AND CONTROL FLOW 4.3. FOR-LOOP APPLICATIONS

    Code 4.3-5: Function

    1 #include 2 #include 3 #include 4 using namespace std;5

    6 int main() {7 float x;8 float f;9 for (x=0; x

  • 4.3. FOR-LOOP APPLICATIONS CHAPTER 4. LOOPS AND CONTROL FLOW

    Code 4.3-6: Summation

    1 #include 2 using namespace std;3

    4 int main() {5 int i, n, S=0;6 cout > n;8 if (n < 1) return 1;9 for (i=1; i

  • CHAPTER 4. LOOPS AND CONTROL FLOW 4.3. FOR-LOOP APPLICATIONS

    Code 4.3-7: De-product

    1 #include 2 using namespace std;3

    4 int main() {5 int i, P;6 cout > P;8 for (i=1; P>1; i++)9 P /= i;10 cout

  • 4.3. FOR-LOOP APPLICATIONS CHAPTER 4. LOOPS AND CONTROL FLOW

    Code 4.3-8: Multiplication Table

    1 #include 2 #include 3 using namespace std;4

    5 int main() {6 int i, j;7 for (j=1; j

  • CHAPTER 4. LOOPS AND CONTROL FLOW 4.3. FOR-LOOP APPLICATIONS

    Code 4.3-10: Null

    1 #include 2 #include 3 #include 4 using namespace std;5

    6 int main() {7 int n = 1;8 float f;9 float x = 0;10 double sum = 1;11 double avg = 1;12 while (avg > .1) {13 x += .01;14 f = exp(-x) * sin(x);15 sum += abs(f);16 avg = sum / n++;17 cout

  • 4.3. FOR-LOOP APPLICATIONS CHAPTER 4. LOOPS AND CONTROL FLOW

    Code 4.3-11: Forward Difference Approximation

    1 #include

    2 #include

    3 #include

    4 using namespace std;

    5

    6 int main() {

    7 float x, f1, f2, d;

    8 f1 = pow(-2.1, 3.0);

    9 for (x=-2; x

  • CHAPTER 4. LOOPS AND CONTROL FLOW 4.3. FOR-LOOP APPLICATIONS

    39

  • 4.3. FOR-LOOP APPLICATIONS CHAPTER 4. LOOPS AND CONTROL FLOW

    40

  • Chapter 5

    Nesting

    Contents5.1 Conditional Nesting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

    5.2 Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

    41

  • 5.1. CONDITIONAL NESTING CHAPTER 5. NESTING

    5.1 Conditional Nesting

    Code 5.1-1: If inside If

    1 #include 2 using namespace std;3

    4 int main() {5 bool a, b;6 cin >> a;7 cin >> b;8 if (a)9 if (b)10 b = 0;11 else12 b = 1;13 cout

  • CHAPTER 5. NESTING 5.1. CONDITIONAL NESTING

    Code 5.1-3: For Inside If

    1 #include 2 using namespace std;3

    4 int main() {5 bool a;6 int i;7 cin >> a;8 if (a)9 for (i=1; i

  • 5.2. APPLICATIONS CHAPTER 5. NESTING

    5.2 Applications

    Code 5.2-5: Factoring

    1 #include 2 #include 3 using namespace std;4

    5 int main () {6 int i, n;7 cin >> n;8 for (i=1; i

  • CHAPTER 5. NESTING 5.2. APPLICATIONS

    Code 5.2-6: Boolean Crack

    1 #include 2 using namespace std;3

    4 int main() {5 int a, b, c, d;6 for (a=0; a

  • 5.2. APPLICATIONS CHAPTER 5. NESTING

    Code 5.2-7: Rolling Dice

    1 #include 2 #include 3 #include 4 using namespace std;5

    6 int main() {7 int a,b,c,i,j=0,s,N;8 cout > N;10 srand(time(NULL ));11 for (i=1; i

  • CHAPTER 5. NESTING 5.2. APPLICATIONS

    Code 5.2-8: Primes

    1 #include 2 #include 3 using namespace std;4

    5 int main () {6 int i, j;7 bool prime;8 for (j=2; j

  • 5.2. APPLICATIONS CHAPTER 5. NESTING

    Code 5.2-9: Heatup

    1 #include 2 #include 3 #include 4 #include 5 using namespace std;6

    7 int main() {8 float i,j,t,n=9,T=2;9 for (t=0; t

  • Chapter 6

    Algorithm Design and Analysis

    Contents6.1 Pseudocode Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

    6.2 Flowchart Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

    49

  • 6.1. PSEUDOCODE DESIGN CHAPTER 6. ALGORITHM DESIGN AND ANALYSIS

    6.1 Pseudocode Design

    Here is a pseudocode for writing pseudocode:

    Where P is a problem description,

    define Algorithm Synthesize Algorithm(P ):

    1. Based upon P , identify I, the set of inputs, their types, and their descriptions. Write these down.

    2. Identify the desired output O. This is what is output or returned by the algorithm. Write thisdown as well.

    3. Now solve an example case P by hand; but in doing so, for each step ai in the process of solvingP :

    (a) If ai is done in sequence, or many times, encase step ai within an iterative structure (a for,while, or do-while loop). Identify the parameters of the structure so that the repeated stepai is executed with correct starting conditions, stopping conditions, and step.

    (b) If ai is done conditionally, encase it within a selection structure (if, if-else, if-elseif-else, orswitch). Identify the conditions required to make ai execute only when it should.

    (c) Write down the step ai, without regard to its order in the final algorithm A.

    Use the problem specification P to identify the steps that need to be taken, in order from the mostobvious to the least. Bear in mind that the objective of the final algorithm A is to obtain O givenI.

    4. Then re-order all ai you have identified so that P is solved (O is obtained from I).

    5. Until A can be used to solve P :

    (a) Check A by solving the example problem P by following all the steps in A, in order.

    (b) Insert, remove or modify steps in A to account for missteps.

    6. Return A.

    50

  • CHAPTER 6. ALGORITHM DESIGN AND ANALYSIS 6.1. PSEUDOCODE DESIGN

    Identify set of inputs I,their types, and

    descriptions

    Read P critially.Scan for relevant

    information.

    Identify the output O andwhether or not it is

    stdout output, file output,or returned

    Pseudocodecan solveexample?

    Exampleproblemsolved?

    Start

    Finish

    false

    true

    false

    true

    First timesolving theproblem?

    Do and write downthe next step in

    solving the example problem.

    Re-order, modify,insert, or deletesteps until the

    problem is solved.

    true

    false

    51

  • 6.2. FLOWCHART DESIGN CHAPTER 6. ALGORITHM DESIGN AND ANALYSIS

    6.2 Flowchart Design

    Here is a pseudocode for drawing a flowchart:

    Where P is a problem description,

    define Algorithm Synthesize Flowchart(P ):

    1. Based upon P , identify I, the set of inputs, their types, and their descriptions. Write these downand draw parallelograms around them.

    2. Identify the desired output O. This is what is output or returned by the algorithm. Write thisdown and draw a parallelogram around it if it is output, or bubble if it is returned.

    3. Now solve an example case P by hand; but in doing so, for each step ai in the process of solvingP :

    (a) Write down the step ai, without regard to its order in the final algorithm A.

    Use the problem specification P to identify the steps that need to be taken, in order from the mostobvious to the least. Bear in mind that the objective of the final algorithm A is to obtain O givenI.

    4. For all the steps you have written, draw arrows as follows:

    (a) If ai is done in sequence with similar steps, or many times, encase the step within an iterativestructure (a for, while, or do-while loop) by drawing arrows in a loop which contains ai.Identify the parameters of the structure so that the repeated step ai is executed with correctstarting conditions, stopping conditions, and step.

    (b) If ai is done conditionally, identify the conditions required to make ai execute only when itshould, then write those down. Encase ai within a selection structure (if, if-else, if-elseif-else,or switch) by drawing a diamond around the condition, then branching to ai only if thecondition is true.

    5. Then order all the other ai you have identified by drawing arrows indicating the flow of the steps,so that P is solved (O is obtained from I).

    6. Until A can be used to solve P :

    (a) Check A by solving the example problem P by following all the steps in A, in order.

    (b) Insert, remove or modify steps in A, or re-draw arrows, to account for missteps.

    7. Return A.

    52

  • CHAPTER 6. ALGORITHM DESIGN AND ANALYSIS 6.2. FLOWCHART DESIGN

    Identify set of inputs I,and draw parallelograms

    around them

    Read P critially.Scan for relevant

    information.

    Identify the output O. Ifit is output to stdout

    draw a parallelogram,otherwise a bubble

    Flowchartcan solveexample?

    Exampleproblemsolved?

    Start

    Finish

    false

    true

    false

    true

    First timesolving theproblem?

    Do and write downthe next step in

    solving the example problem.,

    Draw a box around it.

    Delete or insertsteps, re-drawarrows to try tosolve example

    true

    false

    53

  • 6.2. FLOWCHART DESIGN CHAPTER 6. ALGORITHM DESIGN AND ANALYSIS

    54

  • Chapter 7

    Functions

    Contents7.1 Function Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

    7.2 Function Prototypes, Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

    7.3 Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

    55

  • CHAPTER 7. FUNCTIONS

    7.1 Function Basics

    Code 7.1-1: Introduction to Functions

    1 #include 2 using namespace std;3

    4 int f(int x) {5 return x*x;6 }7

    8 int main() {9 int x=0;10 for (x=-5; x

  • CHAPTER 7. FUNCTIONS

    The code below demonstrates the use of multiple arguments in a function call. The inputs given in thefunction call are called arguments, while the variables in the function signature for f are called parameters.The values 2, 3, and 5 are put in order as the arguments to f; thus they are assigned in that order to theparameters in the function signature for f. Thun x1 holds the value 2, x2 holds the value 3, and x3 holdsthe value 5. Finally the function prints the values.

    Code 7.1-2: Arguments

    1 #include 2 #include 3 #include 4 using namespace std;5

    6 void f(int x1, int x2 , int x3) {7 cout

  • CHAPTER 7. FUNCTIONS

    Code 7.1-3: Hello

    1 #include 2 using namespace std;3

    4 void hello () {5 cout

  • CHAPTER 7. FUNCTIONS

    7.2 Function Prototypes, Hierarchy

    Code 7.2-5: Prototypes

    1 #include 2 using namespace std;3

    4 void hello ();5 void goodbye ();6

    7 int main() {8 hello ();9 goodbye ();10 }11

    12 void hello () { cout

  • CHAPTER 7. FUNCTIONS

    Code 7.2-6: Function Composition

    1 #include 2 #include 3 #include 4 using namespace std;5

    6 float halve(float x) {7 return x/2;8 }9

    10 float \hyperref[def:increment ]{ increment }(float x) {11 return x+1;12 }13

    14 float square(float x) {15 return x*x;16 }17

    18 int main() {19 cout

  • CHAPTER 7. FUNCTIONS

    Code 7.2-7: Function Hierarchy

    1 #include 2 #include 3 #include 4 using namespace std;5

    6 void a() {7 cout

  • CHAPTER 7. FUNCTIONS

    Code 7.2-8: Function Overloading

    1 #include 2 using namespace std;3

    4 int add(int a, int b);5 float add(float a, float b);6 int add(int a, int b, int c);7

    8 int main() {9 cout

  • CHAPTER 7. FUNCTIONS

    7.3 Applications

    Code 7.3-9: Sums and Products

    1 #include 2 using namespace std;3

    4 /**5 * Sums from a to b in step in O(n) time.6 */7 int sum(int a, int b, int step) {8 int i, sum=0;9 for (i=a; i

  • CHAPTER 7. FUNCTIONS

    2. For each integer i from a to b inclusive in steps of j:

    (a) Let S S + i.3. Return S.

    64

  • CHAPTER 7. FUNCTIONS

    Code 7.3-10: Multiplication Tables

    1 #include 2 #include 3 #include 4 using namespace std;5

    6 /**7 * Outputs multiplication table in O(mn) time , O(1) space.8 */9 void multitable(int x1 , int x2 , int y1 , int y2) {10 int x, y;11

    12 // Prints the column header13 cout

  • CHAPTER 7. FUNCTIONS

    Code 7.3-11: Left Difference Approximation

    1 #include 2 #include 3 #include 4 using namespace std;5

    6 float f(float x) {7 return pow(x, 2) - 5*x + 6;8 }9

    10 int main() {11

    12 float x, h=.01, fp;13

    14 cout > x;16 cout

  • CHAPTER 7. FUNCTIONS

    Code 7.3-12: Boolean Bit-Flipping

    1 #include 2 using namespace std;3

    4 void switchup(bool a, bool b) {5 if (a) b = !b;6 if (b) a = !a;7 cout > b;13 switchup(a, b);14 cout

  • CHAPTER 7. FUNCTIONS

    This code illustrates a re-encoding of a 2-bit sequence ab. If a is true, b is flipped; then b is evaluated. If itis true, then the value of a is flipped. So

    00 yields 00;

    01 yields 11;

    10 yields 01;

    11 yields 10.

    Where a, b are boolean variables in the sequence a, b:

    define Algorithm Switchup(a, b):

    1. If a is true, let b b; otherwise let b = b.2. If b is true, let a a; otherwise let a = a.3. Output ab.

    68

  • CHAPTER 7. FUNCTIONS

    Code 7.3-13: Fibonacci Sequence

    1 #include 2 using namespace std;3

    4 /**5 * Computes Fibonacci sequence in O(n) time , O(1) space.6 */7 int fib(int n) {8 int j, f1=1, f2=1, f;9 for (j=1; j

  • CHAPTER 7. FUNCTIONS

    70

  • Chapter 8

    Files

    Contents8.1 Passing by Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72

    8.2 Input from a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

    8.3 Output to a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76

    8.4 Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

    71

  • CHAPTER 8. FILES

    8.1 Passing by Reference

    Code 8.1-1: pass-by-ref

    1 #include 2 using namespace std;3

    4 void \hyperref[def:swap]{swap}(char &a, char &b) {5 char c = a;6 a = b;7 b = c;8 }9

    10 int main() {11 string word = "dormitory";12 \hyperref[def:swap]{swap}(word[1], word [4]);13 \hyperref[def:swap]{swap}(word[3], word [5]);14 \hyperref[def:swap]{swap}(word[4], word [8]);15 \hyperref[def:swap]{swap}(word[5], word [7]);16 \hyperref[def:swap]{swap}(word[7], word [8]);17 cout

  • CHAPTER 8. FILES

    Where

    a : int : int to swapb : int : int to swap

    define Algorithm swap(a, b):

    1. Let c a.2. Let a b.3. Let b c.4. Return (a, b).

    73

  • CHAPTER 8. FILES

    8.2 Input from a File

    Code 8.2-2: input-from-file

    1 #include 2 #include 3 #include 4 #include 5 using namespace std;6

    7 int main() {8 int sylls;9 string word;10 ifstream infile;11 infile.open("words.txt");12 if (infile) {13 while (infile >> word >> sylls) {14 cout

  • CHAPTER 8. FILES

    operator. Similarly there exists std::right for right-flushing. On the condition that the file open fails (filenot found, wrong permissions, etc.), an error message is printed to that effect.

    75

  • CHAPTER 8. FILES

    8.3 Output to a File

    Code 8.3-3: output-to-file

    1 #include 2 #include 3 #include 4 #include 5 using namespace std;6

    7 int main() {8 int start=33, end=126, i;9 ofstream outfile;10 outfile.open("ascii.dat");11 if (outfile) {12 for (i=start; i

  • CHAPTER 8. FILES

    Code 8.3-4: input-and-output

    1 #include 2 #include 3 #include 4 #include 5 using namespace std;6

    7 int main() {8 int charge;9 string name , symbol;10 ifstream infile;11 ofstream outfile;12 infile.open("infile.dat");13 outfile.open("outfile.dat");14 if (infile && outfile) {15 while (infile >> name16 >> symbol17 >> charge) {18 outfile

  • CHAPTER 8. FILES

    8.4 Applications

    8.4.1 Ionic Data Lookup

    Code 8.4-5: ion-lookup

    1 #include 2 #include 3 #include 4 #include 5 using namespace std;6

    7 string symbol (string n) {8 int charge;9 string name , symbol;10 ifstream infile;11 infile.open("ions.dat");12 if (infile) {13 while (infile >> name14 >> symbol15 >> charge) {16 if (n == name)17 return symbol;18 }19 }20 cout

  • CHAPTER 8. FILES

    8.4.2 Self-Copying Programs

    Code 8.4-6: copycat

    1 #include 2 #include 3 #include "string.h"4 #include 5 using namespace std;6

    7 int main(int argc , char** argv) {8 if (strcmp(argv[0],"j.bin")==0) exit (0);9 ifstream i;10 ofstream you;11 i.open(argv[0], ios:: binary );12 argv [0][0]++;13 you.open(argv[0], ios:: binary );14 char* c = new char [1];15 while ( i.read (c, 1)) {16 you.write(c, 1);17 }18 i.close ();19 you.close ();20 char *cmd;21 cmd = new char [16];22 strcpy(cmd , "chmod 755 ");23 strcat(cmd , argv [0]);24 system(cmd);25 system(argv [0]);26 return 0;27 }

    This program is an example of advanced file I/O concepts, including binary reading, binary writing, andsystem command execution on files.

    The program is compiled and run as follows:

    g++ copycat.cpp -o a.bina.bin

    The executable a.bin will then have its instruction code copied to memory as it executes. It will openitself for binary reading (Line 11), then increment the first letter in its name (argv[0], whose first letter isargv[0][0]) so that a becomes b (Line 12). It will then open a file by that name called b.bin (Line 13) forbinary writing.

    It then allocates a character pointer called c for a character array of size 1 to prepare to copy itself

    79

  • CHAPTER 8. FILES

    byte-wise. Pointers will be discussed later; for now, let it suffice to say that c acts as a handler for a singlecharacter. The file is then copied byte-wise (Lines 15-16) and both files are promptly closed (Lines 17-18).

    The program then prepares a character buffer of size 16 (Lines 20-21) to hold a command to execute, thatis chmod 755 (Line 22). It appends the name of the new files to make chmod 755 b.bin (Line 23), whichrenders the new file executable once executed (Line 24). Finally the new file is executed as in b.bin (Line25).

    80

  • CHAPTER 8. FILES

    8.4.3 Forensics

    Code 8.4-7: forensics

    1 #include 2 #include 3 #include 4 #include "string.h"5 #include 6 using namespace std;7

    8 #define N 89

    10 bool isascii(char c) {11 if (c > 31 && c < 125) return true;12 else return false;13 }14

    15 int main() {16 ifstream infile;17 infile.open("floppy.dat", ios:: binary );18 char* c = new char [1];19 char block[N];20 int i;21 while (infile.read(c,1)) {22 if (isascii(c[0])) {23 if (i < N) block[i++] = c[0];24 else if (i++ == N) cout

  • CHAPTER 8. FILES

    character (Line 26) and we had already read a block, we print a newline (Line 27), and regardless we resetthe counter back to 0 to indicate that we wish to start a new block.

    Once the program finishes reading, it close the file (Line 31).

    82

  • CHAPTER 8. FILES

    8.4.4 Parsing Music Notes

    Code 8.4-8: parse-notes

    1 #include 2 #include 3 #include 4 #include 5 using namespace std;6

    7 int half_steps(string note) {8 int n, offset =0;9 if (note[0]>B) offset ++;10 if (note[0]>E) offset ++;11 n = (note [0] - A)*2 - offset;12 int i = 1;13 if (note [1] == b) { i++; n--; }14 else if (note [1] == #) { i++; n++; }15 n += (note[i] - 4)*12;16 return n;17 }18

    19 int main() {20 string note;21 ifstream infile;22 infile.open("notes.dat");23 if (infile) {24 while (infile >> note) {25 cout

  • CHAPTER 8. FILES

    A[4 is -1 half-steps from A4 while A#4 is 1 half-step from A4. B4 is 2 half-steps from A4, while G3 is -2half-steps from A4. A difference in note (A,B,C, etc.) indicates a separation of 2 half-steps; a flat-sharp is1 half-step; and an octave is 12: 2 for each of the seven notes, except there is no half-step between B and Cor E and F .

    The program reads the strings indicating the notes into note and calls a function half steps of returntype int to calculate the half-steps. In that function, first character in the string note, which gives themusic note, is subtracted off from the literal character 0, whose ASCII decimal equivalent is 65. Also, theequivalent of A is 65, B is 66, and so on. Thus the difference note[0] from A is equivalent to the numberof steps away. Multiplying by 2 gives the number of half-steps (since two half-steps form one step).

    To deal with the optional flat/sharp indicator, we introduce i as a variable index. If in fact note[1] is a flator sharp indicator, we decrement or increment n; also we increment i in either case so that i then equals 2,and thus indexes the octave. If note[1] is neither a flat nor sharp indicator, we do no such increment andi still then references the octave number (since it must be at position 1).

    The half-steps per octave is 12 (for 7 notes per octave, 2 half-steps per step, with two exceptions), and wesubtract note[i] from literal 4 to obtain how many octaves removed from A4 we are.

    84

  • Chapter 9

    Libraries

    85

  • CHAPTER 9. LIBRARIES

    Code 9.0-1: math

    1 #include 2 #include 3 using namespace std;4

    5 int main() {6

    7 float x=sqrt(2), y=M_PI;8

    9 cout

  • CHAPTER 9. LIBRARIES

    Code 9.0-2: blink

    1 #include 2 #include 3 #include "unistd.h"4 using namespace std;5

    6 /**7 * Blinks messages a, b for t1, t2 respectively.8 */9 void blink( string a,10 string b,11 unsigned int t1,12 unsigned int t2 ) {13 int i;14 cout

  • CHAPTER 9. LIBRARIES

    Code 9.0-3: typeout

    1 #include 2 #include 3 #include "unistd.h"4 using namespace std;5

    6 /**7 * Types out string to console.8 */9 void typeout(string str) {10 int i;11 unsigned int naptime = 30000; //!< Time delay between characters12 for (i=0; i

  • CHAPTER 9. LIBRARIES

    Code 9.0-4: libalgebra/algebra

    1 #include 2 #include "algebra.h"3

    4 namespace alg {5

    6 /**7 * Finds the x-intercept of a linear equation y=mx+b given m and b.8 */9 float x_intercept(float m, float b) {10 return -b/m;11 }12

    13 /**14 * Solves the quadratic equation given a, b, c; returns left -hand result.15 * If the result is an imaginary number , returns NaN.16 */17 float quadratic(float a, float b, float c) {18 float res; //!< Holds the result19 if (pow(b,2.0) - 4.0*a*c >= 0.0)20 res = (-b - sqrt(pow(b, 2.0) - 4.0*a*c)) / (2.0*a);21 else res = nan("NaN");22 return res;23 }24

    25 }

    Above are two functions x intercept and quadratic, defined in a file algebra.cpp. The correspondingfunction prototypes are defined inside algebra.h, which is included in this function definition file.

    The functions are defined inside their own namespace, alg. Similar to the cout object and its std namespace,in order to refer to the functions outside of the alg namespace, one must use the scope operator (::) as inalg::quadratic(a, b, c); that is, unless the statement using namespace alg; appears where they areto be used.

    89

  • CHAPTER 9. LIBRARIES

    Code 9.0-5: libalgebra/algebra

    1 namespace alg {2

    3 float x_intercept(float m, float b);4 float quadratic(float a, float b, float c);5

    6 }

    Above are the contents of the function definition file algebra.h. Within are function prototypes forx intercept and quadratic, defined in a separate file algebra.cpp. This is the header file that mustbe included by algebra.cpp and all examples which use the library.The prototypes in the header files are defined inside their own namespace, alg; the significance of namespaceis explained along with algebra.cpp.

    Code 9.0-6: libalgebra/main

    1 #include 2 #include "algebra.h"3 using namespace std;4 using namespace alg;5

    6 int main() {7

    8 float a, b, c;9 float m, y0;10

    11 cout > a; cin >> b; cin >> c;13 cout > y0;17 cout

  • CHAPTER 9. LIBRARIES

    91

  • CHAPTER 9. LIBRARIES

    Code 9.0-7: libtypeout/typeout

    1 #include

    2 #include

    3 #include "unistd.h"

    4 #include "typeout.h"

    5 using namespace std;

    6

    7 /**

    8 * Types out to console.

    9 */

    10 namespace typ {

    11

    12 void typeout(string str) {

    13 int i;

    14 unsigned int naptime = 30000; //!< Time delay between characters

    15 for (i=0; i

  • CHAPTER 9. LIBRARIES

    Code 9.0-8: libtypeout/typeout

    1 #include 2 using namespace std;3

    4 namespace typ {5 void typeout(string str);6 void typeout(string str , unsigned int naptime );7 void typeout(int a, int b, int step);8 void typeout(int a, int b, int step , unsigned int naptime );9 }

    Code 9.0-9: libtypeout/goodbye

    1 #include 2 #include "typeout.h"3

    4 int main() {5 string goodbye = "See you later!\n";6 typ:: typeout(goodbye );7 }

    This simple file tests libtypeout. It includes typeout.h to make available the function voidtypeout(string s) for use with the string See you later!. Line 6 demonstrates the use of the scopeoperator to refer to the typeout function in the typ namespace.

    Code 9.0-10: libtypeout/sequence

    1 #include "typeout.h"2 using namespace std;3 using namespace typ;4

    5 int main() {6 int i;7 for (i=0; i

  • CHAPTER 9. LIBRARIES

    94

  • Chapter 10

    Arrays and Matrices

    95

  • CHAPTER 10. ARRAYS AND MATRICES

    Code 10.0-1: array-example

    1 #include 2 using namespace std;3

    4 #define N 105

    6 int main() {7 int a[N] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};8 int i;9 //a[7] = 6;10 for (i=0; i

  • CHAPTER 10. ARRAYS AND MATRICES

    Code 10.0-2: array-dot-product

    1 #include 2 #include 3 using namespace std;4

    5 int dot (int u[], int v[], int n) {6 int sum = 0;7 for (int i=0; i

  • CHAPTER 10. ARRAYS AND MATRICES

    Code 10.0-3: array-min-max

    1 #include 2 #include 3 using namespace std;4

    5 #define N 106

    7 int min(int v[]) {8 int i, min=v[0];9 for (i=0; i v[i])11 min = v[i];12 return min;13 }14

    15 int ) {16 int i, min=v[0], argmin =0;17 for (i=0; i v[i]) {19 min = v[i];20 argmin = i;21 }22 return argmin;23 }24

    25 int max(int v[]) {26 int i, max=v[0];27 for (i=0; i

  • CHAPTER 10. ARRAYS AND MATRICES

    The above code illustrates the algorithms min, max, argmin, and argmax; that is for finding the minimumand maximum of an array and the corresponding indices for the minimum and maximum.

    The pseudocodes for min and argmin are given below. With a change of names and the direction of thecomparison operator >, one can derive the max algorithms.

    Where

    ~a : array in which to find minimum

    define Algorithm min(~v):

    1. Let min v0.2. For i in the range [0, n):

    (a) If min > vi:

    i. Let min vi.3. Return min.

    Where

    ~a : argmin

    define Algorithm argmin(~v):

    1. Let min v0.2. For i in the range [0, n):

    (a) If min > vi:

    i. Let min vi.ii. Let argmin i.

    3. Return argmin.

    99

  • CHAPTER 10. ARRAYS AND MATRICES

    Code 10.0-4: array-sum

    1 #include 2 #include 3 #include 4 using namespace std;5

    6 #define N 107

    8 int sum(int a[]) {9 int i, sum=0;10 for (i=0; i

  • CHAPTER 10. ARRAYS AND MATRICES

    Code 10.0-5: matrix-example

    1 #include 2 using namespace std;3

    4 #define N 45 #define M 56

    7 int main() {8 int A[N][M] = {9 {1, 2, 4, 3, 5},10 {3, 5, 2, 1, 4},11 {2, 3, 5, 4, 1},12 {4, 1, 2, 5, 3}13 };14 int i, j;15 for (i=0; i

  • CHAPTER 10. ARRAYS AND MATRICES

    Code 10.0-6: matrix-scalar-mul

    1 #include

    2 #include

    3 using namespace std;

    4

    5 #define N 4

    6 #define M 5

    7

    8 void scalar_mul(int a[N][M], int b) {

    9 int i, j;

    10 for (i=0; i

  • CHAPTER 10. ARRAYS AND MATRICES

    Code 10.0-7: matrix-mul

    1 #include 2 #include 3 using namespace std;4

    5 #define N 46 #define M 57

    8 void print_matrix(int A[N][M]);9 void print_matrix(int A[M][N]);10 void print_square(int A[N][N]);11

    12 // c_ij = sum from k to M of a_ik * b_kj13 void matrix_mul(int A[N][M], int B[M][N], int C[N][N]) {14 int i, j, k;15 for (i=0; i

  • CHAPTER 10. ARRAYS AND MATRICES

    This code illustrates matrix multiplication of two matrices A and B. In this example, A is an NxM matrixand B is an MxN matrix AB of size NxN using the following formula:

    ABij =Nk

    AikBkj .

    That is, for each element ABij in the resulting matrix, take the dot product of the column of A and therow of B.

    104

  • CHAPTER 10. ARRAYS AND MATRICES

    Code 10.0-8: matrix-passing

    1 #include 2 using namespace std;3

    4 void print_matrix(int A[4][5]) {5 int i, j;6 for (i=0; i

  • CHAPTER 10. ARRAYS AND MATRICES

    Code 10.0-9: matrix-transpose

    1 #include

    2 using namespace std;

    3

    4 #define N 4

    5 #define M 5

    6

    7 void transpose(int A[N][M], int B[M][N]) {

    8 int i, j;

    9 for (i=0; i

  • CHAPTER 10. ARRAYS AND MATRICES

    This code illustrates the transpose of a matrix. For an NxM matrix A, the transpose AT can be defined as

    ATji = Aij .

    That is, for each element, flip the indices. Or, make the rows into columns and the columns into rows.This principle is captured on Line 11, when a matrix A is copied into B except that the indices have beenswitched. Notice that A is NxM , but B is MxN .

    107

  • CHAPTER 10. ARRAYS AND MATRICES

    108

  • Chapter 11

    Structs

    109

  • CHAPTER 11. STRUCTS

    Code 11.0-1: struct

    1 #include 2 #include 3 using namespace std;4

    5 struct character {6 int hp , mp;7 string name;8 };9

    10 int main() {11 character dc;12 dc.hp = 100;13 dc.mp = 50;14 dc.name = "D. Castleberry";15 cout

  • CHAPTER 11. STRUCTS

    Code 11.0-2: structarray

    1 #include 2 #include 3 #include 4 #include 5 using namespace std;6

    7 #define N 58

    9 struct character {10 int hp , mp , lvl;11 string name;12 };13

    14 int main() {15 int i;16 character party[N];17 string names[] = {18 "H. Kaiser",19 "C. Douglas",20 "W. Duncan",21 "D. Castleberry",22 ""23 };24 cout

  • CHAPTER 11. STRUCTS

    A counter is declared for looping (Line 15) and then a struct array of type character called party (Line16). A string array called names is initialized for copying the names into the struct array later (Lines 17-23).The last name can be entered (Lines 24-25). An RNG is seeded (Line 26) and the ith party members statsare determined from formulas based upon i (Lines 28-30). The names are also copied from the names array(Line 31).

    Finally the stats are displayed (Lines 33-39).

    112

  • Chapter 12

    Recursion

    113

  • CHAPTER 12. RECURSION

    Code 12.0-1: rec-hello

    1 #include 2 using namespace std;3

    4 void hello () {5 cout

  • CHAPTER 12. RECURSION

    Code 12.0-2: rec-count

    1 #include 2 using namespace std;3

    4 void count(int i) {5 cout

  • CHAPTER 12. RECURSION

    Code 12.0-3: rec-sum

    1 #include 2 using namespace std;3

    4 int sum(int i, int n) {5 if (i==n) return n;6 return i+sum(i+1, n);7 }8

    9 int main() {10 cout

  • CHAPTER 12. RECURSION

    Code 12.0-4: rec-factorial

    1 #include 2 using namespace std;3

    4 int factorial(int n) {5 if (n

  • CHAPTER 12. RECURSION

    Code 12.0-5: rec-fib

    1 #include 2 using namespace std;3

    4 int fib(int n) {5 if (n

  • CHAPTER 12. RECURSION

    Code 12.0-6: dyn-fib

    1 #include 2 using namespace std;3

    4 int fib(int n) {5 int i, fn2=1, fn1=1, fn;6 for(i=3; i

  • CHAPTER 12. RECURSION

    Code 12.0-7: rec-indirect

    1 #include 2 using namespace std;3

    4 void a(int n);5 void b(int n);6

    7 void a(int n) {8 cout

  • Appendix A

    Problem Sets

    ContentsA.1 Problem Set 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122

    A.2 Problem Set 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125

    A.3 Problem Set 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129

    A.4 Problem Set 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133

    121

  • A.1. PROBLEM SET 1 APPENDIX A. PROBLEM SETS

    A.1 Problem Set 1

    122

  • APPENDIX A. PROBLEM SETS A.1. PROBLEM SET 1

    1. [20] Hello, world! L. 1 Application (Computer Science). Write a program that prints

    Hello, world!

    to the screen. The output must be character-for-character identical: with correct spelling [2x2], punctuation[2x2], and capitalization [2x2]; a newline should be printed afterward [4]. It should return 0 [2] and donothing else [2]. Name the source file hello-world.cpp [-5]. As with all programs, it must compile [-10]and be free of run-time errors [-10].

    2. [20] Variables and Expressions L. 3 Application (Mathematics). Consider the function

    f(x) = |x| 12x2 +

    13x3 + sin(x)ex.

    Write a program to approximate the derivative f (x) for any input x by use of the central difference methodformula:

    f (x) f(x+ h) f(x h)2h

    ,

    where h = .001 and f is defined above. Define correct types [3x1], prompt for x [1], write the code-form ofthe equations correctly [5x2], and format the output as shown [3x2]:

    x : _f : _f: _

    where is the output. Use setw(8) and setprecision(2) for f and f . Call the programdifference-approx.cpp [-5].

    123

  • A.1. PROBLEM SET 1 APPENDIX A. PROBLEM SETS

    4. [25] For/For L. 3 Application (Mathematics). Write a program to compute

    nj=1

    ji=1

    i.

    Prompt with Enter n: , then output The sum of product is (where is the result) followed by anewline [10]. Call this sum-of-product.cpp [-5].

    Also write another program which can, given a sum of a product generated in this fashion, find n.Prompt with Enter sum of product: and output n is followed by a newline [15]. Call thisreverse-sum-of-product.cpp [-5].

    3. [40] If and Boolean Logic L. 4 Application (Computer Science). I have a code which accepts booleanvalues a, b, and c as input, in that order, with no prompt. Once entered, it executes the following pseudocode:

    If c is true, flip the value of a. Then if b is true, flip the value of c. Then if a is true, flip the value of b.

    It then outputs abc. Write a code that accepts the output of my code and derives the original abc. Use onlythree boolean variables and output the solution as specified [10]. For full credit the solution must use onlythree conditionals and three flips [30=3x10]. Program interaction looks like:

    > 1 0 1< 1 1 0

    124

  • APPENDIX A. PROBLEM SETS A.2. PROBLEM SET 2

    A.2 Problem Set 2

    125

  • A.2. PROBLEM SET 2 APPENDIX A. PROBLEM SETS

    1. [20] Strings, Library Functions L. 2 Application (Linguistics). Translate the following pseudocode intoC++ code. Let s be a string input through stdin in main [2]. Make functions swap [4] and reverse [8], andinclude their prototypes [2=2x1]. Above each function in multi-line block comment, provide a one-sentencecomment which gives a brief description of what it does [2=2x1]. Use the variable names in the pseudocode[2]. Use unistd.h for time functions and string() to clear the screen. Use std::flush to flush standardoutput before each wait time inside the for-loop. Call it string-reverse.cpp [-5].

    1. Define Swap(a, b):

    (a) Let c a.(b) Let a b.(c) Let b c.(d) Return (a, b).

    Where

    s : string

    define Reverse String(s):

    1. Let S size(s).2. Clear the screen.

    3. Output s.

    4. Wait for 1 second.

    5. For i in the range [0, S/2):

    (a) Clear the screen.

    (b) Swap(s[i], s[S i 1]).(c) Output s and end line.

    (d) For all characters j in the range [0, S 1]:i. If j = i or j = S-i-1, print a caret ().ii. Else print a space.

    (e) Wait for 500 milliseconds.

    6. Wait for 1 seconds.

    7. Return s.

    126

  • APPENDIX A. PROBLEM SETS A.2. PROBLEM SET 2

    2. [30] File I/O: L. 3 Application (Chemistry). Write a program which accepts two strings a and b fromstdin [4] each representing the names of two distinct ionic particles to undergo an ionic bonding into a singleproduct. The program should then produce the reaction equation. Use a provided dictionary D containingentries name, symbol, charge to lookup the symbols and charges for names a and b.

    Prompt for a with A: and b with B: [2=2x1], then output the reaction as given in the example [4]. Createa function void react(string a, string b) [10] to output the reaction. Also write other functions: intcharge(string name) which looks up charge from the file [5] and string symbol(string name) whichlooks up symbol from the file [5], each to be called by react. Document these functions with a multi-linecomment block and a one-line description per function [4]. Call the code ionic-reaction.cpp [-5]. Anexample is:

    A: magneiumB: sulphateMg + SO4 -> (Mg)2(SO4)2Makes magnesium sulphate.

    Note that if charges of -1 or +1 are exchanged, there should be no parentheses surrounding the product:

    A: sodiumB: hydroxideNa + OH -> NaOHMakes sodium hydroxide.

    Also, if the lookup fails, print that the string entered was not found in the dictionary:

    A: sodiujB: hydroxidesodiuj was not found in the dictionary.

    Where a is the name of the first reactant, b is the name of the second reactant, and D is a dictionaryfile which contains entries n, sn, cn: where n is the name of some reactant in D, sn is the symbol of n,and cn is the charge of n,

    define Ionic Reaction(a, b,D):

    1. Lookup ca, sa, cb, sb in D.

    2. Output sa + sb (sa)cb(sb)ca .3. Output Makes a b.

    127

  • A.2. PROBLEM SET 2 APPENDIX A. PROBLEM SETS

    3. [50] Functions and Libraries L. 4 Application (Music, Physics). Write a library of functions to composemusic from raw sound data. Write functions:

    uint8 t wave(float f, float t)

    float freq(string note)

    void play(string note, float duration)

    Define these [2x15] in a file sound.cpp. Also write a header file sound.h [5], example usage example.cppwhich writes to a file sound.raw [5], and a Makefile to compile the library as well as the example, completewith a clean rule [5]. Create the functions in a namspace called snd. Document the two library functions[4=2x2] and the example [1] by writing one-sentence descriptions in multi-line comment blocks above thefunction definitions.

    The function wave will generate a sound wave given any frequency f at time t. Include unistd.h to makethe function of type uint8 t. The function to generate a sound wave is:

    A(f, t) = Asin(2piftR )

    Let the volume constant A = 127, the sampling rate R = 8000, and phase shift = 0.

    Additionally a function freq will tell the frequency of any musical note entered as a string in scientific pitchnotation. It will contain the note (as a character A-G), an optional flat/sharp indicator (b, #, or nothing),followed by an octave (integer 1 to 8), in that order. Examples include:

    A4: A4, or 440 Hz.

    Bb4: B[4, or 466.16 Hz.

    C#3: C]4, or 138.59 Hz.

    Calculate the frequency by parsing the string note and using the formula:

    fn = f0(a)n

    where f0 is the frequency of a fixed note, a = 2112 , and n is the number of half-steps or semitones away from

    the fixed note fn is. Use f0 = 440 Hz for A4. Be sure to name all the files correctly [-25=5x-5].

    128

  • APPENDIX A. PROBLEM SETS A.3. PROBLEM SET 3

    A.3 Problem Set 3

    129

  • A.3. PROBLEM SET 3 APPENDIX A. PROBLEM SETS

    1. [10] Strings/Files L. 1 Application (Computer Science). Write a program called hello-generator.cppwhich generates a program called hello-world.cpp. It should do so by opening the file hello-world.cppfor writing, and output a Hello, world! program to it line-by-line in the form of strings. The generated codeshould look like this:

    #include using namespace std;

    int main() {cout , which accepts commandsseq, sum, and prd, which argument lists. It will then execute the corresponding library function given thearguments input on the command prompt and give its output on the next line, followed by a line break[15=5x3 or 3x5]. Here is an example of program interaction:

    > seq 1 10 11 2 3 4 5 6 7 8 9 10> sum 1 10 155> prd 1 36

    Call this program x -interpreter.cpp, where x is one of seq, word, or html, after the library you arewriting the interpreter for [-5].

    130

  • APPENDIX A. PROBLEM SETS A.3. PROBLEM SET 3

    3. [30] Arrays and Files L. 4 Application (Psychology). Your task is to find (a) the person in the classwho is most similar to you and (b) the person in the class who is most different from you. The data fileD, or neo-ffi.dat, contains personality data from your classmates in the form of N size-10 vectors. First,identify your entry and delete it from the file. Then load your entry vector x into a size-10 array and thedata from D into a matrix P ; then compute the Manhattan distance between your vector x and eachvector yj P ; that is

    10i

    |xi yji|.

    Load these distances into an array of size N . Then use functions argmin and argmax to find the indices ofthe most similar and most different vectors, respectively; that is

    arg minj

    [ 10i

    |xi yji|],yj P

    arg maxj

    [ 10i

    |xi yji|],yj P

    The program will output Similar: then the space-delimited vector; also Different: , and the same.E.g.:

    Similar: 1 3 2 4 5 4 3 2 1 2Different: 5 5 5 1 2 1 1 5 5 4

    be sure to align them, like so [2x5]. Create [3x5] and use [5] the functions

    int argmin (int x[N]);int argmax (int x[N]);int manhattan(int x[N], int y[N]);

    Call this program find-person.cpp [-5].

    If you find the name of the person most similar and place their name as in First Last into a text filesimilar.txt; and the name of the person most different and place it into a text file different.txt; thenI will drop a test question for each of the two that is correct.

    131

  • A.3. PROBLEM SET 3 APPENDIX A. PROBLEM SETS

    4. [40] Matrices, Boolean Logic L. 5 Application (Biology). You will implement a simulation of cellularlife, i.e. a cellular life automata, as per the rules in Conways Game of Life.

    You will create a board B of size NxM , where N = 65 and M = 20, of type boolean. To initialize the board,for each element bij B, set bij to 1 with 10% probability, 0 otherwise. You may do this using the rand()function from cstdlib and a modulus operation. Initialize the board inside a function init board.

    For each iteration in the evolution of the board, create the next board as follows:

    1. For each element bij B:(a) Count the Moore neighbors of bij (all the neighbors in the 8 adjacent cells) and set that

    number to n. Then:

    i. If n > 3: bij 0.ii. Else if n > 1 and bij = 1: bij 1.iii. Else if n < 2: bij 0.iv. Else if n = 2 and bij = 0 : bij 1.

    You will need to copy the board beforehand in order to ensure the integrity of the checks in the if-elseif-elsestructure.

    After obtaining the next board, print the board, wait 60 ms, and clear the screen for the next iteration[8]. Every 50 iterations, disinfect the board; that is for all bij B, let bij 0 with probability .5. Writefunctions [30=5x6]:

    int moore (bool x[N][M], int i, int j);void init_board(bool x[N][M]);void next_board(bool x[N][M]);void print_board(bool x[N][M]);void clean_board(bool x[N][M]);

    Inside main, make a call to init board, then loop over calls to next board and print board and theoccasional clean board.

    Name the file conway.cpp [-5].

    132

  • APPENDIX A. PROBLEM SETS A.4. PROBLEM SET 4

    A.4 Problem Set 4

    133

  • A.4. PROBLEM SET 4 APPENDIX A. PROBLEM SETS

    [20] Expressions, Arrays L. 2 Application (Mathematics). Write a program to compute the cross productof two vectors ~u = u1, u2, u3 and ~v = v1, v2, v3, that is ~u ~v = w1, w2, w3, using the equations

    w1 = u2v3 u3v2w2 = u3v1 u1v3w3 = u1v2 u2v1

    Give the user a prompt u> , then read 3 integers. Also prompt with v> and read 3 integers. Write afunction cross(int u[], int v[], int w[]) which does a cross product of ~u and ~v and stores the resultin ~w. Then output the result like so:

    w< 3i + 4j - 5k

    Name this cross-product.cpp [-5]. If you want, create a library [+20] and interpreter [+20] for the func-tions int add(int u[], int v[], int w[], int n), int dot(int u[], int v[], int n) and voidcross(int u[], int v[], int w[], int n) for use with vector problems. For dot and add, you willneed to have the user enter n (the function cross will only support n = 3). Interaction looks like:

    > dot 3> 1> -2> 3

    < ok> 1> 3> 2

    < ok< 1

    [20] Loops, Functions L. 2 Application (Physics). Simulate the throwing of a ball into the air using theparametric equations:

    x(t) = t,

    y(t) =t2

    60 t+ 25,

    on an ASCII gride of size 25x60. Define macros N = 25,M = 60. Modify print board fromball-bounce.cpp to print a ball at x, y coordinates defined by the equations. Sleep for 60 ms in be-tween each call to print board. Name this ball-throw.cpp [-5]. For a little extra challenge [+10], throwthe ball back and forth indefinitely until the program is killed.

    134

  • APPENDIX A. PROBLEM SETS A.4. PROBLEM SET 4

    [20] Loops, Functions L. 2 Application (Chemistry). Solve for pressure of one mole of gas under multiplepossible volumes and temperatures as dictated by the ideal gas law :

    P (V, T ) =RT

    V.

    Define functions

    float pressure (float volume, float temperature);void pressures(float v1, float v2, float vstep,

    float t1, float t2, float tstep);

    where the body of pressure is 1 line, and the body of pressures is 15 lines (a double-for). Also definea macro for R as 8.314. To test the program, in main call

    pressures(1, 2, .2, 1, 2, .25);

    Name this ideal-gas.cpp [-5]. To get more use out of it [+10], create the corresponding functions fortemperature and volume.

    [20] Loops, Strings L. 2 Application (Biology). In the body of a main function which is 15 lines or less,perform RNA transcription on a user-supplied string of RNA nucleotides. Give a prompt > , then allow theuser to enter a string. Output the DNA transcribed form after a < .

    > UCGACAUGU< AGCTGTACA

    Loop over the string and make the transcriptions: U A, G C, C G, A T . If the string containsany letters other than U, C, G, or A, then output an error message that says X is not a nucleotide. andexit with status code 1. Name this transcribe-rna.cpp [-5].

    To get more use out of it [+20], copy each three-letter sequences into a codon array and look up the codonin the file dna-codons.dat to get the amino acid that it codes for, then output it. Output for the abovelooks like:

    AGC SerTGT CysACA Thr

    135

  • A.4. PROBLEM SET 4 APPENDIX A. PROBLEM SETS

    [20] Selection Structures, Arrays (Psychology). Write a program which gives a condensed Myers-Briggstest to guess the users Myers-Briggs type. At startup, print out:

    On a scale of 1-7: 1 (strongly disagree), 2 (disagree), 3 (slightly

    disagree), 4 (neutral), 5 (slightly agree), 6 (agree), 7 (strongly agree), rate

    the extent to which you agree/disagree with the following statements:

    Then ask the following 8 questions, and store the answers into a size-8 integer array or answer vector ~a:

    1). I like to meet new people.

    2). I prefer the tangible and like specific details.

    3). I make decisions through detached, rational and logical thought.

    4). I prefer to have things settled as opposed to open-ended.

    5). I like to reflect on my thoughts and ideas.

    6). I prefer the abstract and love to generalize patterns.

    7). I make decisions by getting a feel for the situation.

    8). I prefer to be spontaneous and keep my decisions open.

    Where indexing starts at 1, use the following logic to determine the typology from the response set:

    If a1 + (8 a5) > 8, output E, else if a1 + (8 a5) < 8, output I, else output X.

    If a2 + (8 a6) > 8, output S, else if a2 + (8 a6) < 8, output N, else output X.

    If a3 + (8 a7) > 8, output T, else if a3 + (8 a7) < 8, output F, else output X.

    If a4 + (8 a8) > 8, output J, else if a4 + (8 a8) < 8, output P, else output X.

    Example output: You are an INTJ! or You are an ESXP!. Name this program myers-briggs.cpp [-5].For some more fun [+20], transcript the resulting string to its opposite counterpart, e.g. for the above, Theopposite is an ESFP! or The opposite is an INXJ!. For yet more fun [+20], log all the raw numericresponses entered into a file called myers-briggs.dat for your later perusal. Each line should have 8space-delimited entries.

    [20] Selection Structures, Loops L. 2 Application (Electrical Engineering, Philosophy). Where the bodyof your main function is 15 lines or less, show that De Morgans laws

    1. (p q) p q2. (p q) p q

    are true by exhausting combinations of p, q with double-for loops to obtain the truth tables for them.Output should be like the following:

    1.) p:0, q:0 : 1p:0, q:1 : 1p:1, q:0 : 1p:1, q:1 : 1

    2.) p:0, q:0 : 1...

    You will need to declare p and q as integers to loop them over [0, 1]. Name this de-morgan.cpp [-5].(Once you have the solution, you will be able to obtain truth tables for other boolean expressions by editingthe conditionals. ;) If you want more practice [+10], generate similar truth tables for modus ponens(p q, p ` q) and modus tollens (p q,q ` p).

    136

  • APPENDIX A. PROBLEM SETS A.4. PROBLEM SET 4

    [30] Matrices L. 3 Application (Art). Write an ASCII-based font. Here is an example:

    _ ____ ___ ____ ____/_ / /___ / / // / ____/ /___ _/_ _/__

    You can write any such font you wish. To do so, initialize a 26xX matrix to contain strings like the following:

    {" ___"," / ","/___ ",},

    Write a function to print a string vertically given the string and your matrix. Name this ascii-font.cpp[-5]. To get the best use out of it [+30], also write a function that prints any alphabetic string in your fonthorizontally, as depicted above.

    [25] Boolean Logic, Library Functions L. 3 Application (Computer Science). Write a program to deala poker hand. It should deal 5 cards from a deck of 52, and should not deal the same card twice. Outputshould look like:

    5 of heartsJ of spades

    10 of diamonds2 of clubs3 of hearts

    It should support jacks (J), queens (Q), kings (K), and aces (A). Name this poker-dealer.cpp [-5]. For achallenge [+20], allow the use of only one unsigned long long integer variable throughout the whole program;represent the dealt cards using bitwise operators and powers of 2.

    137

  • A.4. PROBLEM SET 4 APPENDIX A. PROBLEM SETS

    [40] Loops, Libraries, Arrays L. 4 Application (Music, Language, Computer Science). Using code andideas from the library libsound, write a program which generates a song from a string of characters (a wordor sentence) [40]. Write a function void play string(string str) which plays each character in the stringfor some duration d of your choosing. Map the characters [a-z] and [A-Z] to an n of 1-52, where n is thenumber of semitones above A4. Also, let a space be a rest for d. Test it in main with two words that rhymeand contain similar letters [5]. Name this play-words.cpp [-5].

    For some extra fun [+20], put void play string(string str) into libsound and then write an in-terpreter for it that supports both functions void play(string note, float duration) and voidplay string(string str) so that you can play whatever you want to file.

    [60] Matrices L. 4 Application (Earth science). As a general rule, rainfall drains from higher-elevationareas to lower-elevation areas. Given elevation data, one could obtain a vector field of directional flowof rainwater on the Earths surface at the start of a rainshower. Your task is to obtain the vector field ofrainwater drainage on dry land for the city of Baton Rouge.

    You are given a data file baton-rouge.dat containing fields longitude, latitude, elevation, or , , r; or,when approximated as a uniform grid, x, y, z. The xy component grid is NxN . For any point (xi, yi, zi) onthe grid, first calculate the differences zizj for all four points zj in the von Neumann Neighborhood ofzi; then let the directional vector vi be the direction given by the maximum difference. If all the differencesare negative, then the point at i is a sink ; that is, water drains to this point and cannot runoff because thereis no lower-elevation area in the neighborhood.

    Let any vi be indicated by an ASCII symbol corresponding to its direction (> < ^ v). If i is a sink point,indicate it with an asterisk (*). Load these into a matrix of type char and print them to stdout. Name thisprogram rainfall.cpp [-5].

    138

  • APPENDIX A. PROBLEM SETS A.4. PROBLEM SET 4

    [80] Matrices (Physics). L. 5 Application Modify ball-bounce.cpp to populate the board with multipleballs, and detect and handle any collisions between two balls when they occur.

    Initially, for each point aij on the board, a ball will be spawned with .1 probability, for an average of 10%density. The x and y momenta will range from [-1, 1] (thus it is possible for a ball to begin stationary).

    For each iteration in the evolution of the board, for each position aij , if aij contains a ball, check its directionand find the cell b it will be in at the next iteration. If there is a ball in b which is stationary, then on thenext iteration aij will halt and b will inherit the momentum of aij . If b does not contain a stationary ball,but one moving opposite to aij , they will both halt upon the next iteration and swap momenta.

    Otherwise, check the Moore neighborhood of b to see if any other ball exists such that its direction lands itin b on the next iteration. If such a ball does exist, a and b collide.

    Upon a collision, the law of conservation of momentum determines the new momenta of the two balls. Thatis, the x and ycomponent momenta must be preserved. Note that you only need to handle collisions oftwo balls; if more than two balls would collide on the next iteration, handle the collision case for the firstone you detect.

    139

  • A.4. PROBLEM SET 4 APPENDIX A. PROBLEM SETS

    140

  • Appendix B

    Self-Tests

    ContentsB.1 Chapter 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143

    B.2 Chapter 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144

    B.3 Chapter 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149

    B.4 Chapter 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152

    B.5 Chapter 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159

    B.6 Chapter 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162

    B.7 Chapter 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164

    B.8 Chapter 11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167

    B.9 Chapter 12 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168

    B.10 Pre-Test 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170

    B.11 Test 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175

    B.12 Pre-Final . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185

    B.13 Final . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187

    141

  • APPENDIX B. SELF-TESTS

    142

  • APPENDIX B. SELF-TESTS B.1. CHAPTER 1

    B.1 Chapter 1

    [10] Binary Conversion: L. 1 Application (Computer Science) Convert 101010102 to decimal.

    [12] Binary Addition: L. 1 Application (Computer Science, Electrical Engineering). Compute 001111102+ 000111102. Report the answer in binary and decimal.

    143

  • B.2. CHAPTER 2 APPENDIX B. SELF-TESTS

    B.2 Chapter 2

    [10] Hello, world!: L. 1 Knowledge (Computer Science). Fill in the following 5-line skeleton [5x2]. Eachunderscore corresponds to exactly one character (there is exactly one correct solution). The program shouldprint out the string Hello, World! followed by a newline, then return a success exit code.

    Code B.2-1: Hello World

    1 #_______ __________

    2 _____ _________ ____

    3

    4 ___ ______ {

    5 ____ __ _Hello , World!_ __ ____;

    6 ______ __

    7 }

    [12] Variables and Expressions: L. 1 Knowledge, L. 1 Comprehension (Computer Science). Define thefollowing terms: variable, declare, initialize, assign [4x2]. Using the words variable, declared , initialized ,and assigned , fill in the blanks for the following [4x1]:

    A can be but not , then later a value.

    144

  • APPENDIX B. SELF-TESTS B.2. CHAPTER 2

    [11] Variables and Expressions: L. 1 Knowledge, L. 1 Comprehension (Computer Science). Define thefollowing terms: operator , increment , decrement , and expression [4x2]. Using the words operator , expression,increment , and fill in the blanks for the following two sentences [3x1]:

    The cannot be applied to an , but it can be applied to a variable.

    [11] Variables and Expressions: L. 1 Knowledge, L. 1 Comprehension (Computer Science). Define thefollowing terms: operator , increment , decrement , and expression [4x2]. Using the words operator , expression,increment , and decrement , fill in the blanks for the following two sentences [3x1]:

    If I start with 0 then and I end up with 0.A binary arithmetic on two variables forms an .

    145

  • B.2. CHAPTER 2 APPENDIX B. SELF-TESTS

    [10] Debugging: L. 2 Comprehension (Computer Science). The following main method block has one syntaxerror per line (except the return statement). Fix each bug, giving the correct code to the right-hand side[10=5x2].

    Code B.2-2: Debugging

    1 #include 2 using namespace std;3

    4 int main() {5 cout >> "Enter a number: ";6 cin

  • APPENDIX B. SELF-TESTS B.2. CHAPTER 2

    [10] Boolean Operators, Boolean Logic: L. 2 Comprehension (Philosophy). Print the program output[8=4x2]. Mind the formatting [2].

    Code B.2-4: Boolean Expressions

    1 #include 2 using namespace std;3

    4 int main() {5 int p = 0, q = 0;6 cout

  • B.2. CHAPTER 2 APPENDIX B. SELF-TESTS

    [12] Bitwise Operations: L. 2 Application (Electrical Engineering). Compute 85 170 & 1. Convert eachnumber to binary [6], then perform the two bitwise operations [4] and convert back to decimal [2].

    [12] Bitwise Operations: L. 2 Analysis (Electrical Engineering). Suppose I compute a b & c. If c is01010101, how many possible combinations of a b & c are there?

    148

  • APPENDIX B. SELF-TESTS B.3. CHAPTER 3

    B.3 Chapter 3

    [8] If-Elseif : L. 1 Comprehension (Biology). Print the output for of this DNA-to-RNA transcriptor forinput cases C,A, T,G [4x2].

    Code B.3-6: If

    1 #include 2 using namespace std;3

    4 int main() {5 char a;6 cin >> a;7 if (a == A) cout b;7 if (b == 2*a + 2) cout

  • B.3. CHAPTER 3 APPENDIX B. SELF-TESTS

    [10] Switch: L. 2 Comprehension (Computer Science, Mathematics). What happens when I put in a valuesof 1, 2, 3, 4?

    Code B.3-8: Switch

    1 #include

    2 using namespace std;

    3

    4 int main() {

    5 int a;

    6 cin >> a;

    7 switch (a) {

    8 case 1: a = a; break;

    9 case 2: a = -a/2; break;

    10 case 3: a = a/2; break;

    11 default : a = -a/4; break;

    12 }

    13 return 0;

    14 }

    [10] If : L. 2 Comprehension (Psychology). The following toy code accepts an (integer) number (a Likertscale response of 1-7) and prints out emoticons based upon the response. What is printed when the responseis 1, 2, 3, 4, 5, 6, 7 [7]? What about 8 [2]? Is it possible to enter an integer that yields no output [1]?

    Code B.3-9: If-Elseif-Else

    1 #include 2 using namespace std;34 int main() {5 cout response;9 if (response > 6) cout 5) cout 4) cout

  • APPENDIX B. SELF-TESTS B.3. CHAPTER 3

    [10] If-Else, Boolean Logic: L. 3 Comprehension (Electrical Engineering). If 1, 0, 1 are put in, whatis output [3]? If the output is 1010, what values of a, b, and c must have been put in [4]? Identify oneimpossible 4-digit binary output [3].

    Code B.3-10: If-Else; Boolean Logic

    1 #include

    2 using namespace std;

    3

    4 int main() {

    5 bool a, b, c;

    6 cout > a;

    7 cout > b;

    8 cout > c;

    9 if (a && b) cout

  • B.4. CHAPTER 4 APPENDIX B. SELF-TESTS

    B.4 Chapter 4

    [9] For: L. 1 Knowledge