Chapter 9: Variables and Assignment Statements Bradley Kjell (Revised 07/20/2008)
|
|
- Hannah Lester
- 7 years ago
- Views:
Transcription
1 Chapter 9: Variables and Assignment Statements Bradley Kjell (Revised 07/20/2008) In all but the smallest programs, an executing program is constantly working with values. These values are kept in little sections of main memory called variables. Chapter Topics: Variables Assignment Statements Expressions Arithmetic Operators QUESTION 1: Do you imagine that a variable can change its value? Used by permission. Page 1 of 44
2 Yes that is why is is called a variable. Variables The billions of bytes of main storage in your home computer are used to store both machine instructions and data. The electronic circuits of main memory (and all other types of memory) make no distinction between the two. When a program is running, some memory locations are used for machine instructions and others for data. Later, when another program is running some of the bytes that previously held machine instructions may now hold data, and some that previously held data may now hold machine instructions. Using the same memory for both instructions and data was the idea of John von Neumann, a computer pioneer. (If you are unclear about bytes and memory locations, please read Chapter 3.) variable a named location in main memory which uses a particular data type to hold a value. Recall that a data type is a scheme for using bit patterns to represent a value. Think of a variable as a little box made of one or more bytes that can hold a value using a particular data type. To put a value in memory, and later to get it back, a program must have a name for each variable. Variables have names such as payamount. (Details will be given in a few pages.) QUESTION 2: Used by permission. Page 2 of 44
3 Must a variable always have a data type? Used by permission. Page 3 of 44
4 Yes. Otherwise it would not be clear what its bits represent. Declaration of a Variable The example program uses the variable payamount. The statement long payamount = 123; is a declaration of a variable. A declaration of a variable is where a program says that it needs a variable. For our small programs, place declaration statements between the two braces of the main method. The declaration gives a name and a data type for the variable. It may also ask that a particular value be placed in the variable. In a high level language (such as Java) the programmer does not need to worry about how the computer hardware actually does what was asked. If you ask for a variable of type long, you get it. If you ask for the value 123 to be placed in the variable, that is what happens. Details like bytes, bit patterns, and memory addresses are up to the Java compiler. In the example program, the declaration requests an eight-byte section of memory named payamount which uses the primitive data type long for representing values. When the program starts running, the variable will initially have the value 123 stored in it. A variable cannot be used in a program unless it has been declared. A variable can be declared only once. Used by permission. Page 4 of 44
5 QUESTION 3: What do you think the program prints on the monitor? (You should be able to figure this out.) Used by permission. Page 5 of 44
6 The variable contains: 123 Simulated Java Program To get the most out of these notes, copy the program to a text editor, save it to a file called Example.java, compile it, and run it. See Chapter 7 on how to do this. For a simulation of running the program, enter an integer in the text box below and click on "Compile", then click on "Run". (Note: if this does not work, your browser does not have JavaScript enabled.) This is just a simulation (using JavaScript), so it is not exactly like compiling and running a real Java program. Don't take it too seriously. Please do the real thing if you can. QUESTION 4: Try entering something like "rats" in the declaration. Does the program compile successfully? Used by permission. Page 6 of 44
7 No. Syntax of Variable Declaration The word syntax means the grammar of a programming language. We can talk about the syntax of just a small part of a program, such as the syntax of variable declaration. There are several ways to declare variables: datatype variablename; This declares a variable, declares its data type, and reserves memory for it. It says nothing about what value is put in memory. (Later in these notes you will learn that in some circumstances the variable is automatically initialized, and that in other circumstances the variable is left uninitialized.) datatype variablename = initialvalue ; This declares a variable, declares its data type, reserves memory for it, and puts an initial value into that memory. The initial value must be of the correct data type. datatype variablenameone, variablenametwo ; This declares two variables, both of the same data type, reserves memory for each, but puts nothing in any variable. You can do this with more than two variables, if you want. datatype variablenameone = initialvalueone, variablenametwo = initialvaluetwo ; This declares two variables, both of the same data type, reserves memory, and puts an initial value in each variable. You can do this all on one line if there is room. Again, you can do this for more than two variables as long as you follow the pattern. If you have several variables of different types, use several declaration statements. You can even use several declaration statements for several variables of the same type. Used by permission. Page 7 of 44
8 QUESTION 5: Is the following correct? int answer; double rate = 0.05; Used by permission. Page 8 of 44
9 Yes as long as the names answer and rate have not already been used. Names for Variables The programmer picks a name for each variable in a program. Various things in a program are given names. A name chosen by a programmer is called an identifier. Here are the rules for identifiers: Use only the characters 'a' through 'z', 'A' through 'Z', '0' through '9', character '_', and character '$'. o An identifier can not contain the space character. Do not start with a digit. An identifier can be any length. Upper and lower case count as different characters. o SUM and Sum are different identifiers. An identifier can not be a reserved word. An identifier must not already be in use in this part of the program. A reserved word is a word which has a predefined meaning in Java. For example int, double, true, and import are reserved words. Rather than worry about the complete list of reserved words, just remember to avoid using names that you know already mean something, and be prepared to make a change if you accidentally use a reserved word you didn't know. As a matter of programming style, a name for a variable usually starts with a lower case letter. If a name for a variable is made of several words, capitalize each word except the first. For example, payamount and grandtotal. These conventions are not required by syntax, but make programs easier to read. QUESTION 6: Which of the following variable declarations are correct? int mypay, yourpay; long good-by ; Used by permission. Page 9 of 44
10 short shrift = 0; double bubble = 0, toil= 9, trouble = 8 byte the bullet ; int double; char thismustbetoolong ; int 8ball; float a=12.3; b=67.5; c= ; Used by permission. Page 10 of 44
11 There are some syntax errors: int mypay, yourpay; // OK long good-by ; // bad identifier: "-" not allowed short shrift = 0; // OK double bubble = 0, toil= 9, trouble = 8 // missing ";" at end. byte the bullet ; space // bad identifier: can't contain a int double; word // bad identifier: double is a reserved char thismustbetoolong ; choice // OK in syntax, but a poor // for a variable name int 8ball; // bad identifier: can't start with a digit float a=12.3; b=67.5; c= ; // bad syntax: don't use ";" to separate variables Example Program The example program, containis three variable declarations. The variables are given initial values. The character * means multiply. In the program, Used by permission. Page 11 of 44
12 (hoursworked * payrate) means to multiply the number stored in hoursworked by the number stored in payrate. Important Idea: When used as part of an expression, the name of a variable represents the value it holds. (An expression is a part of a statement that asks for a value to be calculated.) When it follows a character string, + means to add characters to the end of the character string. So "Hours Worked: " + hoursworked makes a character string starting with "Hours Worked: " and ending with characters for the value of hoursworked. The program prints: Hours Worked: 40 pay Amount : tax Amount : 40.0 Remember that if you want to see this program run, copy it from your Web browser, paste it into Notepad or other text editor, save it to a file, compile, and run it. (See Chapter 7.) QUESTION 7: Why did the program print the first 40 without a decimal point, but printed the second one with a decimal point as 40.0? (Hint: look at the variable declarations.) Used by permission. Page 12 of 44
13 The first value was stored in a variable of data type long, an integer type. Integers do not have fractional parts. The second forty was the result of a calculation involving a variable of data type double, a floating point type, which does have a fractional part. (Here, the fractional part was zero.) Calculation Look carefully at the statement highlighted in red. The parentheses around (hoursworked * payrate) force the multiplication to be done first. After it is done, the result is converted to characters and appended to the string "pay Amount : ". When you have a calculation as part of a System.out.println() statement, it is a good idea to surround the calculation with parentheses to show that you want it done first. Sometimes this is not necessary, but it does not hurt, and makes the program more readable. QUESTION 8: Would it be better to write some of those statements on two lines instead one one? Used by permission. Page 13 of 44
14 Yes. Several Lines per Statement You can use several lines for a statement. Anywhere a space character is OK you can split a statement. This means you can't split a statement in the middle of a name, nor between the quote marks of a string literal, nor in the middle of a numeric literal. Here is the program with some statements correctly put on two lines: Although correct, the division of statements is confusing to humans. It is also true that anywhere one space is OK any number of spaces are OK. Here is a better style for the program: Used by permission. Page 14 of 44
15 It is a good idea to indent the second half of a split statement further than the start of the statement. QUESTION 9: Is the following correct? cla ss Example { public static void main ( String[] args ) { long hoursworked = 40; double payrate = 10.0, taxrate = 0.10; System.out.println("Hours Worked: " + hoursworked ); System.out.println("pay Amount : " + (hours Worked * payrate) ); } } System.out.println("tax Amount : " + ( hoursworked * payrate * taxrate) ); Used by permission. Page 15 of 44
16 No. The incorrect splittings are highlighted in red: cla ss Example { public static void main ( String[] args ) { long hoursworked = 40; double payrate = 10.0, taxrate = 0.10; System.out.println("Hours Worked: " + hoursworked ); System.out.println("pay Amount : " + (hours Worked * payrate) ); System.out.println("tax Amount : " + ( hoursworked * payrate * taxrate) ); } The last statement is correct, although not done in a good style for easy human comprehension. The extra blank lines are OK. Assignment Statements So far, the example programs have been using the value initially put into a variable. Programs can change the value in a variable. An assignment statement changes the value that is held in a variable. Here is a program that uses an assignment statement: The assignment statement puts the value 123 into the variable. In other words, while the program is executing there will be a 64 bit section of memory that holds Used by permission. Page 16 of 44
17 the value 123. Remember that the word "execute" is often used to mean "run". You speak of "executing a program" or "executing" a line of the program. QUESTION 10: What does the program print to the monitor? Used by permission. Page 17 of 44
18 The variable contains: 123 The program prints out the same thing as the first example program. However, this program did not initialize the variable and so had to put a value into it later. Assignment Statement Syntax Assignment statements look like this: variablename = expression ; The equal sign = is the assignment operator. variablename is the name of a variable that has been declared previously in the program. expression is a collection of characters that calls for a value. Here are some example assignment statements (assume that the variables have already been declared): total = 3 + 5; price = 34.56; tax = total*0.05; In the source file, the variable must be declared before any assignment statement that uses that variable. QUESTION 11: Is the following correct? int sum; sum = ; Used by permission. Page 18 of 44
19 Yes, the statements are syntactically correct. Assignment Statement Semantics The syntax of a programming language says what programs look like. It is the grammar of how to arrange the symbols. The semantics of a programming language says what the program does as it executes. It says what the symbols mean. This page explains the semantics of the assignment statement. An assignment statement does its work in two steps: First, do the calculation on the RIGHT of the equal sign. If there is nothing to calculate, use the value on the right. Next, replace the contents of the variable to the LEFT of the equal sign with the result of the calculation. For example: total = 3 + 5; Do the calculation 3+5 to get 8. Put 8 in the variable named total. It does not matter if total already has a number in it. Step 2 will replace whatever is already in total. For example: points = 23; Use the value 23. Put 23 in the variable named points. QUESTION 12: What happens FIRST when the following statement executes? value = 2*3 ; Used by permission. Page 19 of 44
20 FIRST, do the multiplication 2*3 to get the value 6. Two Steps FIRST, do the multiplication 2*3 to get the value 6. NEXT, put the result of the calculation into the "litte box of memory" used for the variable value: It will really, really help you to think carefully about these two steps. Sometimes even second year computer science majors get confused about this and write buggy code. QUESTION 13: What will this program fragment write? value = 2*3; System.out.println( "value holds: " + value ); Used by permission. Page 20 of 44
21 value holds: 6 More Practice Here is another program fragment: int extra; extra = 5; The assignment statement is correct. It matches the syntax: variablename = expression; The expression is the literal 5. No calculation needs to be done. But the assignment statement still takes two steps. FIRST, get the 5: NEXT, put the 5 in the variable: QUESTION 14: What does the following fragment write? int quantity = 7; quantity = 13; System.out.println( "quantity holds: " + quantity ); Used by permission. Page 21 of 44
22 quantity holds: 13 The assignment statement replaced the value that was originally in quantity with the value 13. Adding a Number to a Variable Assume that extra already contains the value 5. Here is another statement: value = extra + 2; The statement will be performed in two steps (as always). The first step performs the calculation extra + 2 by first copying the 5 from extra, and then adding 2 to it: The result of the calculation is 7. The second step puts 7 into the variable value: Used by permission. Page 22 of 44
23 QUESTION 15: What will the following program print out: // Example assignment statements int extra, value; extra = 5; value = extra + 2; System.out.println( "value now holds: " + value ); Used by permission. Page 23 of 44
24 The program will print out: value now holds: 7 Same Variable Twice in an Assignment Statement Look at the statements: value = 5; value = 12 + value; Assume that value has already been declared. The two statements execute one after the other, and each statement performs two steps. The first statement: Gets the number on the RIGHT of the equal sign: 5 Puts the 5 in the variable called value. Used by permission. Page 24 of 44
25 The second statement: Does the calculation on the RIGHT of the equal sign: 12 + value. Look into the variable value to get the number 5. Perform the sum: to get 17 Look on the LEFT of the equal sign to see where to put the result. Put the 17 in the variable value. Note: A variable can be used on both the LEFT and the RIGHT of the = in the same assignment statement. When it is used on the right, it provides a number used to calculate a value. When it is used on the left, it says where in memory to save that value. The two roles are in separate steps, so they don't interfere with each other. Step 1 uses the original value in the variable. Then step 2 puts the new value (from the calculation) into the variable. QUESTION 16: Used by permission. Page 25 of 44
26 What does the following program fragment write? value = 5; System.out.println("value is: " + value ); value = value + 10; System.out.println("value is: " + value ); Used by permission. Page 26 of 44
27 The program will print out: value is: 5 value is: 15 A Sequence that Counts Look at this program fragment: Here is how the program works: 1. Statement 1 puts 0 into count. 2. Statement 2 writes out the 0 in count. 3. Statement 3 first gets the 0 from count, adds 1 to it, and puts the result back in count. 4. Statement 4 writes out the 1 that is now in count. When the fragment runs, it writes: 0 1 QUESTION 17: Think of a way to write 0, 1, and 2. Used by permission. Page 27 of 44
28 Put a copy of statements 3 and 4 at the end. Counting Higher The following fragment: prints out The statement count = count + 1; increments the number in count. Sometimes programmers call this "incrementing a variable" although (of course) it is really the number in the variable that is incremented. QUESTION 18: What does the following assignment statement do: sum = 2*sum ; (What are the two steps, in order?) Used by permission. Page 28 of 44
29 Evaluate the expression: get the value in sum and multiply it by two. Then, put that value into sum. Expressions Sometimes you need to think carefully about the two steps of an assignment statement. The first step is to evaluate the expression on the right of the assignment operator. An expression is a combination of literals, operators, variable names, and parentheses used to calculate a value. This (slighly incomplete) definition needs some explanation: literal characters that directly give you a value, like: operator a symbol like plus + or times * that asks for an arithmetic operation. variable a section of memory containing a value. parentheses ( and ). This might sound awful. Actually, this is stuff that you know from algebra, like: (32 - y) / ( x + 5 ) In the above, the character / means division. Not just any mess of symbols will work. The following 32 - y) / ( x 5 + ) is not a syntactically correct expression. There are rules for this, but the best rule is that an expression must look OK as algebra. However, multiplication must always be shown by using a * operator. You can't multiply two variables by placing them next to each other. So, although xy might be correct in algebra, you must use x*y in Java. QUESTION 19: Which of the following expressions are correct? (Assume that the variables have been properly declared elsewhere.) Used by permission. Page 29 of 44
30 Expression ) x + 34 *z 99 sum value + Correct or Not? Correct NOT Correct Correct NOT Correct Correct More Practice Let's try some more. Again, assume that all the variables have been correctly declared. Used by permission. Page 30 of 44
31 QUESTION 20: Why is the last expression not correct? Used by permission. Page 31 of 44
32 Multiplication must be shown with a * operator. (Another answer is that 3.14y is not a correct variable name.) Spaces Don't Much Matter An expression can be written without using any spaces. Operators and parentheses are enough to separate the parts of an expression. You can use one or more spaces in an expression to visually separate the parts without changing the meaning. For example, the following is a correct expression: (hoursworked*payrate)-deduction The following means exactly the same: (hoursworked * payrate) - deduction Use spaces wisely to make it clear what the expression means. By making things clear, you might save yourself hours of debugging. Spaces can't be placed in the middle of identifiers. The following is NOT correct: ( hours Worked * pay Rate) -deduction It is possible (but unwise) to be deceptive with spaces. For example, in the following: 12-4 / 2+2 it looks as if 4 is subtracted from 12, and then that the result, 8, is divided by 4. However, the spaces don't count, and the expression is the same as: 12-4/2 + 2 This arrangement of spaces makes it clear what the expression means. QUESTION 21: Based on what you know about algebra, what is the value of this expression: 12-4/2 + 2 Used by permission. Page 32 of 44
33 12, since the expression means: Arithmetic Operators An arithmetic operator is a symbol that asks for doing some arithmetic. As the previous question illustrates, if several operators are used in an expression, the operations are done in a specific order. Operators of higher precedence are done first. The table shows the precedence of some Java operators. Some operators have equal precedence. For example, addition + and subtraction - have the same precedence. The unary minus and unary plus operators are used as part of a negative or a positive number. For example, -23 means negative twenty-three and +23 means positive twenty-three. More on this later. When both operands (the numbers) are integers, these operators do integer arithmetic. If one operand or both operands are floating point, then these operators do floating point arithmetic. This is especially important to remember with division, because the result of integer division is an integer. For example: 5/2 is 2 (not 2.5) 5/10 is 0 (not 0.5). More on this later. QUESTION 22:What is the value of the following expressions? In each expression, do the highest precedence operator first. Used by permission. Page 33 of 44
34 Used by permission. Page 34 of 44
35 The last result is correct. First 6/8 is done using integer division, resulting in 0. Then that 0 is added to 2. Evaluation by Rewriting When evaluating an expression, it can be helpful to do it one step at a time and to rewrite the expression after each step. Look at: / 4 Do the division first, since it has highest precedence. Next, rewrite the expression replacing the division with its value: 16-3 Now evaluate the resulting expression: 13 You can write the process like this: / The dashed lines show what was done at each step. QUESTION 23: What is the value of the following expression? 24 / 2-8 Used by permission. Page 35 of 44
36 24 / Evaluate Equal Precedence from Left to Right When there are two (or more) operators of equal precedence, evaluate the expression from left to right. 2 * 7 * * Since both operators are *, each has equal precidence, so calculate 2 * 7 first, then use that result with the second operator Here the operators are different, but they both have the same precidence, so they are evaluated left to right. Usually it doesn't matter if evaluation is done left to right or in any other order. In algebra it makes no difference. But with floating point math it sometimes makes an important difference. Also, when an expression uses a method it can make a very big difference. (Methods are discussed in part 6 of these notes.) Used by permission. Page 36 of 44
37 QUESTION 24: What is the value of the following expression? 2 + 4/2 + 1 Used by permission. Page 37 of 44
38 2 + 4/ Unary Minus If you look in the table of operators you will see that the character - is listed twice. That is because - is used for two purposes. In some contexts, - is the unary minus operator. In other contexts, - is the subtraction operator. The unary minus is used to show a negative number. For example: means "negative ninety seven point thirty four." The subtraction operator is used to show a subtraction of one number from another. For example: asks for 12 to be subtracted from 95. The unary minus operator has high precedence. Addition and subtraction have low precedence. For example means add 3 to negative 12 (resulting in -9). The unary minus is done first, so it applies only to the twelve. unary plus + can be applied to a number to show that it is positive. It also has high precedence. It is rarely used. QUESTION 25: What is the value of the following expression? * -4 Used by permission. Page 38 of 44
39 * The first + is a unary plus, so it has high precidence and applies only to the 24. The - is a unary minus, so it applies only to the 4. Next in order of precidence is the *, so three times negative four is calculated yielding negative twelve. Finally the low precidence + combines the postive twenty four with the negative twelve. Arrange what you want with Parentheses To say exactly what numbers go with each operator, use parentheses. For example -1 * ( 9-2 ) * 3 means do 9-2 first. The "( )" groups together what you want done first. After doing the subtraction, the ( 9-2 ) becomes a 7: -1 * 7 * 3 Now follow the left-to-right rule for operators of equal precedence: -1 * 7 * * QUESTION 26: What is the value of each of the following expressions? Used by permission. Page 39 of 44
40 Used by permission. Page 40 of 44
41 Extra Parentheses Notice that the last expression (above) did not need parentheses. It does not hurt to use parentheses that are not needed. For example, all of the following are equivalent: Warning! Look out for division. The / operator is a constant source of bugs! Parentheses will help. QUESTION 27: What is the value of each of the following expressions? Used by permission. Page 41 of 44
42 The last answer is correct. It is done like this: / (2 + 3 ) / /5 is 0 with integer division. Nested Parentheses Sometimes in a complicated expression one set of parentheses is not enough. In that case use several nested sets to show what you want. The rule is: The innermost set of parentheses is evaluated first. Start evaluating at the most deeply nested set of parentheses, and then work outward until there are no parentheses left. If there are several sets of parentheses at the same level, evaluate them left to right. For example: Used by permission. Page 42 of 44
43 Ordinarily you would not do this in such detail. QUESTION 28: What is the value of this expression: (12 / 4 ) + ( 12 / 3) Used by permission. Page 43 of 44
44 7 End of the Chapter Here is a list of subjects you may wish to review. Click on a high precedence subject to go to where it was discussed. What variables are. Declaring variables. Syntax of declaring variables. Names for variables. Reserved words. Assignment statements Semantics Expressions. Table of operators and their precedence. How parentheses change the order of evaluation. The next chapter will continue with arithmetic expressions. Used by permission. Page 44 of 44
Chapter 2: Elements of Java
Chapter 2: Elements of Java Basic components of a Java program Primitive data types Arithmetic expressions Type casting. The String type (introduction) Basic I/O statements Importing packages. 1 Introduction
More informationName: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.
Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to
More informationIntroduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved.
1 2 Introduction to Java Applications 2.2 First Program in Java: Printing a Line of Text 2 Application Executes when you use the java command to launch the Java Virtual Machine (JVM) Sample program Displays
More informationMoving from CS 61A Scheme to CS 61B Java
Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you
More informationJava Basics: Data Types, Variables, and Loops
Java Basics: Data Types, Variables, and Loops If debugging is the process of removing software bugs, then programming must be the process of putting them in. - Edsger Dijkstra Plan for the Day Variables
More informationChapter 14: Boolean Expressions Bradley Kjell (Revised 10/08/08)
Chapter 14: Boolean Expressions Bradley Kjell (Revised 10/08/08) The if statements of the previous chapters ask simple questions such as count
More informationHandout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.
Handout 1 CS603 Object-Oriented Programming Fall 15 Page 1 of 11 Handout 1 Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Java
More information1.6 The Order of Operations
1.6 The Order of Operations Contents: Operations Grouping Symbols The Order of Operations Exponents and Negative Numbers Negative Square Roots Square Root of a Negative Number Order of Operations and Negative
More informationJava CPD (I) Frans Coenen Department of Computer Science
Java CPD (I) Frans Coenen Department of Computer Science Content Session 1, 12:45-14:30 (First Java Programme, Inheritance, Arithmetic) Session 2, 14:45-16:45 (Input and Programme Constructs) Materials
More informationTopics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:
Introduction to Programming and Algorithms Module 2 CS 146 Sam Houston State University Dr. Tim McGuire Introduction To Computers And Java Chapter Objectives To understand: the meaning and placement of
More informationLab Experience 17. Programming Language Translation
Lab Experience 17 Programming Language Translation Objectives Gain insight into the translation process for converting one virtual machine to another See the process by which an assembler translates assembly
More informationCS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013
Oct 4, 2013, p 1 Name: CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 1. (max 18) 4. (max 16) 2. (max 12) 5. (max 12) 3. (max 24) 6. (max 18) Total: (max 100)
More informationBase Conversion written by Cathy Saxton
Base Conversion written by Cathy Saxton 1. Base 10 In base 10, the digits, from right to left, specify the 1 s, 10 s, 100 s, 1000 s, etc. These are powers of 10 (10 x ): 10 0 = 1, 10 1 = 10, 10 2 = 100,
More information1 Description of The Simpletron
Simulating The Simpletron Computer 50 points 1 Description of The Simpletron In this assignment you will write a program to simulate a fictional computer that we will call the Simpletron. As its name implies
More informationSection 1.5 Exponents, Square Roots, and the Order of Operations
Section 1.5 Exponents, Square Roots, and the Order of Operations Objectives In this section, you will learn to: To successfully complete this section, you need to understand: Identify perfect squares.
More informationChapter One Introduction to Programming
Chapter One Introduction to Programming 1-1 Algorithm and Flowchart Algorithm is a step-by-step procedure for calculation. More precisely, algorithm is an effective method expressed as a finite list of
More informationBachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)
Unit- I Introduction to c Language: C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating
More informationJava Interview Questions and Answers
1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java
More informationOrder of Operations More Essential Practice
Order of Operations More Essential Practice We will be simplifying expressions using the order of operations in this section. Automatic Skill: Order of operations needs to become an automatic skill. Failure
More informationExample of a Java program
Example of a Java program class SomeNumbers static int square (int x) return x*x; public static void main (String[] args) int n=20; if (args.length > 0) // change default n = Integer.parseInt(args[0]);
More informationCS 106 Introduction to Computer Science I
CS 106 Introduction to Computer Science I 01 / 21 / 2014 Instructor: Michael Eckmann Today s Topics Introduction Homework assignment Review the syllabus Review the policies on academic dishonesty and improper
More informationCSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals
CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals 1 Recall From Last Time: Java Program import java.util.scanner; public class EggBasket { public static void main(string[]
More informationKeywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void
1. Explain C tokens Tokens are basic building blocks of a C program. A token is the smallest element of a C program that is meaningful to the compiler. The C compiler recognizes the following kinds of
More informationVariables, Constants, and Data Types
Variables, Constants, and Data Types Primitive Data Types Variables, Initialization, and Assignment Constants Characters Strings Reading for this class: L&L, 2.1-2.3, App C 1 Primitive Data There are eight
More informationPart 1 Expressions, Equations, and Inequalities: Simplifying and Solving
Section 7 Algebraic Manipulations and Solving Part 1 Expressions, Equations, and Inequalities: Simplifying and Solving Before launching into the mathematics, let s take a moment to talk about the words
More informationOperations with positive and negative numbers - see first chapter below. Rules related to working with fractions - see second chapter below
INTRODUCTION If you are uncomfortable with the math required to solve the word problems in this class, we strongly encourage you to take a day to look through the following links and notes. Some of them
More informationActivity 1: Using base ten blocks to model operations on decimals
Rational Numbers 9: Decimal Form of Rational Numbers Objectives To use base ten blocks to model operations on decimal numbers To review the algorithms for addition, subtraction, multiplication and division
More informationSAT Math Facts & Formulas Review Quiz
Test your knowledge of SAT math facts, formulas, and vocabulary with the following quiz. Some questions are more challenging, just like a few of the questions that you ll encounter on the SAT; these questions
More informationIntroduction to Python
Caltech/LEAD Summer 2012 Computer Science Lecture 2: July 10, 2012 Introduction to Python The Python shell Outline Python as a calculator Arithmetic expressions Operator precedence Variables and assignment
More informationarrays C Programming Language - Arrays
arrays So far, we have been using only scalar variables scalar meaning a variable with a single value But many things require a set of related values coordinates or vectors require 3 (or 2, or 4, or more)
More informationIn this Chapter you ll learn:
Now go, write it before them in a table, and note it in a book. Isaiah 30:8 To go beyond is as wrong as to fall short. Confucius Begin at the beginning, and go on till you come to the end: then stop. Lewis
More informationWe will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.
LING115 Lecture Note Session #4 Python (1) 1. Introduction As we have seen in previous sessions, we can use Linux shell commands to do simple text processing. We now know, for example, how to count words.
More informationEmbedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C
Embedded Systems A Review of ANSI C and Considerations for Embedded C Programming Dr. Jeff Jackson Lecture 2-1 Review of ANSI C Topics Basic features of C C fundamentals Basic data types Expressions Selection
More informationJavaScript: Introduction to Scripting. 2008 Pearson Education, Inc. All rights reserved.
1 6 JavaScript: Introduction to Scripting 2 Comment is free, but facts are sacred. C. P. Scott The creditor hath a better memory than the debtor. James Howell When faced with a decision, I always ask,
More informationPre-Algebra Lecture 6
Pre-Algebra Lecture 6 Today we will discuss Decimals and Percentages. Outline: 1. Decimals 2. Ordering Decimals 3. Rounding Decimals 4. Adding and subtracting Decimals 5. Multiplying and Dividing Decimals
More informationChapter 3. Input and output. 3.1 The System class
Chapter 3 Input and output The programs we ve looked at so far just display messages, which doesn t involve a lot of real computation. This chapter will show you how to read input from the keyboard, use
More information0.8 Rational Expressions and Equations
96 Prerequisites 0.8 Rational Expressions and Equations We now turn our attention to rational expressions - that is, algebraic fractions - and equations which contain them. The reader is encouraged to
More informationComputer Science 281 Binary and Hexadecimal Review
Computer Science 281 Binary and Hexadecimal Review 1 The Binary Number System Computers store everything, both instructions and data, by using many, many transistors, each of which can be in one of two
More informationSection 4.1 Rules of Exponents
Section 4.1 Rules of Exponents THE MEANING OF THE EXPONENT The exponent is an abbreviation for repeated multiplication. The repeated number is called a factor. x n means n factors of x. The exponent tells
More informationFirst Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science
First Java Programs V. Paúl Pauca Department of Computer Science Wake Forest University CSC 111D Fall, 2015 Hello World revisited / 8/23/15 The f i r s t o b l i g a t o r y Java program @author Paul Pauca
More informationMULTIPLICATION AND DIVISION OF REAL NUMBERS In this section we will complete the study of the four basic operations with real numbers.
1.4 Multiplication and (1-25) 25 In this section Multiplication of Real Numbers Division by Zero helpful hint The product of two numbers with like signs is positive, but the product of three numbers with
More informationComp 255Q - 1M: Computer Organization Lab #3 - Machine Language Programs for the PDP-8
Comp 255Q - 1M: Computer Organization Lab #3 - Machine Language Programs for the PDP-8 January 22, 2013 Name: Grade /10 Introduction: In this lab you will write, test, and execute a number of simple PDP-8
More informationVHDL Test Bench Tutorial
University of Pennsylvania Department of Electrical and Systems Engineering ESE171 - Digital Design Laboratory VHDL Test Bench Tutorial Purpose The goal of this tutorial is to demonstrate how to automate
More informationBinary Adders: Half Adders and Full Adders
Binary Adders: Half Adders and Full Adders In this set of slides, we present the two basic types of adders: 1. Half adders, and 2. Full adders. Each type of adder functions to add two binary bits. In order
More informationClick on the links below to jump directly to the relevant section
Click on the links below to jump directly to the relevant section What is algebra? Operations with algebraic terms Mathematical properties of real numbers Order of operations What is Algebra? Algebra is
More informationDebugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go
Debugging ESE112 Java Programming: API, Psuedo-Code, Scope It is highly unlikely that you will write code that will work on the first go Bugs or errors Syntax Fixable if you learn to read compiler error
More informationDirect Translation is the process of translating English words and phrases into numbers, mathematical symbols, expressions, and equations.
Section 1 Mathematics has a language all its own. In order to be able to solve many types of word problems, we need to be able to translate the English Language into Math Language. is the process of translating
More informationClasses and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:
In creating objects of the type, we have used statements similar to the following: f = new (); The parentheses in the expression () makes it look like a method, yet we never created such a method in our
More informationPAYCHEX, INC. BASIC BUSINESS MATH TRAINING MODULE
PAYCHEX, INC. BASIC BUSINESS MATH TRAINING MODULE 1 Property of Paychex, Inc. Basic Business Math Table of Contents Overview...3 Objectives...3 Calculator...4 Basic Calculations...6 Order of Operation...9
More informationChapter 1 Java Program Design and Development
presentation slides for JAVA, JAVA, JAVA Object-Oriented Problem Solving Third Edition Ralph Morelli Ralph Walde Trinity College Hartford, CT published by Prentice Hall Java, Java, Java Object Oriented
More informationMultiplication Rules! Tips to help your child learn their times tables
Multiplication Rules! Tips to help your child learn their times tables 1. Have fun! We want relaxed kids and plenty of giggles. 2. Go slowly and relax. 3. Do the preliminary review, all the preliminary
More informationIntroduction to Java. CS 3: Computer Programming in Java
Introduction to Java CS 3: Computer Programming in Java Objectives Begin with primitive data types Create a main class with helper methods Learn how to call built-in class methods and instance methods
More informationPREPARATION FOR MATH TESTING at CityLab Academy
PREPARATION FOR MATH TESTING at CityLab Academy compiled by Gloria Vachino, M.S. Refresh your math skills with a MATH REVIEW and find out if you are ready for the math entrance test by taking a PRE-TEST
More informationSome Scanner Class Methods
Keyboard Input Scanner, Documentation, Style Java 5.0 has reasonable facilities for handling keyboard input. These facilities are provided by the Scanner class in the java.util package. A package is a
More informationChapter 5 Names, Bindings, Type Checking, and Scopes
Chapter 5 Names, Bindings, Type Checking, and Scopes Chapter 5 Topics Introduction Names Variables The Concept of Binding Type Checking Strong Typing Scope Scope and Lifetime Referencing Environments Named
More informationChapter 2 Elementary Programming
Chapter 2 Elementary Programming 2.1 Introduction You will learn elementary programming using Java primitive data types and related subjects, such as variables, constants, operators, expressions, and input
More informationVB.NET Programming Fundamentals
Chapter 3 Objectives Programming Fundamentals In this chapter, you will: Learn about the programming language Write a module definition Use variables and data types Compute with Write decision-making statements
More informationSources: On the Web: Slides will be available on:
C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,
More informationSection 1.4 Place Value Systems of Numeration in Other Bases
Section.4 Place Value Systems of Numeration in Other Bases Other Bases The Hindu-Arabic system that is used in most of the world today is a positional value system with a base of ten. The simplest reason
More information2.6 Exponents and Order of Operations
2.6 Exponents and Order of Operations We begin this section with exponents applied to negative numbers. The idea of applying an exponent to a negative number is identical to that of a positive number (repeated
More informationNumbering Systems. InThisAppendix...
G InThisAppendix... Introduction Binary Numbering System Hexadecimal Numbering System Octal Numbering System Binary Coded Decimal (BCD) Numbering System Real (Floating Point) Numbering System BCD/Binary/Decimal/Hex/Octal
More informationEncoding Text with a Small Alphabet
Chapter 2 Encoding Text with a Small Alphabet Given the nature of the Internet, we can break the process of understanding how information is transmitted into two components. First, we have to figure out
More informationIntroduction to Python
WEEK ONE Introduction to Python Python is such a simple language to learn that we can throw away the manual and start with an example. Traditionally, the first program to write in any programming language
More informationChapter 2 Introduction to Java programming
Chapter 2 Introduction to Java programming 1 Keywords boolean if interface class true char else package volatile false byte final switch while throws float private case return native void protected break
More informationTraining Manual. Pre-Employment Math. Version 1.1
Training Manual Pre-Employment Math Version 1.1 Created April 2012 1 Table of Contents Item # Training Topic Page # 1. Operations with Whole Numbers... 3 2. Operations with Decimal Numbers... 4 3. Operations
More informationChapter 7D The Java Virtual Machine
This sub chapter discusses another architecture, that of the JVM (Java Virtual Machine). In general, a VM (Virtual Machine) is a hypothetical machine (implemented in either hardware or software) that directly
More informationA single register, called the accumulator, stores the. operand before the operation, and stores the result. Add y # add y from memory to the acc
Other architectures Example. Accumulator-based machines A single register, called the accumulator, stores the operand before the operation, and stores the result after the operation. Load x # into acc
More informationJAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.
http://www.tutorialspoint.com/java/java_quick_guide.htm JAVA - QUICK GUIDE Copyright tutorialspoint.com What is Java? Java is: Object Oriented Platform independent: Simple Secure Architectural- neutral
More informationIP Subnetting: Practical Subnet Design and Address Determination Example
IP Subnetting: Practical Subnet Design and Address Determination Example When educators ask students what they consider to be the most confusing aspect in learning about networking, many say that it is
More informationALGEBRA. sequence, term, nth term, consecutive, rule, relationship, generate, predict, continue increase, decrease finite, infinite
ALGEBRA Pupils should be taught to: Generate and describe sequences As outcomes, Year 7 pupils should, for example: Use, read and write, spelling correctly: sequence, term, nth term, consecutive, rule,
More informationLab 4.4 Secret Messages: Indexing, Arrays, and Iteration
Lab 4.4 Secret Messages: Indexing, Arrays, and Iteration This JavaScript lab (the last of the series) focuses on indexing, arrays, and iteration, but it also provides another context for practicing with
More informationSession 29 Scientific Notation and Laws of Exponents. If you have ever taken a Chemistry class, you may have encountered the following numbers:
Session 9 Scientific Notation and Laws of Exponents If you have ever taken a Chemistry class, you may have encountered the following numbers: There are approximately 60,4,79,00,000,000,000,000 molecules
More informationOct: 50 8 = 6 (r = 2) 6 8 = 0 (r = 6) Writing the remainders in reverse order we get: (50) 10 = (62) 8
ECE Department Summer LECTURE #5: Number Systems EEL : Digital Logic and Computer Systems Based on lecture notes by Dr. Eric M. Schwartz Decimal Number System: -Our standard number system is base, also
More informationVisual Logic Instructions and Assignments
Visual Logic Instructions and Assignments Visual Logic can be installed from the CD that accompanies our textbook. It is a nifty tool for creating program flowcharts, but that is only half of the story.
More informationA PRACTICAL GUIDE TO db CALCULATIONS
A PRACTICAL GUIDE TO db CALCULATIONS This is a practical guide to doing db (decibel) calculations, covering most common audio situations. You see db numbers all the time in audio. You may understand that
More informationIntroduction to Java
Introduction to Java The HelloWorld program Primitive data types Assignment and arithmetic operations User input Conditional statements Looping Arrays CSA0011 Matthew Xuereb 2008 1 Java Overview A high
More information1.00/1.001 - Session 2 Fall 2004. Basic Java Data Types, Control Structures. Java Data Types. 8 primitive or built-in data types
1.00/1.001 - Session 2 Fall 2004 Basic Java Data Types, Control Structures Java Data Types 8 primitive or built-in data types 4 integer types (byte, short, int, long) 2 floating point types (float, double)
More informationCommon Beginner C++ Programming Mistakes
Common Beginner C++ Programming Mistakes This documents some common C++ mistakes that beginning programmers make. These errors are two types: Syntax errors these are detected at compile time and you won't
More informationInstall Java Development Kit (JDK) 1.8 http://www.oracle.com/technetwork/java/javase/downloads/index.html
CS 259: Data Structures with Java Hello World with the IntelliJ IDE Instructor: Joel Castellanos e-mail: joel.unm.edu Web: http://cs.unm.edu/~joel/ Office: Farris Engineering Center 319 8/19/2015 Install
More informationPL / SQL Basics. Chapter 3
PL / SQL Basics Chapter 3 PL / SQL Basics PL / SQL block Lexical units Variable declarations PL / SQL types Expressions and operators PL / SQL control structures PL / SQL style guide 2 PL / SQL Block Basic
More informationThis Unit: Floating Point Arithmetic. CIS 371 Computer Organization and Design. Readings. Floating Point (FP) Numbers
This Unit: Floating Point Arithmetic CIS 371 Computer Organization and Design Unit 7: Floating Point App App App System software Mem CPU I/O Formats Precision and range IEEE 754 standard Operations Addition
More informationSemantic Analysis: Types and Type Checking
Semantic Analysis Semantic Analysis: Types and Type Checking CS 471 October 10, 2007 Source code Lexical Analysis tokens Syntactic Analysis AST Semantic Analysis AST Intermediate Code Gen lexical errors
More informationwhat operations can it perform? how does it perform them? on what kind of data? where are instructions and data stored?
Inside the CPU how does the CPU work? what operations can it perform? how does it perform them? on what kind of data? where are instructions and data stored? some short, boring programs to illustrate the
More informationObject Oriented Software Design
Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 28, 2010 G. Lipari (Scuola Superiore Sant Anna) Introduction
More informationCAHSEE on Target UC Davis, School and University Partnerships
UC Davis, School and University Partnerships CAHSEE on Target Mathematics Curriculum Published by The University of California, Davis, School/University Partnerships Program 006 Director Sarah R. Martinez,
More informationPart I. The Picture class
CS 161 LAB 5 This lab will have two parts. In the first part, we will create a class to automate the drawing of the robot from the second lab. For the second part, we will begin a ClunkyCalculator class
More informationNumber Representation
Number Representation CS10001: Programming & Data Structures Pallab Dasgupta Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur Topics to be Discussed How are numeric data
More informationOutline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators
Conditional Statements For computer to make decisions, must be able to test CONDITIONS IF it is raining THEN I will not go outside IF Count is not zero THEN the Average is Sum divided by Count Conditions
More informationJ a v a Quiz (Unit 3, Test 0 Practice)
Computer Science S-111a: Intensive Introduction to Computer Science Using Java Handout #11 Your Name Teaching Fellow J a v a Quiz (Unit 3, Test 0 Practice) Multiple-choice questions are worth 2 points
More information1 Abstract Data Types Information Hiding
1 1 Abstract Data Types Information Hiding 1.1 Data Types Data types are an integral part of every programming language. ANSI-C has int, double and char to name just a few. Programmers are rarely content
More informationTo convert an arbitrary power of 2 into its English equivalent, remember the rules of exponential arithmetic:
Binary Numbers In computer science we deal almost exclusively with binary numbers. it will be very helpful to memorize some binary constants and their decimal and English equivalents. By English equivalents
More information26 Integers: Multiplication, Division, and Order
26 Integers: Multiplication, Division, and Order Integer multiplication and division are extensions of whole number multiplication and division. In multiplying and dividing integers, the one new issue
More informationLecture 5: Java Fundamentals III
Lecture 5: Java Fundamentals III School of Science and Technology The University of New England Trimester 2 2015 Lecture 5: Java Fundamentals III - Operators Reading: Finish reading Chapter 2 of the 2nd
More informationFinancial Mathematics
Financial Mathematics For the next few weeks we will study the mathematics of finance. Apart from basic arithmetic, financial mathematics is probably the most practical math you will learn. practical in
More informationSYSTEMS OF EQUATIONS AND MATRICES WITH THE TI-89. by Joseph Collison
SYSTEMS OF EQUATIONS AND MATRICES WITH THE TI-89 by Joseph Collison Copyright 2000 by Joseph Collison All rights reserved Reproduction or translation of any part of this work beyond that permitted by Sections
More informationYOU MUST BE ABLE TO DO THE FOLLOWING PROBLEMS WITHOUT A CALCULATOR!
DETAILED SOLUTIONS AND CONCEPTS - DECIMALS AND WHOLE NUMBERS Prepared by Ingrid Stewart, Ph.D., College of Southern Nevada Please Send Questions and Comments to ingrid.stewart@csn.edu. Thank you! YOU MUST
More informationThe Hexadecimal Number System and Memory Addressing
APPENDIX C The Hexadecimal Number System and Memory Addressing U nderstanding the number system and the coding system that computers use to store data and communicate with each other is fundamental to
More information6 3 4 9 = 6 10 + 3 10 + 4 10 + 9 10
Lesson The Binary Number System. Why Binary? The number system that you are familiar with, that you use every day, is the decimal number system, also commonly referred to as the base- system. When you
More informationUdacity cs101: Building a Search Engine. Extracting a Link
Udacity cs101: Building a Search Engine Unit 1: How to get started: your first program Extracting a Link Introducing the Web Crawler (Video: Web Crawler)... 2 Quiz (Video: First Quiz)...2 Programming (Video:
More informationIntegers are positive and negative whole numbers, that is they are; {... 3, 2, 1,0,1,2,3...}. The dots mean they continue in that pattern.
INTEGERS Integers are positive and negative whole numbers, that is they are; {... 3, 2, 1,0,1,2,3...}. The dots mean they continue in that pattern. Like all number sets, integers were invented to describe
More information