Introduction to Computer Science - ICS3U Grade 11 PDF

Summary

This document is an introduction to computer science, specifically covering the programming process and different types of computers and programming languages. It explores the concepts of compilers, interpreters, and virtual machines, and includes exercises to test understanding. This will include concepts of byte-code, binary instruction, source code and how to write simple Java examples.

Full Transcript

Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 Introduction - THE PROGRAMMING PROCESS Introduction.1 Compilers, Interpreters and all that Programming is at the heart of the functioning of computer systems. What makes a computer unique from other machines is that it...

Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 Introduction - THE PROGRAMMING PROCESS Introduction.1 Compilers, Interpreters and all that Programming is at the heart of the functioning of computer systems. What makes a computer unique from other machines is that it is programmable, that is, its internal state can be set to perform particular tasks based on an instruction set we call a program. Two types of computers rise out of programmable machines: General Purpose and Specific Purpose. General Purpose computers are machines that are fully programmable for an indefinite number of tasks. General Purpose programming languages such as Java, C, Pascal, Turing, are used with this end in mind. Desktop computers are General Purpose computers. Specific Purpose computers are pre-programmed computers with a specific goal. These machines have been optimized for speed and space and do not need to do more than perform the one needed task. Image processors, printers, cell phones, video game consoles, are examples of Specific Purpose computers. Specific Purpose languages are used for these machines. Examples of such languages are PostScript for printers, or DataCube for image processing. At the heart of programming instructions is binary code. All electronic computer systems ultimately work with instructions coded in binary. In the development of computer systems (1930‘s onward) all coding was initially done in binary, thereby making programming very difficult and tedious. Though computer systems are still designed to work with binary instructions, their evolution over time has allowed programmers to use instructions that are more meaningful to humans. These programs are written in languages that are English-like, making it possible to code very sophisticated and abstract problems and solutions. We call these programs the source code. A program written in source code needs to be translated into binary instructions before it can be run by a computer. This translation is done by yet another program. This other program comes in two flavours: Interpreter or compiler. The interpreter translates one instruction of the source code and immediately runs the translated instruction. Then the next instruction from source code is translated and run. This process continues until the 1 ⓒ 2015, 2016 Mario Portoraro, All Rights Reserved Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 end of the source code is reached. In contrast, the compiler translates the entire source code once and then the compiled program is run by the computer without any further aid from the compiler. The compiled program is known as the executable and it is made of binary code, also called machine code. It contains only ones and zeroes. The interpreter method requires that during the running process both the source code and the interpreter be present in the computer’s memory. With the compiler method, once the source code has been compiled, the resulting executable can be installed and run in any machine without the compiler being present. Programs such as Word, PowerPoint, Halo, Windows 7, and thousands of others are executables that have been compiled from source code. They have been written in languages such as C, C++, Java, Pascal, etc. but the manufacturers do not release the source code, only the executables. Introduction.1 Exercises 1. Why is a printer considered a Specific Purpose Computer? 2. In this section we learned the difference between an interpreter and a compiler. Research further on these two types of programs and write down a situation in which it would be more convenient to use an interpreter instead of a compiler. Then write a situation in which it would be more convenient to use a compiler instead of an interpreter. 3. Why do you think that companies that make software do not release their source code? 4. Research what is meant by Open Source 2 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 Introduction.2 From source code to binary code This example shows the standard programming process. Source code of a Turing program is shown here: The binary code that is generated from this process is specific to a particular computer processor. A compiler will generate binary code that will run, for example, on only Intel processors. If we wish to run a program in a different processor, say a Motorola, we need to compile our source code again using a compiler that will translate for a Motorola processor. Because of this, binary code is limited to a particular type processor. With the advent of the internet, programs need to run on computers for which we do not know the processor. This is because programs are sent over the internet lines and they need to run on the machine where they are being sent. There is no way of knowing in what type of computer a program may end up once it is sent over the net. This creates a big problem, but it was solved in the late 1990s with the invention of the Virtual Machine. 3 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 A Virtual Machine is a program that simulates a computer. In other words, with a Virtual Machine we can make a computer behave like a different computer. For example, we can make an Intel processor behave like a Motorola processor. In this way, if a program that has been compiled for an Intel processor needs to run on a Motorola processor, we use a Virtual Machine to make Motorola processor behave like an Intel processor and thus we are able to run our programs. This is how we can run Windows programs on a Mac. Software like Wine or VMFusion are examples of virtual machines. In particular they are Systems Virtual Machines (SVM) When we compile programs using Java, we are not generating binary code, but byte code. The byte code does not run directly on the computer but runs on top of the Java Virtual Machine (JVM). Any computer on the internet that is Java-enabled has a Java Virtual Machine installed, which means that byte code can run on that computer regardless of the type of processor. The JVM guarantees that the instructions contained in the byte code always work, no matter what computer is being used. The JVM allows our programs to run on computers without our knowing the type of processor those computers have. The JVM is an Application Based Virtual Machine (AVM). The following diagram shows the Java Programming Process. Java source code compiles to Byte Code which then runs on a virtual machine, and not directly on the processor of the computer. 4 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 The following visual analogy, as conceived by Alexander Mirabella, demonstrates how the same byte code interacts with JVMs that have been designed to work with three different computer processors1: - SVM2 1 Visual representation by Alexander Mirabella, 2016. Used with permission. 2 The SVM is present only if it has been deliberately installed for the purposes of simulating a processor 5 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 Introduction.2 Exercises 1. Define the following: a. Binary code b. Machine code c. Assembly code d. Byte code e. Source code 2. Define the following: a. Instruction set b. Virtual machine c. ALU d. RISC e. JVM 3. Why is it that programs compiled for an Intel processor cannot run on a different type of processor? 4. Put the following in order, from the furthest to the closest to machine code: Executable, Source Code, Compiler, JVM, Byte Code 5. What is a general purpose programming language? Give some examples 6 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 Introduction.3 Generations of Programming Languages Over the past eighty years of computer development, programming languages have gotten more and more sophisticated. These languages have been categorized in generations as follows: Generation Characteristics Uses Example First Low-level Machine code Binary code Controls hardware directly 1001 0001 1001 1101 Second Low-level Mnemonics Assembly language Controls hardware indirectly through machine MV 3, 10 code Third High-level and abstract English-like C, C++, Java, Turing, Can control hardware language Pascal, PL/1 through operating system General purpose printf("%d", 35); Fourth High-level and abstract English-like SQL (Structured Query Specific purpose language Language) Removed from hardware list all entries with mark > 72 Fifth High-level English-like PROLOG, Lisp Mathematical language General purpose Self-generating Conceptually based 7 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 1 - FUNDAMENTALS and Input/Output 1.1 The Fundamental Java Program The essential framework on which all Java programs are based is illustrated with this example we call MyFirstJavaProgram import hsa.*; public class MyFirstJavaProgram { public static void main(String[] args) { Stdout.println(“Hello World”); } } // End of program The import statement allows us to make use of predefined methods such as those for printing, inputting, etc. This statement will be explained fully a bit later, once we have some practice with programming. The public class MyFirstJavaProgram is a class declaration. Keywords are used, in this case public and class. These words are part of the Java language and they direct the compiler. They are not user defined. The identifier MyFirstJavaProgram gives a name to our class, and we use name conventions when choosing a name for a class. These are, The name of the class starts with upper case The name of the class contains no spaces The name of the class contains only alphanumeric characters For readability, if there is more than one word in the name of the class we capitalize the start of the new word For our program to compile successfully it is necessary to save the program with the very same name as the class followed by the extension.java. Our program file needs to have the name MyFirstJavaProgram.java 8 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 The main method of our program where execution always begins is identified by the heading public static void main(String[] args) Finally, braces {} are used to enclose code. Notice that for every opening brace there is a corresponding closing one. In our program, there is a set of opening and closing braces for the class MyFirstJavaProgram and there is also another set for the main method. The innermost opening braces always correspond with the innermost closing braces. At the very end we have an example of comments. These can be included anywhere in the program and start with two slashes as shown in the example. The compiler will completely ignore the words after the two slashes. The comments can span for one line of text, and they are meant for us to make our programs more readable. Another way of commenting is by using block comment delimiters. Any text inserted between is considered by the compiler as comments and will also be ignored. The following text will be bypassed by the compiler, The Stdout.println(“Hello World”); statement outputs the text Hello World to the output screen. We now spend some time with this statement in the next section. 1.1 Exercises 1. Create a folder within your Desktop and call it Java Programs. Use this folder to store all your programs. Do not store programs in the Java RTP folder. 2. Create and run the program above MyFirstJavaProgram 3. Modify the program above so that the class is named MySecondJavaProgram. Make sure it compiles and runs 9 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 4. Write a Java program that prints out your name, your address, city, province, and postal code. The program needs to print out each item in a separate line as if being printed on an envelope. Call this program MyInfo 5. Using these course notes and the internet, find definitions for these items and write a sentence about each of them in your own words: a) Program e) Compiler b) Programming Language f) Interpreter c) Editor d) Integrated Development Environment 1.2 Text and Number Output with Java Sending text to the screen is a fundamental programming operation. Before windowing systems were invented by Xerox and commercialized by Apple and Microsoft, all text was sent to the one screen which had only one window: The entire screen. The first windowing system was called Smalltalk and was created by the Xerox photocopying company in the 1960’s. Not many people paid attention to this system and it was archived for 10 years as nothing more than an interesting pilot project. When Steve Jobs visited Xerox in the late 1970‘s for a presentation of Smalltalk, he was absolutely amazed and quickly realized the potential of this system. He soon thereafter created the windowing system for the Apple MacIntosh in the early 1980's. Microsoft followed with Windows 1.0, though it was not until Windows 3.0 in 1990 that Microsoft started to seriously implement windowing systems. Java allows the programmer to send output to windows as needed. There are three different ways in which a programmer can do this. A programmer can send text output to any or all of the following: 1. The Standard Java Output window 2. The Standard Java Output window using import hsa.* 3. The programmer's own defined window also using import hsa.* 4. Any combination of the above 10 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 We now look at each of these separately 1.2.1 Printing to the Standard Output Window with System.out.print() and System.out.println() The System.out.print()and System.out.println() methods are used to output text, numbers, evaluated expressions, and concatenated expressions. Here is a summary with examples: System.out.print(“Hello”) prints the word Hello on the output screen. Any text enclosed in double quotes will be printed as is System.out.print(24)prints the number 24 on the output screen System.out.print(2 + 3 * 5) evaluates the expression in brackets and prints the result on the output screen. In this case 17 will be printed. Mathematical expressions follow BEDMAS System.out.print(5 / 2)evaluates the expression and prints the result. This is an example of integer division since both dividend and divisor are integers. The result is not rounded but truncated to 2 System.out.print(5.0 / 2)evaluates the expression an prints the result. This is an example of floating point division. It is enough that either dividend or divisor be a floating point that the result will also be a floating point. In this case 2.5 System.out.print(“Hello” + “ ” + “world.”) evaluates the expression and prints the result. This is called concatenation, where text is joined by means of the plus sign. The result printed is Hello world. System.out.print(“You are ” + (15 + 1) + “ years old”) evaluates the expression. Here numbers and text are mixed, something that, unlike Java, most languages do not allow. Java first evaluates the mathematical expression (15 + 1) to yield 16. Then Java converts the 16 to text and joins it with the rest of the expression. Notice that in a single statement the plus sign takes on two different meanings: Arithmetic addition and concatenation. The printed result is You are 16 years old 11 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 For every example given above we can replace System.out.print with System.out.println. The effect will be that a new line feed is printed System.out.println() prints a blank line 1.2.2 Printing to the Standard Output Window with Stdout.print() and Stdout.println() A second way to send text to the Standard Java Window is through the use of also print() and println() statements. These work in the same way as the ones explained above but contain a powerful feature: Formatting. This feature has been implemented in such a way that makes it easier on the programmer. For us to have access to these printing statements, we need to include the statement import hsa.*; before the header of our class. For example import hsa.*; public class NamesOfStudent { public static void main(String[] args) { <.... program code goes here.... > } } To perform actual printing, we can use the commands Stdout.print() and Stdout.println() in the same way that we use System.out.print() and System.out. println() In the small program above, we can now insert commands like: Stdout.print(“Hello”) prints the word Hello Stdout.print(24)prints the number 24 Stdout.print(2 + 3 * 5) evaluates to 17 and is printed 12 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 These commands offer simple yet powerful formatting as well. For example, Stdout.print(“My Java textbook”, 30) prints the words My Java Textbook on a left justified field of 30 spaces Stdout.print(“My Java textbook”, -30) prints the words My Java Textbook on a right justified field of 30 spaces Stdout.print(18 * 3, 6, 2) evaluates the expression and prints the result. The result is 54 but a formatting is specified: 6 spaces in total, including 2 decimal places. The command prints 54.00 right justified. Note that the decimal point takes one space. Stdout.print(2.5 / 7, 10, 6) prints 0.357143 right justified in a field of 10. The division of 2.5 by 7 has more than 6 decimal places. Java rounds the result before outputting it. 1.2.3 Printing to our own defined window with print() and println() The third way to send text to the screen is through the use of a window that we define ourselves. To do this, we need to include a statement in our program that creates the window. Once this is done, the window will be available for output and will become visible on the first output command. Here is the code to send the word Hello to our own defined window: import hsa.*; public class MyFirstOwnWindow { public static void main(String[] args) { Console c = new Console(); c.println("Hello"); } } We can now use the print() and println() commands in the same way as we did above for number formatting. For text, only left justification is done the same way as in Stdout. Text right justification is not possible with 13 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 a user defined window and we need to use other methods, such as tabs, to do this. To output to our own window, we always need to write the window and the printing command separated with a period. For example, if our window is called glass, our printing commands become, glass.println(100 * 2 - 1); glass.println(“hello, how are you”); glass.println(“The cat came back”); glass.println(“Your test mark is: “ + ((87 + 82 + 91) / 3.0)); 1.2 Exercises 1. Write a Java program with the class name MovieTicket that displays in the Standard Java Window the following information, exactly as shown here: ---------------------------- AMG Movie Theatres – Toronto July 15, 2015 8:05 pm Mr. Holmes, $12.25 Theatre 3 – Not reserved Payment method: Debit Card Amount paid : $12.25 Enjoy the show ---------------------------- 2. Write a Java program with the class name LetterE that displays in the Standard Java Window, but using Stdout, the following pattern, exactly as shown here: ********** ** ** ******* ** ** ********** 14 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 3. Write a Java program with the class name Triangle that displays in Standard Java Window, using Stdout, the following pattern, exactly as shown here: * * * * * * * * * * * * * * * * * * * * * * * * 4. Write, compile and run these three programs. Study their differences and similarities. import hsa.*; public class Multiply1 { public static void main(String[] args) { Stdout.print(“3 + 2 = “); Stdout.print(3 + 2); Stdout.println(); } } import hsa.*; public class Multiply2 { public static void main(String[] args) { Stdout.println(“3 + 2 = “ + (3 + 2)); } } import hsa.*; public class Multiply2 { public static void main(String[] args) { Stdout.println(“3 + 2 = “ + 3 + 2); } } 15 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 5. Write, compile and run these two programs. Study their differences and similarities. import hsa.*; public class Divide1 { public static void main(String[] args) { Stdout.println(“12 / 11 = “ + 12 / 11); } } import hsa.*; public class Divide2 { public static void main(String[] args) { Stdout.println(“12 / 11 = “ + 12.0 / 11); } } 6. Write, compile and run these two programs. Study their differences and similarities. import hsa.*; public class Divide3 { public static void main(String[] args) { Stdout.print(“12/5=“); Stdout.println(12 / 5, 8, 2); } } import hsa.*; public class Divide4 { public static void main(String[] args) { Stdout.print(“12/5=“); Stdout.println(12.0 / 5, 8, 2); } } 16 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 7. Write a program that outputs the following with proper alignment, exactly as shown here: a. Output needs to be sent to the Java Standard Window using Stdout. b. Numbers must be output as numbers, not text: Do not write your numbers in quotation marks. c. Use the adequate format of the commands Stdout.print() and Stdout.println() : One 1 Ten 10 One hundred 100 One hundred 100.00 Thousands 3645.1 Thousandths 0.342 Two hot dogs $ 3.45 Two soft drinks $ 2.76 Full meal $ 12.59 ! 8. In this exercise we experiment with the special tab character \t. This character will create a tab in the output. For example: System.out.print("John\tSmith") will output John Smith The word Smith is pushed to the next tab position. Tab positions usually happen at 9, 17, 25, 33, i.e. multiples of 8 plus 1. Write a Java program with the class name Students that uses the \t character. This character can be used in any output window The program must output exactly: Student Number Name Phone -------------- ---- ------------ 324332546 John 416-464-3321 354657555 Sue 905-443-2222 354665575 Anna 416-435-3633 17 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 9. Write a program with the class name StudentMarks that outputs the following with proper alignment and decimal places. Make sure to use numbers for the marks, not text, and a correct expression to calculate the average. Do not copy the number for the class average as given here: Student Number Quiz1 Quiz2 Quiz3 Average 323144324 67% 70% 78% 71.67% 324435007 89% 73% 86% 82.67% 310755654 57% 64% 74% 65.00% 387102291 34% 54% 57% 48.33% 375842516 67% 64% 58% 63.00% 300644535 95% 67% 75% 79.00% ------------------------------------------------------ Class average 68.28% 10.Write a Java program with the class name Calculator. The program needs to calculate and print the following expressions. Answers on the right column are for you to check your output: a) (24 + 1) * -2 (ans. -50) b) The square root of (125 / 5 * 4) (ans. 10.0) c) 4 / 2 + 8 / 4 + 12 / 6 + 16 / 8 (ans. 8) d) 4 cubed (ans. 64.00) e) 2 raised to the power of 5 (ans. 32.00) 11.Write a Java program with the class name Calculations. Only letters can go in quotes. All numbers need to be printed without quotes and all calculations must be performed by Java, not by you. The program outputs on any window the following three statements: A square has a side of 25.0m Its area is 625.0 sq m A rectangle has length 10.30m and height 3.00m Therefore, its perimeter is 26.60m A circle has a radius of 10.00cm Its circumference is 62.80 cm 18 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 1.3 Variables and Data Types A fundamental concept of programming languages is the variable. A variable is a name associated with a block of memory, where values can be stored, retrieved, and modified. Variables are created by the programmer as part of the program source code. The concept of storage of values in memory was introduced in the 1950‘s by John Von Neumann, a Hungarian born mathematician and physicist who worked in the Manhattan project. Von Neumann based his work partly on the work of J. Presper Ecker and John William Mauchly, the inventors of the ENIAC computer at the University of Pennsylvania (1946). Von Neumann proposed an architectural plan for the computer that has been used ever since. Thus our modern computer is appropriately called a Von Neumann Computer. This early vision of a separate logic for a central processing unit (CPU) that fetches, processes and stores information from and to memory (RAM) set the plan for all future computer systems. 1.3.1 Variables In Third Generation languages, access to memory is made relatively easy by the use of variables. Variables contain information that can be accessed through declared names. In Java, all variables need to be declared before they can be used. A declaration statement tells the Java compiler/ interpreter that we intend to use a variable in the program. The declaration also specifies the type of information that we will put in the variable. There are two kinds of variables in Java: Primitives and objects. First we will look at primitives. At a later time in the course, we will look at objects which are partially built on primitives. Primitives are variables whose memory is automatically allocated at declaration time. This means that the variable has its own memory space that can only be used by the program that created it. It is the responsibility of the Operating System to make sure that this space is fully protected and not used by any other program. Once declared, primitives can be used right away. In Java, when we use the word variable, we mean a primitive variable. 19 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 Different types of variables can contain different types of data, as explained below. The conventions for naming a variable: The name starts with a lower case letter If the name has more than one word, each additional word is capitalized Only numbers or letters in the name. No underscores or special symbols A variable name cannot use a keyword for a name It is good practice to use descriptive names We will see that variables can be used in Java commands such as print() and println() to output their values. 1.3.2 Data Types When a variable is declared, we will need to specify its data type, i.e., the kind of data that a variable can hold. Here are the data types we use most frequently for Java variables, declaration data type what it can hold byte integer integers from -128 to 127 char single character 65,536 different characters short integer integers from -32768 to 32767 int integer integers from -2^31 to 2^31 - 1 long integer integers from -2^63 to 2^63 - 1 float floating point -3.4E38 to 3.4E38 with 6-7 decimals of precision double floating point floats from -1.8E308 to 1.8E308 with 15-17 decimals of precision boolean logical true or false String text(*) text *A String is not a primitive but an object. Because it is used so often, Java compilers allow its use as though it were a primitive. We will see later why it is important to remember that it is an object. 20 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 1.3.3 Declaring Variables In a variable declaration, we use the syntax: [data type] [identifier]; For example, int age; int monthOfYear; double average; boolean finished; Here are some more examples, int mountainHeight; int lotteryPick1, lotteryPick2, lotteryPick3; double probabilityOfAThree; boolean gameOver; double assignmentMark; byte keyboardLetter; Alternatively, we can declare the variable and give it an initial value. The syntax is [data type] [identifier] = [initial value]; For example, double mark = 84.5; int numberOfCars = 0; boolean gameOver = false; 1.3 Exercises 1. Write a declaration statement for the following: a) The number of bank accounts a customer can have b) The maximum air speed of an airplane c) Whether a person has previously applied for a particular job d) The number of people in the classroom e) The amount in a bank account f) The number of basketballs in a department store g) The price of a basketball 21 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 2. Write a Java program with the class name VolumeOfCylinder. In the program declare and initialize the following variables: radius is a double with a value of 4.18 height is a double with a value of 11.18 Use the formula for the volume of the cylinder to calculate and print the volume of a cylinder with the dimensions given above. When the program runs, it should display radius = 4.18u, height = 11.18u, volume = 613.37 cu. u 3. Write a Java program with the class name SlopeOfLine. In the program declare and initialize the following variables: x1 is a double with a value of 5 y1 is a double with a value of 1 x2 is a double with a value of -3 y2 is a double with a value of 5 Use the slope formula to determine the slope of the line that passes through the points (x1, y1)and(x2, y2). Your code must not use actual numbers after the variables have been declared and initialized, but only the variables. The program output should be Slope of the line through (5, 1) and (-3, 5) is -0.5 4. Write a Java program with the class name AverageMark. In the program declare and initialize the following variables: test1 is a double with a value of 75.5 test2 is a double with a value of 81.0 test3 is a double with a value of 80.0 The program outputs the average mark with one rounded decimal place Average mark is 78.8% 5. Write a Java program with the class name RectangleGraphic. In the program declare and initialize the following variables: 22 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 upperLeftX is an int with a value of 60 upperLeftY is an int with a value of 110 width is an int with a value of 250 height is an int with a value of 150 Define a window with the name g and include the command g.drawRect(upperLeftX, upperLeftY, width, height); 6. Write a Java program with the class name NameInfo. In the program declare and initialize the following variables: name is a String with the value "Joanne Adams" age is an int with a value of 16 birth is a String with the value of "May" year is an int with a value of 1998 Using a single printing statement and making use of the variables but not the actual values, write the program that will print Born in May 1998, Joanne Adams is now 16 years old. 7. The following program calculates how many times the human heart beats in one month, on average. The program does not compile because it contains 6 errors. Find the errors so that you can compile and run the program: import hsa*; public class HeartBeats { public void static main(String() args) { console window = new Console(); int beats = 72.0; window.print("The human heart beats "); window.print(beats * 60 * 24 * 30); window.println(" times in one month") } } 23 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 1.4 Sizes of Variables A quick and simple introduction to Random Access Memory (RAM) will be helpful for understanding variables. RAM is a large grid where each cell of the grid can hold one exactly one byte. In most programming languages one byte is exactly one character. The following is a RAM that can hold a maximum of 80 bytes: The words we type on the keyboard are placed in RAM like this: c a t (sp) d o g Java is different from other languages in that it uses two bytes to store a character. Therefore, when storing the words cat dog, Java places them in memory this way: c a t (sp) d o g 24 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 With this simple definition in mind, we can now specify how much space each type takes in memory when programming with Java, declaration size in memory byte 1 byte char 2 bytes short 2 bytes int 4 bytes long 8 bytes float 4 bytes double 8 bytes boolean 1 byte String variable multiples of 2 bytes 25 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 1.4 Exercises 1. Calculate how much memory in bytes is being used by each of the following cases: a) 3 bytes and 2 shorts b) 4 floats, 240 characters, and 6 doubles c) 20 integers 2. Calculate how much memory in bytes is being used by the primitives of this program when it is running import hsa.*; public class Quadratic { public static void main(String[] args) { int a = 1; int b = 5; int c = 6; double x1=(-1.0*b+Math.sqrt(Math.pow(b, 2)-4*a*c))/(2*a); double x2=(-1.0*b-Math.sqrt(Math.pow(b, 2)-4*a*c))/(2*a); Stdout.println(“Root 1: “ + x1); Stdout.println(“Root 2: “ + x2); } } 3. Write a Java program that uses a total of 44 bytes by declaring only integers, character, and double variable types. Initialize each integer or double variable of your program to a value that is clearly invalid. By ‘invalid’ we mean that the value can be assigned, the program will compile, but the value is non-sensical. For example, initializing a variable named height to -1. Then, initialize each character value to the null character: ‘\0’ 26 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 1.5 Assignment Statements and Casting Now that we know how to declare variables, we can use them in different ways. One of the most fundamental ways is through assignment, which has the effect of storing a value into the variable. 1.5.1 Assignments Java allows the following assignment operations with variables: A constant to a variable, int cars; cars = 14; An expression to a variable, double cost; double tax; cost = 125; tax = cost * 0.13; A variable to a variable, int boxes = -1; int wrapping = -1; boxes = 3; wrapping = boxes; A constant, an expression or a variable at declaration time boolean done = true; double diameter = 2 * 10.5; double d = diameter; An increment int count = 0; count = count + 1; 27 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 An alternative way to increment int count = 0; count++; An expression of variable to itself, int numberOfPeople; numberOfPeople = 32; numberOfPeople = numberOfPeople + 3; Alternatively, int numberOfPeople; numberOfPeople = 32; numberOfPeople += 3; 28 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 1.5.2 Casting During assignment, the value assigned and the receiving variable must be Of the same type, or Implicitly casted2 to a higher type, for example int to double, or Explicitly casted3 to a lower type, for example double to int From the highest to the lowest the casting order of types in Java is, declaration data type Size in memory double numbers with fractional part 8 bytes float numbers with fractional part 4 bytes long integers 8 bytes int integers 4 bytes short integers 2 bytes char single character 2 bytes byte single byte 1 byte Exceptions in the above table are char to short and short to char, char to byte and byte to char, which must always be explicity cast regardless of the assignment direction 4. Furthermore, the char type can be assigned to the String type with implicit casting using concatenation, but String cannot be assigned to char, even with explicitly casting, because String is not a primitive. declaration data type Size in memory String text unlimited char single character 2 bytes 2 Change of type, whether implicit or explicit, is sometimes referred to as coercion 3 Ibid. 4 char and short must be cast to byte because byte is the lowest in the table. But byte and short need to be cast to char because char cannot contain negative numbers that short and byte could pontentially contain. Through casting, any negative short or byte are changed to a positive value that can be found in the ASCII table. This change to positive value is NOT an absolute value function as defined in mathematics. Exercise 1.6 4d deals with the ASCII table.. 29 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 Notes on Casting An integer type variable can have assigned to it values implicitly as long as the values fit in the storage space of the variable. A floating point type variable can have assigned to it values implicitly as long as the values fit in the storage space of the variable. A floating point variable can always accept an integer value because the floating point variable's range is larger than any integer type. An implicit casting means that Java will automatically create the correct type from the given value to the assigned variable. For example: int days = 628; double months = days / 31; // careful: integer division When 628 is divided by 31, the resulting integer value is first converted to a double before it is assigned to the variable months. This is possible because a double is considered a higher type than an int. Because of this, there is no loss of precision and the entire value is fully kept in the new variable. An explicit casting means that the programmer must specify in the program how the value will be assigned. This is done when a higher type needs to be assigned to a lower type. In this operation, higher order bytes may be lost. This is done to conserve space or because the higher order bytes are not needed. For example, long time = 1143351756; int seconds = (int) time; Since the number 1143361756 fits in an integer, it can be cast to the variable seconds without loss of information. The first four left most bytes are lost. 30 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 Effects of Casting When casting, the receiving variable will store the assigned value with the type of the receiving variable, but the assigned value will not have its type changed. When casting an integer value to an integer variable of a higher type, the value will be stored with as many leading binary zeroes to match the size of the receiving variable. When casting an integer value to a variable of a lower type, the value will be stored with its leftmost bits truncated so as to fit in the lower type variable. This can lead to loss of precision of the original value. When casting a floating point value to an integer type variable, the fractional part of the floating point number will be lost. This can lead to loss of precision of the original value. When casting an integer value to a floating point variable, the receiving variable will store the value in floating point format. Floating point format is more complex that integer format and requires interpretation. Special notes on long and float Notes on long and variable assignments: If the value being assigned to a long is a constant and is not in the range of an int, then we need to add the letter L (upper case or lower case) at the end of the constant for the compiler to accept the value. In the example that we saw above long time = 1143351756; the constant is within the range of an int. Therefore the line compiles successfully. Java keeps the constant 1143351756 as int but it will be cast to a 64 bit long because the variable time is a long. However, if the constant is a number outside the range of an int, for example 7142389754, we need to write the statement like this, long time = 7142389754L; 31 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 Java will always keep a mathematical integer constant as an int unless otherwise specified. Notes on float and variable assignments: When a floating point constant is assigned to a float variable, the constant must always be followed by the letter F (upper case or lower case) as in this example: float area = 6.78f; Java will always keep a mathematical floating point constant as double unless otherwise specified. 1.5.3 Other Considerations with Variables Exponential Notation Java allows the use of exponential notation when assigning values to a variable. For example double c = 3e8; will store in the variable c the value 3.0x108 or 300000000. Note that if the value is in any of the ranges then it will display in scientific notation when printing. For example, double x = 0.382e4 will print as 3820.0, but double x = 0.0382e12 will print as 3.82E10 32 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 Unititialized variables A compiler error will happen if an undefined or uninitialized variable is used in an assignment statement even if such variable has been declared. int a, b; a = b; will cause a compile time error because the variable b does not have a value at the time that it is assigned to a 1.5 Exercises 1. State the type of each value (some could have more than one type) a) -5 b) 37.0 c) 'A' d) 65 e) "Hello" f) 34 * 5 g) 77 / 6 h) 12 / 3.0 i) 2.7e-4 j) "31554" k) false 2. Rewrite in standard decimal form a) 8.77e-3 b) 299.04e0 c) -0.0443e6 d) -23e4 3. Which of the following conversions always require explicit casting? a) long to double b) byte to char c) float to double d) byte to long e) short to char f) double to long 33 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 4. What would be printed from this program fragment double x = 0.093e-1; double y = -3e-3; System.out.println("x: " + x + " y: " + y); 5. Find the four errors in the following program public class ErrorsInProgram { public static main(String[] args); { int i = 7; int j; i = j; System.out.println("Value of i is " + i); System.out.println("Value of j is " + j); } } 6. Write the value of each expression. Use a decimal point in your answer if the result is floating point a) (int) 1.8 * 0.6 b) (int) 6.3 / (int) 4.7 c) (float) 2 * 3 + 0.1 d) (double) (7 % 4 / 3) 7. Assume that all the variables in this exercise have been declared. Rewrite the following statements using alternative increment or decrement operators a) count = count + 1; b) people = people - 1; c) billiards = billiards + 5; d) cars = cars - 3; 34 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 8. Find the value of j and k after execution of the following code fragment int j = 0; int k = 0; j+=2; k = j; k++; k += j; k = k * j; j = 92 % k; 9. Which of the following operations will cause loss of precision? a) long m = 1243524000L; int n = (int) m; b) int x = 345231; short z = (short) x; c) short a = (short) ‘h’; char c = (char) a; 10. Write a number that satisfies the following conditions: a. The most significant binary bit is zero b. The number fits in the space of a short c. Coercing the number to a byte will cause loss of precision d. Coercing the number to a byte will result in a negative number 35 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 1.6 Input from the Keyboard Input from the keyboard can be done in different ways in Java. Here we look at two different ways. It is a good idea to be consistent with the choice of method. 1.6.1 Input using Stdin or a user defined window (Console) Data can be input into a variable through the keyboard. In computer jargon, the keyboard is called the standard input stream or console. When we include the import hsa.* statement, we have access to a set of input methods.They are: Stdin.readByte() Stdin.readShort() Stdin.readInt() Stdin.readLong() Stdin.readFloat() Stdin.readDouble() Stdin.readString() (reads only up to the first blank) Stdin.readLine() (reads the entire line) Stdin.readChar() Stdin.readBoolean() Each one of these returns the appropriate type, and the value is assigned to a variable. For example, the following statements prompt the user for a person’s age: int age = -1; Stdout.print(“Please enter your age: “); age = Stdin.readInt(); All of these are also available in a user defined window, Console w = new Console(); int age = -1; w.print(“Please enter your age: “); age = w.readInt(); 36 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 1.6.2 Input using the Scanner Class Data can also be input through another set of methods that are found in most Java IDE's and implementations. To access these methods we need to include the following import statement at the top of the program: import java.util.Scanner; Inside the program, the following statement is necessary Scanner [variable] = new Scanner(System.in); where [variable] can be any variable name. For example, Scanner keyboard = new Scanner(System.in); The methods available are [variable].nextByte() [variable].nextShort() [variable].nextInt() [variable].nextLong() [variable].nextFloat() [variable].nextDouble() [variable].next() (reads only up to the first blank) [variable].nextLine() (reads the entire line)1 [variable].nextBoolean() If a programming environment does not contain a particular class, then we need to include the class in a folder specified by the environment or specify a path to where the class resides. For example, Java-RTP does not include the Scanner class, so to access its commands we proceed as follows: Download the Scanner.class Copy the downloaded Scanner.class file to the folder Java RTP\Support\Classes Java-RTP does not require the statement import java.util.Scanner; if we install the Scanner.class this way. 1. Note to Scanner users: In some implementations of the Scanner class the method nextLine() does not process the CR and LF and the end of the line together but as two different lines of input. Therefore, two nextLine() statements may be needed to process a single line. Our implementation of Scanner processes CR and LF as a single line of input, so only one nextLine() statement is required. 37 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 1.6 Exercises 1. Write a computer program that clearly asks the user for 3 test marks, computes the average and outputs the result with a clear label. The answer should round to one decimal place. Make sure to initialize variables to invalid or null values. 2. Write a computer program that uses a boolean variable, initialized to false. Use the variable to obtain true or false from the user and then print out its value. The words in red below represent the value of the variable. For example, I am 16 years old: (True/False)? true It is true that I am 16 years old 3. Why is the following program not compiling? public class Numbers { public static void main(String[] args) { short height = -1; speedOfLight = 3e8; } } 4. Write a program that does the following: a. Declares an integer variable, asks the user for an integer, coerces the value into a separate short variable, and prints the value of the short b. Declares a double variable, asks the user for a number with both an integer part and a fractional part. The program then puts only the integer part of the number into another variable and then prints the resulting integer. For example, if 2.43 is input, then the program puts only 2 in another variable and then the 2 is printed. c. Similar to part b but the program puts the fractional part into a variable whose value is then printed with only 2 decimal places. For example, if 2.43 is input, then the program puts the fractional part, i.e. 0.43 in another variable, and then it's printed. d. Declares a short variable, gets a value from the user (between 65 and 110), casts the value into a char, and prints it out as a character. How is the value that you entered related to the character that is printed? 38 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 5. Run through the following program manually, writing out the value of each variable as the program runs. Then write what the program prints. public class Tracing { public static void main(String[] args) { int count = 0; int sum = count; count = count + 1; sum = sum + count; count = count + 1; sum = sum + count; count = count + 1; sum = sum + count; count = count + 1; sum = sum + count; Stdout.print(sum); } } 6. If you invest P dollars at a yearly interest rate of R, compounded yearly, in N years your investment will grow to A according to the formula N ⎛ R ⎞ A = P ⎜ 1+ ⎝ 100⎟⎠ Write a Java program that asks the user for the initial investment, the yearly rate and the number of years. The program calculates and outputs the value of A with two decimal places. 7. Write a Java program that asks the user for four int numbers representing two coordinate points in the plane (x1, y1) and (x2, y2). The program outputs the equation of the line through those points, with the slope and the y-intercept rounded to one decimal place. For example, if points are (1, -2) and (3, 4) the program shows x1: 1 y1: -2 x2: 3 y2: 4 Equation of the line through (1, -2) and (3, 4) is y = 3.0x + -5.0 where the first four lines printed are the input supplied by the user. 39 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 1.7 Graphics output with hsa The hsa package provides a collection of methods that provide the programmer with graphics output. When using the hsa package, all output must be sent to a user defined window or console. 1.7.1 Graphics output using a user defined window (Console) Graphics output using hsa is sent to a user defined window since all the graphics commands available work only with a window that the user creates. Therefore, at the beginning of our code we need the statement import hsa.*; and inside the main method we need a line such as Console w = new Console(); Java gives us a window as shown here Notice that in Java, the origin (0, 0) is at the upper left corner of the window. If we want to plot points using the Cartesian coordinate system, we will need to perform a small transformation so that the points show in the correct location. This standard window has 25 rows and 80 columns for writing text with a font size of 14. 40 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 The new Console() statement can be expanded to allow us to define the window size, the font to use in the window, and the title of the window. Here are the other ways in which it can be used: Console w = new Console(rows, columns) creates a window with as many rows and columns as specified Console w = new Console(rows, columns, fontSize) same as above but the size of the writing font can be specified Console w = new Console(rows, columns, fontSize, title) a title can be specified here, as a string type so it must be in quotes Console w = new Console(rows, columns, title) same as above but the font size is the standard size of 14 Console w = new Console(title) standard size window and a title can be specified Console w = new Console(fontSize) 25 rows by 80 columns with the specified font size Console w = new Console(fontSize, title) same as above and a title can be specified 1.7.2 Graphics commands in hsa Note: All graphics commands given in this section need to be preceded with the variable name of the console. For example, to draw a line between the points (10, 30) and (328, 321) in the console window declared above, the following command would be used w.drawLine(10, 30, 328, 321); 41 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 To use different colours the following is needed at the top of the program, import java.awt.*; The following are some of the graphics methods available in hsa. drawLine(x1, y1, x2, y2) drawRect(x, y, width, height) fillRect(x, y, width, height) drawOval(x, y, hDiameter, vDiameter) fillOval(x, y, width, height) setColor(color) setColor(new Color(redValue, greenValue, blueValue)) clear() setCursor(row, col) drawString(text, x, y) maxx() maxy() These methods are used for text output: maxrow() maxcol() setTextColor(color) setTextColor(new Color(redValue, greenValue, blueValue)) setTextBackgroundColor(color) setTextBackgroundColor(new Color(redValue, greenValue, blueValue)) The values that we pass to the methods are called parameters. All numeric parameters expect values that will fit into the int type: drawLine(x1, y1, x2, y2) draws a line from (x1, y1) to (x2, y2) in the current color. To draw a single point, use drawLine(x, y, x, y) drawRect(x, y, width, height) draws a rectangle with upper left corner at (x, y) with dimensions width and height 42 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 fillRect(x, y, width, height) fills a rectangle with upper left corner at at (x, y) with dimensions width and height drawOval(x, y, hDiameter, vDiameter) draws an oval enclosed in an imaginary rectangle with upper left corner at (x, y)and with a horizontal diameter hDiameter and a vertical diameter vDiameter fillOval(x, y, width, height) draws an oval enclosed in an imaginary rectangle with upper left corner at (x, y)and with a horizontal diameter hDiameter and a vertical diameter vDiameter setColor(color) sets the current drawing color. The parameter to this method can be one of: Color.white Color.red Color.yellow Color.magenta Color.blue Color.green Color.black Color.orange Color.pink Color.cyan Color.gray Color.lightGray Color.darkGray setColor(new Color(redValue, greenValue, blueValue)) sets the current drawing color. The values of redValue, greenValue, and blueValue can be integers from 0 to 255. With this scheme we can create 256x256x256 = 16,777,216 different colors. clear() clears the window and moves the cursor to (0, 0) position setCursor(row, col) moves the cursor to (row, col) 43 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 drawString(text, x, y) draws the string text at location (x, y) maxx() returns the maximum x position of the current window maxy() returns the maximum y position of the current window maxrow() returns the maximum row of the current window (first row is 1) maxcol() returns the maximum column of the current window (first column is 1) setTextColor(color) sets the text color for subsequent print operations setTextColor(new Color(redValue, greenValue, blueValue)) same as above but with user defined colors setTextBackgroundColor(color) sets the background text color for subsequent print operations setTextBackgroundColor(new Color(redValue, greenValue, blueValue)) same as above but with user defined colors 1.7 Exercises 1. Write a Java program that creates a window of 30 rows and 100 columns with a font size 18 and the title Computer Graphics at Bloor CI. The program does the following: a. draws a cyan filled rectangle that takes up the entire window b. draws a black horizontal line that divides the window in half c. draws a black vertical line that divides the window in half d. draws the label x on the horizontal line, approximately on the far right e. draws the label y on the vertical line, approximately on the far top f. draws the line y = x + 15 in the interval [-300, 300] g. sets the text background color to cyan h. sends the cursor to row 10, column 65 i. prints the label y = x + 15 44 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 2. Write a Java program that creates a standard sized window and fills an oval in any location and of any size, with a color whose red, green and blue values are 45, 140, and 221 respectively. 3. Write a Java program that uses Stdin to ask the user for two numbers, x and y. Then the program asks for two other numbers, width and height. The program then creates a standard sized window and draws the frame of a red rectangle in this window with the information supplied by the user. 4. Write a Java program that uses Stdin to ask the user for a mark between 0 and 100 with one decimal place. The program then creates a standard sized window with a label of 0% at the bottom left corner and a label of 100% at the top left corner of the window. The program then draws a blue vertical rectangle that proportionately displays the mark of the student. The mark needs to be rounded. Here is a sample run: Enter a mark: 82.6 45 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 5. The following image is created by drawing two diagonal lines, a rectangle, and an ellipse. The width of the rectangle is half the width of the window, and the height of the rectangle is half the height of the window. Write a Java program that draws this image, centered in the window regardless of the dimensions of the window. Try the program first with a standard window. Then, change the console call to make the window 30 rows and 40 columns. The rest of the code needs to remain unchanged but draw the image correctly. Run the program with other sizes to check that the image is centered correctly. (Note: The console window has a minimum set at 35 columns. The buttons at the top of the window prevent us from creating a narrower window.) 46 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 6. Write a Java program that draws a vector in the Cartesian plane from an x and a y value entered by the user. A vector is drawn from (0, 0) to (x, y). Draw this in a standard console and let each increment of the axes be 20 pixels. For example, ! ! Enter x: -9 Enter y: 8 Include in your drawing a label of the coordinates, enclosed in brackets and a few pixels away from the vector so they can be read. Drawing the arrow at the tip of the vector requires drawing a small horizontal and a small vertical line from the tip. The direction of these lines can be determined by the signs of the x and y coordinates provided by the user. Each line can be drawn with a single c.drawLine() statement. To determine how far each line needs to be drawn, consider using the absolute function Math.abs(x) 47 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 7. Write a Java program that draws a Tic Tac Toe board as shown below. All squares have the same dimensions as accurately as possible (because of integer division some widths or heights may be +/-1 pixel off), and the circles and x’s are centered also as accurately as possible. These drawings need to adjust their locations automatically if the size of the console window is changed during declaration. 48 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 8. Write a Java program that asks, in the user defined window, for your name (possibly with spaces), your student number (also possibly with spaces), and marks for Physics, Science, Careers, and History. The input is then erased from the screen and the program prints a simple report along with a bar graph, with axes, as shown in this sample run: Enter your name: John Blueprint Enter your student number: 463 252 228 Enter your mark for Physics: 87 Enter your mark for Science: 82 Enter your mark for History: 72 Enter your mark for Careers: 97 Note: Right justification and decimal specifications can be done with print() and println() in a user defined window, but not right justification of strings. 49 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 9. Write a Java program that asks, in the user defined window, for three values, each a double. The input is erased from the screen and the program draws a pie chart showing percentages with respect to the sum of the three values. Sample run: Enter value 1: 37 Enter value 2: 45 Enter value 3: 21 For this exercise we need three new methods: Math.cos(angle in radians) that returns the cosine of an angle as a double Math.sin(angle in radians) that returns the sin of an angle as a double Math.toRadians(angle in degrees) that converts to radians as a double For example, to initialize the variable alpha to the cosine of 72 degrees we can write double alpha = Math.cosine(Math.toRadians(72)); Note: Right justification and decimal specifications can be done with print() and println() in a user defined window, but not right justification of strings. 50 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 Unit 1 Extra Exercises 1. Write a Java program that tests casting from short to char and back to short. Is there any loss of information in the process? Why is the casting necessary? 2. In Java all integers are signed. This means that the left most bit represents the sign. When the bit is 0 the number is positive. When the bit is 1 the number is negative. Write a positive int that would become a negative short when coerced. For example, the int 165,888 becomes a short -30720 when coerced. (Hint: Consider bit 15) 3. Trace the following program fragment and determine the final value of amount: double principal = 1000; double interestRate = 0.05; int years = 5; double amount = principal * Math.pow((1 + interestRate), years); years-=2; interestRate += 0.01; amount = amount * Math.pow((1 + interestRate), years); 4. Consider the binary pattern 0100 0011 0100 0110. If this is assigned to the variable short x, what will be the value of a.x b.(byte) x c. implicitly casting x to an int variable 5. What positive integer x will cause the statement ! ! ! System.out.println((int) x); to print -2000147334 51 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 6. Write a Java program that draws the line y = 2x + 10 in the Cartesian plane in the interval [0, 400], where the origin (0, 0) is at the bottom left of the window. 7. Given a quadratic function f (x)= ax2 + bx + c write a Java program that asks the user for the values of the three coefficients a, b, and c and determines whether the function has two, one, or no solutions. 8. Write a Java program that draws a circle centred on the window regardless of the size of the window. 9. Using the formula of exercise 1.6 6, write a Java program that draws a simple plot of an initial $100 investment at a yearly interest rate of 5% showing the increase in amount over 7 years. Sample run, 52 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 Appendix I.1 Converting From Binary to Decimal To convert an unsigned1 binary number into decimal, we start by giving each binary bit a position number. The rightmost bit has position 0, the next bit to the left has position 1, the next has position 2, etc. These positions are then used with powers of 2 to do the conversion. The following example shows how the binary number 11012 is converted to decimal: Here are some more examples: 1012 = 1× 22 + 0× 21 + 1× 20 = 4+ 0+ 1= 5 1112 = 1× 22 + 1× 21 + 1× 20 = 4+ 2+ 1= 7 101112 = 1× 24 + 0× 23 + 1× 22 + 1× 21 + 1× 20 = 16+ 0+ 4+ 2+ 1= 23 1unsignedmeans that the number is assumed to always be positive. The leftmost bit of the number is NOT a sign but a positive quantity 53 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 Appendix I.2 Converting From Decimal to Binary Through a rather simple and clever way of dividing, we can also convert a decimal number into binary. We’ll call this the Remainder’s Method. Let’s convert decimal 23 into binary: Divide by 2 Remainder 23 - 11 1 5 1 2 1 1 0 0 1 If we read the 1’s and 0’s from the bottom upward: 2310 = 101112 54 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 Appendix I.3 Using a programmer’s calculator to convert bases Standard operating systems such as Windows, Ubuntu, or Mac OS come equipped with a programmer’s calculator that can convert from one system to another. The calculator can change views from Standard to Scientific to Programmer. Shown here is Mac OS converting 2310 with 64 binary bits right above the buttons An on-line programmer's calculator can be found at programmer's calculator 55 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 Appendix I Exercises 1. Convert the following numbers to decimal. Confirm your answers using a programmer's calculator. (For really big numbers just use the calculator) a) 12 b) 1102 c) 110112 d) 10010102 e) 02 f) 111001110110102 g) 11 00112 h) 1001 1110 0011 1100 1110 0010 10002 2. Convert the following numbers from decimal to binary. Confirm your answers using a programmer's calculator a) 12 b) 5 c) 28 d) 34 e) 102 f) 384 g) 4096 h) 43231 56 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 2 - DECISION MAKING - CONDITIONS All the programming we have done so far consists of a set of statements, one after another. All statements of our programs have executed in sequence. For this reason these types of constructs are rightly called sequential statements. A very powerful construct that is common to programming languages is the selection construct. It allows for conditions to be placed in the program and, if these conditions become true while the program is running, then the statements following the conditions are executed. Otherwise those statements are ignored and the execution of the program continues elsewhere. In this way, we can be selective about the code that gets executed in our program. 2.1 Selection: if and if...else The first general form of the selection construct is if () { } The statements within the braces are executed if the condition is true. Program execution continues after the closing brace of the if construct whether or not the condition is true. The program below uses an if construct to implement the absolute value function, import hsa.*; public class AbsoluteFunction { public static void main(String[] args) { Stdout.print("Enter a number: "); int number = Stdin.readInt(); Stdout.print("Absolute value of " + number + " is "); if (number < 0) { number = -1 * number; } Stdout.println(number); } } 1 ! 2015, 2016 Mario Portoraro, All Rights Reserved Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 The if construct accepts an else part. If the condition within the if part is true, then the statements under the if are executed. Otherwise the statements under the else are executed. The general form is, if () { } else { } In C and in C++ the actual implementation of the selection construct is exactly like Java. Notice the following important points: a) Statements within the if and within the else are always indented. Code needs to be indented to make programs readable and understandable. Code is indented usually 4 spaces b) Opening and closing parenthesis ( ) are always used to enclose the condition. This is necessary for the program to compile. c) Opening and closing braces { } are used to contain the statements for the if part and for the else part. In Java these braces are optional if there is only one statement following the if or following the else. Having the braces regardless of the number of statements within the if or the else is a way to avoid possible future problems. The following table summarizes the logical operators used in conditions and two (of many) logical String methods: (Note: The char and the byte are considered to be numeric types) 2 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 Here is an example of a program that determines whether the user has input an even or an odd number: import hsa.*; public class EvenOrOdd { public static void main(String[] args) { Stdout.print("Enter a number: "); int number = Stdin.readInt(); if (number % 2 == 0) { Stdout.println(number + " is even"); } else { Stdout.println(number + " is odd"); } } } When the user types in a number, say 65, it is stored in the variable number. Then the condition (number % 2 == 0) is evaluated. If the result of number % 2 is 0, then the condition evaluates to true and thus number must be even. If the result of number % 2 is 1, then the condition evaluates to false and number is odd. Enter a number: 45 45 is odd Enter a number: 14 14 is even 2.1 Exercises 1. Write a Java program that asks the user for two numbers and prints out the larger of the two numbers 2. Write a program that asks the user for a mark. If the mark is 50 or more, the program displays the message A mark of is a PASS where is the actual number that the user typed in. For example, Mark: 79 3 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 A mark of 79 is a PASS Mark: 87 A mark of 87 is a PASS 3. Add code to the previous program so that if the mark is something smaller than 50, the message displayed is With a mark of you do not pass the course For example, Mark: 75 A mark of 75 is a PASS Mark: 46 With a mark of 46 you do not pass the course Mark: 50 A mark of 50 is a PASS 4. Modify the program so that if the mark is less than zero or more than 100 it displays an error message. For example, Mark: 92 A mark of 92 is a PASS Mark: 104 ***Error: Mark cannot be more than 100 Mark: 43 With a mark of 43 you do not pass the course Mark: -4 ***Error: Mark cannot be negative 4 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 5. Write a Java program that asks the user for two numbers. The program divides the first number by the second number and prints the result if and only if the second number is not zero. Otherwise, the program prints an error message. For example, First number: 7 Second number: 2 7 / 2 = 3.5 Number 1: 4 Number 2: 0 Error: Division by zero is undefined 6. Write a Java program that asks the user for a number and determines whether or not the number divisible by 7. For example: Number: 91 91 is divisible by 7 Number 22 22 is not divisible by 7 2.2 Selection: Multiway if Many times we need to include a series of conditions in our program. For example, if we want to print the letter grade for a course mark, we may need to test whether the mark is larger than 80 but less than 90, or larger than 70 but less than 80. Here is a code fragment that handles the situation double mark = Stdin.readDouble(); if (mark > 100) { c.println(“***invalid mark: “ + mark); } else if (mark > 90) { c.println(“A+”); } else if (mark > 80) { c.println(“A”); } else if (mark > 70) { c.println(“B”); 5 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 } else if (mark > 60) { c.println(“C”); } else if (mark > 50) { c.println(“D”); } else if (mark > 0) { c.println(“F”); } else { c.println(“***invalid mark: “ + mark); } The general form is if () { } else if () { } else if () { }... else { } In this construct, the last else is optional. 6 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 2.2 Exercises 1. Write a Java program that asks the user for how much they make in one hour. If the amount entered is 11 then print the words MINIMUM WAGE; if the amount entered is more than 11 then print ABOVE MINIMUM; otherwise print ***INVALID AMOUNT. For example, Hourly wage: 11 MINIMUM WAGE Hourly wage: 4.75 ***INVALID AMOUNT Hourly wage: 17.25 ABOVE MINIMUM 2. Write a Java program that asks the user for three numbers and prints out the largest of the three numbers 3. Write a Java program that asks the user for three numbers and prints them out in ascending order 4. Write a Java program that asks for the user for a number from 1 to 12. The program prints the corresponding month as a word. For example: Month: 10 October 5. Write a Java program that asks the user for a year and determines if the year is a leap year. Research the definition of leap. It is not enough that the year be divisible by 4. For example, the year 2100 is divisible by 4 but it is not a leap year. 7 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 2.3 Selection: switch...case In many instances we will need to make a decision based on one of many possible options. We have already done some of that, and it required many if...else constructs one after the other. Java offers a convenient alternative, i.e., the switch statement. It has its roots (yet again) in the C programming language that, for this particular construct, also shares the very same syntax as Java. Its syntax is: switch() { case : break; case : break;... default: break; } In the switch construct must be of type byte, char, short or int. Here is an example: Stdout.print("Enter an option: "); int option = Stdin.readInt(); switch(option) { case 0: Stdout.println("You chose option 0"); break; case 1: Stdout.println("You chose option 1"); break; case 2: Stdout.println("You chose option 2"); break; default: Stdout.println("You chose neither of 0, 1, or 2"); break; } 8 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 Here is some sample runs: Enter an option: 0 You chose option 0 Enter an option: 5 You chose neither of 0, 1, or 2 Things to keep in mind with the switch construct: 1.The expressions in the switch and case statements must be of an integer type: byte, char, short, or int; long is not accepted 2.The break statement is necessary to have the program jump from the end of the statements to the end of the switch construct. If the break statement is not included then the program will continue with the statements in the next case. This is something to be careful about; it is a cause for bugs in the program. 3.The default statement will cause its statements to run if none of the cases before it have been satisfied. 2.3 Exercises 1. Write a Java program that asks the user for three assignment marks. Once the marks have been entered, the program displays a simple menu with 3 options: 1) To print the average of the marks 2) To print the highest mark 3) To print the lowest mark Then the program asks the user for an option (1, 2, or 3). For each of the options, write the Java code needed to calculate the average, or highest, or lowest value. Here is a sample run, Enter assignment 1 mark: 75 Enter assignment 2 mark: 80 Enter assignment 3 mark: 67 1. Print average 9 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 2. Print highest 3. Print lowest Enter an option: 2 Highest mark is 80 Here is another sample run: Enter assignment 1 mark: 75 Enter assignment 2 mark: 80 Enter assignment 3 mark: 67 1. Print average 2. Print highest 3. Print lowest Enter an option: 1 Average mark is 74 2. Write a program that ask the user for a number from 1 to 12. The program then prints out the name of the month. For example, Enter month: 2 February 3. Write a program that asks the user for two numbers: The first is a number from 1 to 12. This number is a month. The second number is a year. The program prints the number of days for the given month, taking into account that the year could be leap. Here are some examples, Enter month: 5 Enter year: 2015 31 Enter month: 2 Enter year: 1999 28 Enter month: 11 Enter year: 2000 30 Enter month: 2 Enter year: 2016 29 10 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 2.4 Compound Conditions All the conditions we have seen so far require only one test at a given time. If we had a case where two conditions needed to be met, we had to use a nested if statement, that is, an if statement inside another if statement. Java allows for more than one condition to be tested simultaneously in a single if statement through the use of Boolean operators. They are i. AND (Java symbol is &&) ii. OR (Java symbol is ||) iii. NOT (Java symbol is !) These three operators are the foundation of all computer circuit design. All logic boards, processors, memory, and peripherals of computer systems are designed with blocks of these three operators. The most basic machine is the half-adder which allows for the addition of numbers using binary. In this course we will learn how to add two numbers with a half-adder by using these operators and we will explore its circuitry. From this block, full adders, multipliers, and all other operations of calculators and computers are built. 2.4.1 AND operator AND is a binary operator that accepts two operands of type boolean. In this context, binary means that the operator accepts two operands. An operand is a value or an expression on which the operator operates. For example, in the expression 2 + 3, the operator is the plus sign, and the operands are the numbers 2 and 3. In this case the operands are numbers and the result is also a number, namely 5. The AND operator accepts two boolean operands and the result is also boolean. For example: if (mark is larger than 90 AND attendance is higher than 95 percent) For this expression to evaluate to TRUE, both the left operand AND the right operand must be true. Thus, if it is the case that mark is larger than 90 and attendance is higher than 95%, then the whole expression is TRUE. If any of the two operands is false then the whole expression is FALSE. We can look at all the possible scenarios of this operator with a truth table: 11 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 Left Operand AND Right Operand TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE In Java, a condition using this operator requires the use of two ampersands: &&. For example, if (mark > 90 && attendance > 0.95) { } A couple of points to be mindful of: a) In English, the word BUT can be replaced by the AND operator to be used in logical and computer language b) In Java, C and C++ the AND operator is implemented with two ampersands: &&. A single ampersand & has a different meaning: bitwise- and which we will learn soon. 2.4.2 OR operator OR is a binary operator that accepts two operands of type boolean. When the expression is evaluated, the result is also boolean. For example: if (assignment >= 80 OR quiz >= 85) For this expression to be TRUE, it is enough that one of the operands be TRUE. There exist two types of OR in languages: Inclusive and exclusive. In computer languages, the OR is inclusive. The truth table for inclusive OR is 12 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 Left Operand OR Right Operand TRUE TRUE TRUE TRUE TRUE FALSE FALSE TRUE TRUE FALSE FALSE FALSE In Java, the OR operator is implemented with two vertical bars: ||. For example, if (mark < 50 || absences > 4) { Stdout.println(“Mark is dropping...”); } The truth table for exclusive-OR is Left Operand XOR Right Operand TRUE FALSE TRUE TRUE TRUE FALSE FALSE TRUE TRUE FALSE FALSE FALSE Exclusive-OR is not implemented in Java, but it can be easily implemented using the operators AND, OR, NOT. See exercises below. We need to be careful to use two vertical bars. One vertical bar is a bitwise- inclusive-or that we will learn later. The exclusive or exists in Java only at the bit level and its operator is ^ 13 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 2.4.3 NOT operator NOT is a unary operator that toggles the value of the boolean expression. Unary means that it accepts only one operand. A value of TRUE is turned to FALSE and a value of FALSE is turned to TRUE. This is very useful when switching from one state to another, such as displaying or not displaying an object on the screen. The truth table for the NOT operator is: Operand NOT TRUE FALSE FALSE TRUE In Java, a condition using this operator requires the use of the exclamation mark ! which means NOT. For example, boolean gameOver = false; if (!gameOver) { } 2.4.4 Order of operations Boolean operators have an order of operations very much like BEDMAS. When an expression is given, the order is 1. Brackets ( ) 2. Unary plus, unary minus, NOT + - ! 3. Multiplication, division, modulus * / % 4. Addition, subtraction + - 5. Relational comparison < >= == 6. AND && 7. OR || 8. assignment = If test is a boolean variable and we let x = 4 and y = -5 then the expression 14 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 test = x == 4 && (!(y < 0)) evaluates in this order: a) y < 0 is true b) !(y < 0) is false c) (!(y < 0)) is false d) x == 4 is true e) x == 4 && (!(y < 0)) is false f) false is assigned to the variable test 2.4 Exercises 1. Write a Java program that determines if a number is divisible by 6. In this program you need to use the ‘%’ mod operator but you are restricted to using it only with 2 and 3. You may not use an expression that involves the number 6. The point of this is to use a compound condition. 2. Evaluate all possible cases of the expression P && Q || R by completing the following truth table. Remember to apply the correct order of operations: P AND Q OR R T T T T T F T F T T F F F T T F T F F F T F F F 3. Evaluate all possible cases of the expression !P || Q by filling in all the possible combinations of TRUE and FALSE for P and Q in the 15 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 following table. Then evaluate the operators NOT and OR. Remember to apply the correct order of operations: NOT P OR Q 4. In the following compound sentences, let P stand for the sentence to the left of the binary operator without negation, and Q stand for the sentence to the right of the binary operator without negation. Then build the truth tables by assigning all possible values of TRUE and FALSE and evaluating the expressions: a) Peter has $7 in his pocket OR a movie ticket b) It is not the case that you are here AND I am awake c) Year is divisible by 4 BUT not by 100 5. Exclusive-OR, XOR, is a binary operator that takes two binary operands and evaluates to TRUE if and only if one of the operands is true (See the XOR table above in section 6.4.2) If P is the first operand and Q is the second operand, XOR can be expressed as follows: (P or Q) but not both This can be further refined to (P or Q) but not (P and Q) Write the Java expression that implements XOR and verify your expression by writing a Java program that uses it with the four possible different cases: true true, true false, false true, false false. The result of your program should look like this: 16 Introduction to Computer Science - pre-AP/University Preparation ICS3U-Grade 11 p q (p xor q) -------------------------------- true true false true false true false true true false false false 6. Extending: XNOR is the negation of XOR. In other words, XNOR is the same as NOT XOR. Build the truth table for XNOR using two operands, P and Q in a Java program. Your program output should be p q (p xnor q) -------------------------------- true true

Use Quizgecko on...
Browser
Browser