Docsity

Learning Computer Programming using examples, Slides of Computer Science

Partial preview of the text

Download Learning Computer Programming using examples and more Slides Computer Science in PDF only on Docsity!

Learning Computer

Programming using

with

Examples

JAVA

Atiwong Suchato

Mr Oddo

X

XI

XIII

Figure 115: A program coded to run five iterations of statements using a while loop ............................................................................................... Figure 116: A program that keeps prompting for input .......................... Figure 117: A program used to find the average of numbers.................. Figure 118: A guessing game program....................................................... Figure 119: A flowchart representing a for statement .............................. Figure 120: A program calculating the average of input data where the number of data point can be determined via keyboard ................... Figure 121: A program that finds prime factors of an input integer ...... Figure 122: A program calculating term values in a first-order recurrence relation .................................................................................................... Figure 123: Demonstration of using the break statement ........................ Figure 124: Demonstration of using the continue statement which allows the program to ignore statements in some certain iteration............ Figure 125: An example of nested loops in action .................................... Figure 126: Another example of nested loops in action ........................... Figure 127: A compilation error caused by that a variable being declared inside a for loop is used outside .......................................................... Figure 128: Another example of error caused by a variable’s scope ...... Figure 129: A program finding all possible solutions to a 2 +b^2 +c^2 =200 .. Figure 130: Two vectors in the Cartesian coordinate................................ Figure 131: A flowchart showing various subroutines used in the VectorAngle program ........................................................................... Figure 132: A program finding the angle between two vectors.............. Figure 133: Compilation error due to usage of a variable declared inside a method outside the method .............................................................. Figure 134: Illustration of variables when f() is invoked(Step1) ............. Figure 135: Illustration of variables when f() is invoked (Step2) ............ Figure 136: Illustration of variables when f() is invoked (Step3) ............ Figure 137: Illustration of variables when f() is invoked (Step4) ............ Figure 138: A program demonstrating variable name re-use.................. Figure 139: A program that swaps values of two variables..................... Figure 140: An incorrect implementation of a method that swaps values of its two input argument..................................................................... Figure 141: A program demonstrating method overloading .................. Figure 142: A program demonstrating method overloading including a case where the input argument list is not entirely matched with any overloaded methods..............................................................................

XIV

Figure 157: An example of performing the selection sort on an array.

XVII

List of Tables

Table 1: Values of 2 n^ ........................................................................................ Table 2: Powers of two and their abbreviation............................................ Table 3: Escape sequences .............................................................................. Table 4: Primitive data types in Java............................................................. Table 5: Some examples of characters with their corresponding unicode encodings .................................................................................................. Table 6: Description of logic operators ......................................................... Table 7: Precedence and associativity of some basic operators................. Table 8: Data type conversion table .............................................................. Table 9: Data types from expression evaluation ......................................... Table 10: FunnyEncoder encoding scheme................................................ Table 11: Examples of real-world objects together with their attributes and behaviors ......................................................................................... Table 12: Summary of access levels (packages are ignored)....................

XIX

  • Chapter 1: Introduction to Computer Systems Table of Contents
    • Hello Computer, my dear friend!................................................................
    • Computers in Our Lives ...............................................................................
    • What Computers do ......................................................................................
    • Hardware........................................................................................................
      • Central Processing Unit................................................................................
      • Memory ........................................................................................................
      • I/O Devices...................................................................................................
    • Software ..........................................................................................................
      • Application Software Vs. System Software ...............................................
      • Operating System (OS)...............................................................................
    • Binary Representation of Data...................................................................
    • The Power of Two .......................................................................................
    • Units of Measure..........................................................................................
    • Problem Solving Using Computer Program............................................
      • Exercise ......................................................................................................
  • Chapter 2: Programming Concepts .............................................
    • Programming Languages ...........................................................................
    • Running a Java Program.............................................................................
    • Typical Programming Cycle ......................................................................
    • Preparing Java Computing Environment ................................................
      • Getting the required software .....................................................................
      • Letting Your OS Know Where to Find Java...............................................
    • Compiling and Running Java Programs ..................................................
    • Integrated Development Environment (IDE) ..........................................
    • Basic Program Structure in Java ................................................................
    • Syntax, Keywords, and Identifiers ............................................................
    • Comments.....................................................................................................
    • Be Neat and Organized...............................................................................
    • A First Look at Methods .............................................................................
    • Escape Sequences.........................................................................................
    • Variable at a Glance.....................................................................................
    • Naming Rules and Styles............................................................................
    • Statements and Expressions.......................................................................
    • Simple Calculation....................................................................................... IV
    • Representing Algorithms Using Flowcharts............................................
    • Manual Input................................................................................................
    • Decisions and Iterations..............................................................................
    • Subroutines...................................................................................................
    • More Shapes .................................................................................................
      • Exercise ......................................................................................................
  • Chapter 3: Working with Data
    • Strong Data Typing .....................................................................................
    • Data Types in Java .......................................................................................
    • Primitive Data Type for Integers ...............................................................
    • Primitive Types for Floating-Point Values...............................................
    • Primitive Type for Characters....................................................................
    • Primitive Type for Logical Values.............................................................
    • String .............................................................................................................
    • Pointers..........................................................................................................
    • Assigning Data to Variables .......................................................................
    • Final Variables..............................................................................................
    • Un-initialized Variables ..............................................................................
    • Operators ......................................................................................................
    • String and the addition operator (+) .........................................................
    • Math methods ..............................................................................................
    • Precedence and Associativity.....................................................................
      • Exercise ......................................................................................................
  • Chapter 4: More Issues on Data Manipulation
    • Numeric Data Type Specification..............................................................
    • Data Type Conversion ................................................................................
    • Automatic Type Conversion and Explicit Type Casting........................
    • Expressions with Multiple Data Types.....................................................
    • Limitation on Floating Point Computation..............................................
    • An Issue on Floating Point Value Comparison .......................................
    • Overflow and Underflow ...........................................................................
    • Numbers Divided by Zero .........................................................................
    • Compound Assignment..............................................................................
    • Increment and Decrement ..........................................................................
      • Exercise ......................................................................................................
  • Chapter 5: Using Objects .......................................................... V
    • Classes and Objects ...................................................................................
    • Using Data and Methods provided in Classes ......................................
    • Useful String methods ..............................................................................
      • charAt() ....................................................................................................
      • length() .....................................................................................................
      • concat().....................................................................................................
      • indexOf() ..................................................................................................
      • lastIndexOf() ............................................................................................
      • startsWith()...............................................................................................
      • endsWith() ................................................................................................
      • trim().........................................................................................................
      • substring().................................................................................................
      • toLowerCase() ..........................................................................................
      • toUpperCase() ..........................................................................................
      • valueOf() ..................................................................................................
    • Reading Input String from Keyboards ...................................................
    • Converting Strings to numbers................................................................
      • parseInt() ..................................................................................................
      • parseDouble() ...........................................................................................
    • Useful Methods and Values in Class Integer and Class Double.........
    • Reading Formatted Input using Scanner ...............................................
      • next() ........................................................................................................
      • nextBoolean() ...........................................................................................
      • nextByte().................................................................................................
      • nextDouble().............................................................................................
      • nextFloat() ................................................................................................
      • nextInt() ....................................................................................................
      • nextLong() ................................................................................................
      • nextShort()................................................................................................
      • Exercise ....................................................................................................
  • Chapter 6: Decisions .................................................................
    • Controlling the Flow of Your Program...................................................
    • ‘If’ Construct...............................................................................................
    • ‘If-else’ Construct.......................................................................................
    • Nested If......................................................................................................
    • ‘If-else-if’ Construct...................................................................................
    • Use Braces to Avoid Coding Confusions ...............................................
    • The? : Operator .........................................................................................
    • Equality Testing for Values of Primitive Data Types ........................... VI
    • Safe Ways to Compare Floating Point Values .......................................
    • Equality Testing for Non-Primitive Data Types....................................
    • String Equality Testing..............................................................................
      • compareTo() .............................................................................................
    • ‘Switch’ Constructs ....................................................................................
    • Common Instructions for Multiple Cases ..............................................
      • Exercise ....................................................................................................
  • Chapter 7: Iterations .................................................................
    • Repetitive Execution..................................................................................
    • ‘do-while’ Statement..................................................................................
    • ‘while’ statement........................................................................................
    • ‘for’ statement.............................................................................................
    • ‘break’ and ‘continue’................................................................................
    • Nested Loops..............................................................................................
    • Scope of Variables......................................................................................
      • Exercise ....................................................................................................
  • Chapter 8: Methods ...................................................................
    • Methods.......................................................................................................
    • Using a Method..........................................................................................
    • Defining a Method.....................................................................................
    • Multiple Return Statements......................................................................
    • Local Variables ...........................................................................................
    • Method Invocation Mechanism ...............................................................
    • Passing by Value Vs. Passing by Reference ...........................................
    • Method Overloading .................................................................................
      • Exercise ....................................................................................................
  • Chapter 9: Arrays ......................................................................
    • Requirement for a List of Values .............................................................
    • One-dimensional Array ............................................................................
    • Accessing Array Elements........................................................................
    • Explicit Initialization .................................................................................
    • Array Variable Assignment......................................................................
    • Array Utilities.............................................................................................
    • Arrays and Methods..................................................................................
      • Passing an array to a method ....................................................................
        • Returning an array .................................................................................... VII
    • ‘String [ ] args’ Demystified .....................................................................
    • Sequential Search.......................................................................................
    • Selection Sort ..............................................................................................
    • Multi-dimensional Arrays........................................................................
    • Initializer Lists for Multi-dimensional Arrays....................................... - Exercise ....................................................................................................
  • Chapter 10: Recursive Problem Solving.....................................
    • Recursive Problem Solving ......................................................................
    • Recursive Method Design ........................................................................
    • Costs of Recursion .....................................................................................
    • Reducing Numbers of Method Calls ...................................................... - Exercise ....................................................................................................
  • Chapter 11: Creating Classes ....................................................
    • Defining Your Own Data Type................................................................
    • Java Programs and Java Classes ..............................................................
    • Components of Class Definitions ............................................................
    • Diagram for Class Descriptions...............................................................
    • Instance Variables and their Access Levels............................................
    • Object Composition...................................................................................
    • Static and Non-static Data Members ......................................................
    • Methods ......................................................................................................
      • ...................................................................................................................... Discriminating data Members and Variables Declared inside Methods
    • Accessor and Mutator Methods..............................................................
    • toString() .....................................................................................................
    • Putting main() into Class Definitions .....................................................
    • Constructors ...............................................................................................
    • Overloading Constructors........................................................................ - No-argument Constructor ......................................................................... - Detailed Constructor................................................................................. - Copy Constructor......................................................................................
    • Calling a Constructor from Other Constructors.................................... - Exercise ....................................................................................................
  • Chapter 12: Inheritance.............................................................
    • Inheritance: Creating Subclasses from Superclasses.............................
    • Designing Class Inheritance Hierarchy .................................................. VIII
    • Access Levels and Subclasses...................................................................
    • Keyword ‘super’ ........................................................................................
    • Polymorphism............................................................................................
    • Method Overriding....................................................................................
    • Instance Creation Mechanism..................................................................
      • Exercise ....................................................................................................
  • What are the Next Steps? ..........................................................
  • References................................................................................
  • Index .........................................................................................
    • and process termination.......................................................................... Figure 27: Symbols in a flowchart used for regular actions, starting points
  • Figure 28: The flowchart of the AverageDemo program ..............................
  • Figure 29: Symbol used in a flowchart for manual input...........................
    • manually input via keyboard................................................................. Figure 30: The flowchart of a program greeting a person whose name is
  • Figure 31: Symbol used in a flowchart for decisions ..................................
    • manually input integer value................................................................. Figure 32: Flowchart of program calculating the absolute value of a
    • input integer value................................................................................... Figure 33: Flowchart of program calculating the factorial of a manually-
  • Figure 34: Symbols used in a flowchart for a subroutine...........................
  • Figure 35: Flowchart of a program calculating a combinatorial function
  • Figure 36: Some of other symbols used in a flowchart ...............................
    • manually-input values ............................................................................ Figure 37: Flowchart of a program finding the biggest of the three
  • Figure 38: A recipe for shrimp scampi bake ................................................
  • Figure 39: Storing values into variables........................................................
  • Figure 40: Reassigning a String variable.......................................................
  • Figure 41: Various variable declaration and assignment examples..........
  • Figure 42: Invalid variable declarations and assignments .........................
  • Figure 43: Redundantly declaring variables ................................................
  • Figure 44: Assigning a new value to a final variable ..................................
  • Figure 45: Using an uninitialized variable ...................................................
  • Figure 46: Operating on int variables............................................................
  • Figure 47: Operating on boolean variables...................................................
  • Figure 48: String concatenation with + operator .........................................
  • Figure 49: Using + operators with String and other data types ................
  • Figure 50: Using + operators with String and other data types ................
  • Figure 51: Order of operations in evaluating 4*2+20/4..............................
  • Figure 52: Order of operations in evaluating 2+2==6-2+0 .........................
  • Figure 53: Order of operations in evaluating (x=3)==(x=+1-2)&&true....
  • Figure 54: The source code of the Distance3d program .............................
  • Figure 55: The output of the Distance3d program ......................................
  • Figure 56: A program demonstrating data type conversion......................
  • Figure 57: Another program demonstrating data type conversion ..........
    • multiple data types .................................................................................. Figure 58: A Java program showing expressions with operands being of
    • floating-point calculation using computers ......................................... Figure 59: A demonstration of the fact that precisions are limited in the
  • Figure 60: Demonstration of several occurrences of overflow for int .....
  • Figure 61: A Java program that results in the double-valued Infinity .....
  • Figure 62: A demonstration of cases when underflow occurs .................. - .................................................................................................................... Figure 63: A Java program that produces the divided-by-zero exception
    • valued Infinity, -Infinity and NaN ........................................................ Figure 64: A Java program with expressions evaluated to the double-
    • when numbers are divided by zeros..................................................... Figure 65: Compilation errors due to data type mismatch in the cases
    • prefix and the postfix versions of the increment operator................. Figure 66: A Java program demonstrating the difference between the
  • Figure 67: A classroom with 17 desks and 16 chairs.................................
  • Figure 68: Declaration and assignment of a String object ........................
  • Figure 69: An abstract representation of the details of a class.................
    • involving in System.out.print() and System.out.println()................ Figure 70: An abstract representation classes, objects, and methods
  • Figure 71: A program calculating the area of a circle ...............................
  • Figure 72: Demonstration of using charAt() and length()........................
  • Figure 73: Demonstration of using concat()...............................................
  • Figure 74: Demonstration of using indexOf()............................................
  • Figure 75: Demonstration of using lastIndexOf()......................................
  • Figure 76: Finding Strings in another String..............................................
  • Figure 77: Demonstration of using lastIndexOf()...................................... - .................................................................................................................. Figure 78: Demonstration of using trim(), startsWith(), and endsWith()
    • position of characters in String objects as well as toUppercase().... Figure 79: Demonstration of using substring() with methods that find the
  • Figure 80: A program that reads two String inputs from the keyboard
  • Figure 81: A program that reads two String inputs from the keyboard
  • Figure 82: A program that reads two String inputs from the keyboard
  • Figure 83: The code listing of the FunnyEncoder program .....................
  • Figure 84: An output of the FunnyEncoder program...............................
  • Figure 85: Decomposition of a vector F into Fx and Fy............................
  • Figure 86: A program decomposing a force vector...................................
  • Figure 87: The default pattern used by a Scanner object..........................
  • Figure 88: Using Scanner to read String objects ........................................
  • Figure 143: Compilation error due to unmatched overloaded methods
    • and assigned with an array .................................................................. Figure 144: Illustration of memory allocation when a variable is declared
  • Figure 145: Illustration of accessing an array element..............................
  • Figure 146: Demonstration of how array elements are accessed.............
  • Figure 147: An improved version of a program counting digits.............
  • Figure 148: Illustration of some usage of initializer lists ..........................
  • Figure 149: Assigning a new array to a variable .......................................
  • Figure 150: Assigning an array variable to another array variable.........
  • Figure 151: Passing arrays as input to methods ........................................
  • Figure 152: Generating an array with random integers ........................... - .................................................................................................................. Figure 153: Finding the minimum and the maximum values in an array - .................................................................................................................. Figure 154: A program summing numbers read from the command line
  • Figure 155: The sequential search algorithm..............................................
  • Figure 156: Demonstration of the sequential search .................................
    • shaded. .................................................................................................... Each traversal only traverses the portion of the array that is not
  • Figure 158: A program utilizing the selection sort to sort its inputs ......
  • Figure 159: An array of arrays of int ...........................................................
  • Figure 160: A three dimensional array of boolean ....................................
  • Figure 161: Some outputs of a program finding powers of matrices .....
  • Figure 162: Finding s(n)=s(n-1)+n where n=3 recursively .......................
  • Figure 163: Finding 4! recursively ...............................................................
  • Figure 164: How variables change when the loop keeps iterating .........
  • Figure 165: Finding Fibonacci numbers......................................................
  • Figure 166: Recursively invoking methods to find fibo(4).......................
  • Figure 167: Comparison of invoking fibo() and fiboNew()......................
  • Figure 168: The initial setting of the towers of Hanoi puzzle..................
  • Figure 169: Solutions to the Towers of Hanoi puzzle ...............................
  • Figure 170: A class diagram .........................................................................
  • Figure 171: A diagram describing three objects.........................................
  • Figure 172: Accessing values of public instance variables .......................
    • private instance variables from outside if their class definition...... Figure 173: Compilation errors due to attempts in accessing values of
  • Figure 174: A Polygon instance....................................................................
  • Example 1: How large is a giga byte? ........................................................... List of Examples
  • Example 2: Memory card capacity ................................................................
  • Example 3: An electrical resistive circuit problem......................................
  • Example 4: Trivial printing samples .............................................................
  • Example 5: Tabulated output.........................................................................
  • Example 6: Simple calculation and adaptation ...........................................
  • Example 7: An algorithm to find absolute values.......................................
  • Example 8: Factorial function algorithm ......................................................
  • Example 9: Combination function algorithm ..............................................
  • Example 10: An algorithm for finding the biggest of three inputs ...........
  • Example 11: Using + to concatenate multiple strings together .................
  • Example 12: Mathematic methods ................................................................
  • Example 13: Applying rules on precedence and associativity (1).............
  • Example 14: Applying rules on precedence and associativity (2).............
  • Example 15: Applying rules on precedence and associativity (3).............
  • Example 16: Applying rules on precedence and associativity (4).............
  • Example 17: Distance in 3-D space................................................................
  • Example 18: Data type conversion ................................................................
  • Example 19: Resulting data type of an expression......................................
  • Example 20: Oops! They are too big..............................................................
  • Example 21: Once an infinity, always an infinity........................................
  • Example 22: Too close to zero ........................................................................
  • Example 23: Dividing by zeros: Types matter.............................................
  • Example 24: An ‘infinity’ has its data type ..................................................
  • Example 25: Prefix-postfix frenzy .................................................................
  • Example 26: Area of a circle .........................................................................
  • Example 27: Demonstration of String methods (1) ...................................
  • Example 28: Demonstration of String methods (2) ...................................
  • Example 29: Demonstration of String methods (3) ...................................
  • Example 30: Demonstration of String methods (4) ...................................
  • Example 31: Demonstration of String methods (5) ...................................
  • Example 32: Demonstration of String methods (6) ...................................
  • Example 33: Greeting the users by their names ........................................
  • Example 34: Showing the binary representation of the input number ..
  • Example 35: Selective substrings.................................................................
  • Example 36: Funny encoder ......................................................................... XX
  • Example 37: Vector decomposition .............................................................
  • Example 38: Reading one String at a time using Scanner ........................
  • Example 39: Reading formatted data input ...............................................
  • Example 40: Implementing an absolute value finder ...............................
  • Example 41: Ad-hoc sorting of three inputs...............................................
  • Example 42: The bigger number ..................................................................
  • Example 43: Functions of x...........................................................................
  • Example 44: Nested conditions....................................................................
  • Example 45: If neither one is bigger, they are equal .................................
  • Example 46: Funny encoder revisited.........................................................
    • expression) .............................................................................................. Example 47: The absolute value (again! but with short-handed
  • Example 48: Equality testing ........................................................................
  • Example 49: Floating-point value comparison ..........................................
  • Example 50: Comparing Strings with compareTo()..................................
  • Example 51: Printing Stars............................................................................
  • Example 52: Number base converter ..........................................................
  • Example 53: Basic loops with while and do-while....................................
  • Example 54: q for quit ...................................................................................
  • Example 55: Guessing a number .................................................................
  • Example 56: Averaging input numbers ......................................................
  • Example 57: Prime factors ............................................................................
  • Example 58: Recurrence relations................................................................
  • Example 59: The magic word .......................................................................
  • Example 60: The biggest digit in an alphanumeric String input.............
  • Example 61: Nested loops.............................................................................
  • Example 62: Variable scope ..........................................................................
  • Example 63: All solutions to a 2 +b^2 +c^2 =200.................................................
  • Example 64: Introducing methods ..............................................................
  • Example 65: Angle between two vectors....................................................
  • Example 66: Method’s local variables .........................................................
  • Example 67: Parameter passing and returning values .............................
  • Example 68: Different variables with the same identifiers.......................
  • Example 69: Value swapping .......................................................................
  • Example 70: Overloaded number adding ..................................................
  • Example 71: How overloaded methods are selected ................................
  • Example 72: Accessing array elements .......................................................
  • Example 73: Improved digit frequency counting...................................... XXI
  • Example 74: Passing arrays to methods .....................................................
  • Example 75: Generating an array with random elements........................
  • Example 76: Finding the maximum and the minimum array elements
  • Example 77: Command line summation utility.........................................
  • Example 78: Sequential search.....................................................................
  • Example 79: Selection sort ............................................................................
  • Example 80: Lengths of multi-dimensional arrays ...................................
  • Example 81: The n th power of a matrix.......................................................
  • Example 82: Positive integer summation ...................................................
  • Example 83: Factorial function ....................................................................
  • Example 84: Iterative to recursive ...............................................................
  • Example 85: Fibonacci numbers ..................................................................
  • Example 86: Fibonacci numbers revisited..................................................
  • Example 87: The towers of Hanoi................................................................
  • Example 88: A blank class ............................................................................
  • Example 89: Points in the Cartesian coordinate ........................................
  • Example 90: Static vs. non-static data members........................................
  • Example 91: Accessor, mutator, toString() and other methods...............
  • Example 92: Utility class with only static methods...................................
  • Example 93: Executable class definition .....................................................
  • Example 94: Overloaded constructors........................................................
  • Example 95: Missing no-argument constructor.........................................
  • Example 96: Complex numbers ...................................................................
  • Example 97: Designing classes for a map and a maze..............................
  • Example 98: Using super ..............................................................................
  • Example 99: Overriding methods................................................................
  • Example 100: A book shop ...........................................................................
  • Example 101: Creation of inherited instances............................................

Chapter 1: Introduction to

Computer Systems

Objectives

Readers should  Be familiar with computer components and understand their main functionalities.  Conceptually understand how data are represented in computers.  Be able to conceptually explain how to solve problems using computers.

Hello Computer, my dear friend!

A computer is a machine capable of automatically processing data according to instruction lists given. Data processing includes, but not limited to, carrying out arithmetic operations, comparing logical values, as well as, transmitting, receiving and storing information. Data processing tasks, no matter how long or complex they are, can be performed with series of some simple commands, considered “native” to the computers processing those data.

From day one until now, the so-called “native” commands are done electronically in most computers. Many benefits we gain by using computers as our tools to problem solving are due to the fact that electronic devices can perform these commands in a very fast and reliable fashion. Here are some examples of such benefits in normal circumstances.

Computers work fast. Despite common complaints that sounds like “My computer is slow”, it does work very fast! A computer can execute billions commands in a second. Suppose we have golf balls that each of them can be either white or black, how fast can you compare the colors of one thousand pairs of golf balls and say how many pairs are different? A computer can do it in one nanosecond.