CP1270. Programming Fundamentals
|
|
- Catherine Bishop
- 6 years ago
- Views:
Transcription
1 CP1270 Programming Fundamentals
2 WHO AM I? INSTRUCTOR: Dr. Branko Bronco Cirovic
3 WHERE AM I? OFFICE : ET338 PHONE : branko.cirovic@cna.nl.ca WEBSITE(s) :
4 TOPICS Introduction: algorithms and computation Java language, compiler, virtual machine, I/O Java: variables, types, assignment statement and arithmetic Java: decision making - if, if else and switch controls Java: iteration ( loops ) - while, for, do while Java: methods Java: arrays and strings
5 EVALUATION Labs: 30% Midterm exam: 30% Final exam: 40%
6 PROGRAMMING - WHAT IS IT? Computer Program is a... suitable representation of an Algorithm Algorithm - finite sequence of executable, unambiguous instructions that would ultimately terminate and produce solution to a symbol manipulation problem.
7 ALGORITHMS Do they solve problems of hunger, wars, homelessness, diseases? Didn t think so... So what kind of problems are symbol manipulation problems? Examples: sort unsorted list of integers, reverse a word, find shortest distance between nodes in a graph, determine if bird hit the pig or not etc. Good news: there are infinitely many algorithms - plenty of work for plenty of people for a very long amount of time!
8 EXECUTABLE INSTRUCTIONS? 1 Draw a straight-line segment between two points with coordinates ( 0, 0 ) and ( 1, 3 ) Draw a straight-line segment between two points with coordinates ( 2, 2 ) and ( 4, 0 ) Draw circle with radius 2 and centre at the intersection of previous two line segments?
9 UNAMBIGUOUS INSTRUCTIONS? 1. Set the value of variable n to Execute either step 3 or 4 Which one? 3. Set the value of variable i to 2 4. Skip ahead How far? 5. Divide n by i
10 TERMINATION? 1. Go to ATM machine 2.Withdraw 20 dollars 3. Give money to your instructor 4.Go to step 1
11 JAVA Developed by James Gosling at Sun Microsystems in 1995 General purpose, object-oriented programming language Source code compiles into byte-code Byte-code is then executed by Java Virtual Machine ( JVM ) Advantage: portable to any platform / OS Disadvantage: slower execution
12 JRE Java Runtime Environment Java API classes Java Virtual Machine Operating System ( Windows, Mac, Linux, Unix etc ) Hardware ( Intel, Motorola, Alpha etc )
13 Hello.java public class Hello { public static void main(string[] args) { System.out.println("Hello Java");
14 COMPILE AND RUN In order to compile Hello.java, at command line type: javac Hello.java If you don t have any syntax errors, new file is created in the same directory - Hello.class ( byte-code ). In order to execute it, start JVM by typing at command line: java Hello
15 ANALYSIS - class Hello public class Hello { Any program in Java must be encapsulated in at least one class. Attribute public denotes that class is accessible by anyone. The name of a publicly declared class must be the same as file s prefix - Hello.java Curly braces { denote the body of the class.
16 ANALYSIS - main public static void main(string[] args) { Any stand-alone Java application must have the main method - the entry point of execution. main method is public, i.e. it can be accessed by anyone. main method is static, i.e. it belongs to the class, not to class instance. main method s return type is void, i.e. it does not return any values.
17 ANALYSIS - main main method s argument is array of strings: String[] args. Curly braces { denote the body of the main method. System.out.println("Hello Java"); belongs to the main method - it sends string "Hello Java" to standard output ( screen ).
18 VARIABLES Variable, in computer science, refers to a memory location with associated symbolic name ( identifier ) which contains a value. The value of a variable may change during the program execution. In order to declare a variable in Java, we need to specify variable s data type and identifier.
19 DATA TYPES There are eight primitive data types in Java: Type Description boolean unsigned 8-bit integer ( true / false ) byte signed 8-bit integer char unsigned 16-bit integer ( Unicode ) short signed 16-bit integer int signed 32-bit integer long signed 64-bit integer float 32-bit floating point double 64-bit floating point
20 IDENTIFIERS Legal identifiers in Java are strings ( words ) which must begin with a letter, underscore ( _ ) or a dollar sign ( $ ), followed by any combination of letters, digits, dollar signs and underscores. Identifiers must not be Java reserved words. Java is a case - sensitive language, i.e., x and X represent two different identifiers. Once the variable has been declared, it must not be redeclared.
21 VARIABLE DECLARATION In Java, variables are declared as: <type> <identifier>; Examples of variable declaration: int number; char letter; double real; Once declared, values can be assigned to variables.
22 ASSIGNMENT STATEMENT Assignment statement in Java has the form: <identifier> = <value>; Examples of assignment statement: number = 2; letter = a ; real = ; It is important that types of values coincide with the declared types of variables, i.e., number = 2.5; would result in an error.
23 Assignment.java public class Assignment { public static void main(string[] args) { int number; char letter; double real; number = 2; letter = 'a'; real = ; System.out.println("number: " + number); System.out.println("letter: " + letter); System.out.println("real: " + real);
24 ASSIGNMENT THROUGH INPUT Values can be assigned to declared variables through input ( STDIN - keyboard ) There are many different ways to accomplish this task. Probably the easiest one is to use the Scanner class defined in java.util.* library. Values can be declared and assigned value in a single line, as in int n = 1; or int n = s.nextint(); ( input )
25 Input.java import java.util.*; public class Input { public static void main(string[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter integer: "); int n = s.nextint(); System.out.print("Enter real: "); double d = s.nextdouble(); System.out.print("Enter character: "); char c = s.next().charat(0); System.out.println(n + " " + d + " " + c);
26 TYPECASTING Java promotes higher types to lower types, i.e., double to float, float to int, int to char. ( implicit typecasting ). For example, the value of expression a is Why? Because ASCII value of a is 97! Explicit typecasting : the value of 5 / 2 is 2. On the other hand, the value of (double) 5 / (double) 2 is 2.5
27 ARITHMETIC There are five arithmetic operators in Java: Operation Operator Example Addition Subtraction Multiplication * 5 * 2 Division / 5 / 2 Modulus ( remainder ) % 5 % 2
28 ARITHMETIC Rules of Operator Precedence Operators in expressions contained within pairs of parentheses are evaluated first. Multiplication, Division and Modulus are applied next, evaluated from left to right. Addition and Subtraction are applied last, evaluated from left to right.
29 EXAMPLE Evaluate expression: z = (2 + 5) * 3 / 6 - (5 % 4) z = 7 * 3 / 6-1 ( Parentheses ) z = 21 / 6-1 ( Multiplication, LR ) z = 3-1 ( Division ) z = 2 ( Subtraction )
30 Arithmetic.java import java.util.*; public class Arithmetic { public static void main(string[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter a: "); int a = s.nextint(); System.out.print("Enter b: "); int b = s.nextint(); int sum = a + b; int dif = a - b; int pro = a * b; int quo = a / b; int rem = a % b;
31 Arithmetic.java ctd System.out.println("Sum: " + sum); System.out.println("Difference: " + dif); System.out.println("Product: " + pro); System.out.println("Quotient: " + quo); System.out.println("Reminder: " + rem);
32 JAVA MATH LIBRARY More complex mathematical operations are provided by the Math class. The class provides methods for performing numeric operations such as trigonometric functions, exponential, power, logarithm, square root etc. Class also defines two constants: E = ( the base of natural logarithm ) and PI = ( the ratio of the circumference of a circle to its diameter ).
33 TestMath.java import java.util.*; public class TestMath { public static void main(string[] args) { Scanner s = new Scanner(System.in); int power, base, exp; System.out.print("Enter base: "); base = s.nextint(); System.out.print("Enter exponent: "); exp = s.nextint(); power = Math.pow(base, exp); System.out.println("Power: " + power);
34 DECISION MAKING So far we have learned about variables, types, assignment statement and simple arithmetic. How would one handle problems like: if bird hit the pig and if the pig was the last one, compute score and move to the next level? For this type of problems we need flow control structures ( decision making ) Java has three types of control structures: if, if else and switch
35 THE if STATEMENT In the form of a flowchart, the if statement looks like: true BE false Where BE is a boolean expression, i.e. it can be evaluated to true / false // code So, if BE is evaluated to true, associated code is executed. Otherwise, control is simply passed to the joint.
36 BOOLEAN EXPRESSIONS Named after English mathematician, logician and philosopher, George Boole ( ). They are expressions that can be evaluated to true or false. In Java, Boolean expressions are constructed from variables, constants, relational operators and logical connectives.
37 RELATIONAL OPERATORS Operator Meaning > Greater than < Less than == Equal to!= Not equal to >= Greater than or equal <= Less than or equal
38 LOGICAL CONNECTIVES Connective Meaning! Not && And Or b!b a b a && b a b a b
39 LOGIC Rules of Connective Precedence Connectives in expressions contained within pairs of parentheses are evaluated first. Not connective has the highest precedence and is applied first. Evaluation is from from left to right. And connective is applied next. Or connective has the lowest precedence and is applied last.
40 EXAMPLE Assume a = true, b = false and c = true. Evaluate expression: d =!a && (b c) d =!true && (false true) ( Parentheses, Or ) d =!true && true ( Not ) d = false && true ( And ) d = false
41 if SYNTAX Code associated with if statement consists of a single instruction: if(<boolean Expression>) // instruction; Code associated with if statement consists of multiple instructions: if(<boolean Expression>) { // instruction_1;... // instruction_n;
42 Multiple.java import java.util.*; public class Multiple { public static void main(string[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter n: "); int n = s.nextint(); if(n % 10 == 0) System.out.println(n + " is multiple of 10");
43 THE if else STATEMENT if else is similar to plain if statement: true // code A BE false // code B The difference is that, if Boolean expression is evaluated to false, different code is executed ( code B ).
44 if else SYNTAX Code associated with if / else statement consists of a single instruction: if(<boolean Expression>) // instruction_a; else // instruction_b;
45 if else SYNTAX Code associated with if /else statement consists of multiple instructions: if(<boolean Expression>) { // instruction_a1;... // instruction_an; else { // instruction_b1;... // instruction_bn;
46 Multiple.java import java.util.*; public class Multiple { public static void main(string[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter n: "); int n = s.nextint(); if(n % 10 == 0) System.out.println(n + " is multiple of 10"); else System.out.println(n + " is not multiple of 10");
47 NESTED if else true n<0 false negative true n>0 false positive zero
48 Vowels.java import java.util.*; public class Vowels { public static void main(string[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter letter: "); char c = s.next().charat(0); if(c == 'a') System.out.println(c + " is a vowel."); else if(c == 'e') System.out.println(c + " is a vowel.");
49 Vowels.java ctd else if(c == 'i') System.out.println(c + " is a vowel."); else if(c == 'o') System.out.println(c + " is a vowel."); else if(c == 'u') System.out.println(c + " is a vowel."); else System.out.println(c + " is not a vowel.");
50 switch CONTROL A sequence of nested if - else statements that compares a single enumerated value ( byte, short, char, int, String ) against several constant alternatives can be implemented as a switch statement: switch(n) { case 1 : // code; break; case 2 : // code; break;... case n : // code; break; default : // code; break;
51 Vowels.java import java.util.*; public class Vowels { public static void main(string[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter letter: "); char c = s.next().charat(0); switch(c) { case 'a' : System.out.println("Vowel"); break; case 'e' : System.out.println("Vowel"); break; case 'i' : System.out.println("Vowel"); break; case 'o' : System.out.println("Vowel"); break; case 'u' : System.out.println("Vowel"); break; default : System.out.println("Not a vowel"); break;
52 ITERATION ( LOOPS ) When you Google something, how many results do you get? Well, that depends on what we are looking for: qeqwddfd 13!!! dfg $%#^&* -+=kk - did not match any documents www - About 25,270,000,000 results (0.25 seconds)
53 ITERATION ( LOOPS ) So far, our computations took constant number of steps to produce results, no matter what the size of the input was. Many times, the number of steps required to carry out computation is not constant - it depends on the size of input. Because of this, we need iterative structures ( loops ) - while, for and do while.
54 while LOOP BE true // code false In the form of a flowchart, the while loop looks like: As long as boolean expression is evaluated to true, body of the loop is executed. Once this condition fails, control is passed to the code outside of loop.
55 while SYNTAX The while loop syntax in Java is: while(<boolean Expression>) { // code In most applications, it is important to ensure that Boolean Expression will eventually become false and therefore prevent infinite iteration.
56 While.java import java.util.*; public class While { public static void main(string[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter n: "); int n = s.nextint(); int i = 1; while(i <= n) { System.out.print(i + " "); i++; System.out.println();
57 Prime.java import java.util.*; public class Prime { public static void main(string[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter n: "); int n = s.nextint(); int count = 0; int i = 1; while(i <= n) { if(n % i == 0) count++; i++; if(count == 2) System.out.println(n + " is prime."); else System.out.println(n + " is not prime");
58 NUMBER OF ITERATIONS In both examples, While.java and Prime.java, the body of the loop is executed n times, where n is the size of input. Quite often, we cannot predict the number of time the body of the while loop will be executed. Interesting example is the computation of the greatest common divisor. Recall that gcd( a, b ) is the greatest integer that divides both, a and b.
59 GCD - ALGORITHM m n r = m % n m n r = m % n m n r = m % n
60 Gcd.java import java.util.*; public class Gcd { public static void main(string[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter m: "); int m = s.nextint(); System.out.print("Enter n: "); int n = s.nextint();
61 Gcd.java ctd int r = m % n; while(r!= 0) { m = n; n = r; r = m % n; System.out.println("gcd: " + n);
62 for LOOP init BE false init - initializes loop index variable ( e.g. i = 1 ). Executed once. control true // code As long as boolean expression is true, the body of the loop is executed. Last statement in the body of the loop is control - it controls the loop index variable ( e.g i++).
63 for SYNTAX The for loop syntax in Java is: for(init; <Boolean Expression>; control) { // code For loop is typically used when we know in advance the number of iterations.
64 FIBONACCI SEQUENCE Fibonacci sequence are the numbers in the following integer sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,... By definition, the first two integers in the sequence are 1 and each subsequent integer is the sum of the previous two. Leonardo Fibonacci, Italian mathematician ( )
65 FIBONACCI SEQUENCE previous temp next
66 Fibonacci.java import java.util.*; public class Fibonacci { public static void main(string[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter n: "); int n = s.nextint(); int prev = 1; int temp = 1; int next; for(int i = 1; i <= n; i++) { next = prev + temp; System.out.print(next + " "); prev = temp; temp = next; System.out.println();
67 do while LOOP true // code BE false Similar to while loop, except that body of the do-while must be executed at least once. The last statement in do-while loop is Boolean Expression. As long as it evaluates to true, control is passed back to the first line of code.
68 DoWhile.java import java.util.*; public class DoWhile { public static void main(string[] args) { int a, b; Scanner s = new Scanner(System.in); do { System.out.print("Enter a: "); a = s.nextint(); System.out.print("Enter b: "); b = s.nextint(); while(a < b);
69 METHODS Do we build buildings by getting huge chunk of stone or wood and then carve them inside out? Doable ( Al Khazneh ا%$#نة ), but... As foundation, floors, walls, rafters are basic building blocks in civil engineering, so are methods in Computing!
70 METHODS A method is enclosed group of statements ( assignment, flow control, iteration ) that has: Name - any legal identifier as in the case of variable names, but good coding conventions restrict method names furthermore: - method name should be a verb in lower case or - multi-word name that begins with a verb in lowercase, followed by adjectives, nouns etc. Examples: run, runfast, getbackground, isempty
71 METHODS Modifiers - specify methods accessibility ( public, private, static ) - more about this in CP1340. In this course, all our methods will be public static - i.e., class methods accessible by anyone. Return type - methods can return no value ( void ) or a single value whose type must be specified ( int, double, boolean, char etc. ) Argument list - list of parameters including their names and types that can be passed to a method.
72 METHOD S SIGNATURE Defined as [public private protected] [static] [return-type] name([type] arg1, [type] arg2,...) { // body Examples: public static void main(string[] args) public static boolean isprime(int n) public static int gcd(int m, int n)
73 Area.java public class Area { public static void main(string[] args) { int w = 2; int h = 3; int a = area(w, h); System.out.println("area: " + a); public static int area(int w, int h) { int ar = w * h; return ar;
74 ARGUMENTS PASSING a = 6 public static void main(string[] args) { int w = 2; int h = 3; int a = area( w, h ); 2 3 public static int area(int w, int h ) { int ar = w * h; return ar; ar = 2 * 3 = 6
75 Primes.java public class Primes { public static void main(string[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter n: "); int n = s.nextint(); if(isprime(n)) System.out.println(n + " is prime."); else System.out.println(n + " is not prime.");
76 Primes.java ctd public static boolean isprime(int n) { int count = 0; for(int i = 1; i <= n; i++) { if(n % i == 0) count++; if(count == 2) return true; else return false;
77 PrimeSequence.java import java.util.*; public class PrimeSequence { public static void main(string[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter n: "); int n = s.nextint(); generateprimes(n);
78 PrimeSequence.java ctd public static void generateprimes(int n) { int number = 2; int count = 1; while(count <= n) { if(isprime(number)) { System.out.print(number + " "); count++; number++; System.out.println();
79 PrimeSequence.java ctd public static boolean isprime(int n) { int count = 0; for(int i = 1; i <= n; i++) { if(n % i == 0) count++; if(count == 2) return true; else return false;
80 SCOPE OF VARIABLES Scope of variable refers to location where variable is declared. Variables declared within method, including parameter list, are method variables - they are visible, accessible and modifiable within a method only. Variables declared within a class, but outside of any method are class variables - they are visible, accessible and modifiable by any method that belongs to the same class.
81 Scope.java public class Scope { static int x = 1; // class variable public static void main(string[] args) { x++; System.out.println("main:x = " + x); int w = 5; // method variable System.out.println("main:w = " + w); a(w); System.out.println("main:w = " + w); System.out.println("main:x = " + x); public static void a(int w) { x--; w++; System.out.println("a:w = " + w);
82 CALL BY VALUE Any identifier in Java has two values associated with it: Actual value assigned to a variable. Memory location - place in memory where assigned value resides. int n = 10; memory location (e.g. 272d7a10), assigned by compiler value is 10, assigned by developer
83 Scope.java - ANALYSIS class Scope int x = 1; main() { x++; int w = 5; a(w); a(int w) { x--; w++;... Memory x 12 w 5 w 56 addresses ( arbitrary ) 272d d270c 272d d d d271c 272d d d2728
84 RECURSION Recursive method is a method that calls itself either directly or indirectly ( through another method ). It consists of: One or more base cases - trivial cases for which method returns discrete value. One or more nontrivial cases for which method returns a call to itself. In order to avoid infinite recursion, nontrivial cases should return slightly simpler or smaller call.
85 EXAMPLE Factorial function can be recursively defined as: f( x ) =! "# 1 x f(x - 1) if x = 1 otherwise So, f( 1 ) represents the base case - function simply returns 1, i.e. f ( 1 ) = 1. On the other hand, f ( 3 ), for example, is nontrivial call. Recursion than proceeds as: f( 3 ) = 3 f( 2 ) = 3 2 f( 1 ) = = 3 2 = 6
86 Factorial.java import java.util.*; public class Factorial { public static void main(string[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter n: "); int n = s.nextint(); System.out.println(n + "! = " + f(n)); public static int f(int n) { if(n == 1) return 1; else return n * f(n - 1);
87 EXAMPLE Recall Fibonacci sequence. It can be recursively defined as: f( x ) =! "# 1 f(x - 1) + f(x - 2) if x = 1 or x = 2 otherwise Here we have two base cases, when argument x is either 1 or 2, i.e. f( 1 ) = 1 and f( 2 ) = 1, reflecting the fact that first two integers in the sequence are 1, 1. Nontrivial case, say f( 4 ) is evaluated as: f( 4 ) = f( 3 ) + f( 2 ) = f( 2 ) + f( 1 ) + 1 = = 3
88 RecFibo.java public class RecFibo { public static void main(string[] args) { for(int i = 1; i <= 10; i++) System.out.print(rf(i) + " "); System.out.println(); public static int rf(int n) { if(n == 1 n == 2) return 1; else return rf(n - 1) + rf(n - 2);
89 ARRAYS - MOTIVATION How would one write Java code to compute average mark on midterm? int grade0, grade1, grade2,..., grade13; // get grades // compute sum sum = grade0 + grade grade13; Very tedious. What if we have to compute the average of 100 or 1000 marks?
90 ARRAYS An Array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. Array is declared as: type[] name = new type[size]; The new operator requests memory allocation and stores returned address in array s name. For example, int[] a = new int[10]; creates an array of integers whose length is 10.
91 ARRAYS Pictorially, int[] a = new int[10]; can be represented as: First index ( 0 ) Indices Array a of integers whose size is 10 Element ( integer ) at index 8
92 ARRAYS When array is allocated, its values are automatically initialized to zeros for numeric data types and false for boolean type. Arbitrary values can be assigned by either specifying array s name, index and value as in: int[] n = new int[3]; n[0] = 5; n[1] = 2; n[2] = 4; Or by assigning values at time of allocation as in: int[] n = {5, 2, 4;
93 ARRAYS In either case, resulting array is: n Each array has field length associated with it. It stores the number of values in the array. Continuing with the previous example, the value of n.length is 3.
94 Arrays.java public class Arrays { public static void main(string[] args) { int[] n = new int[3]; System.out.print("Array of integers: "); for(int i = 0; i < n.length; i++) System.out.print(n[i] + " "); System.out.println(); char[] c = {'a','b','c','d'; System.out.print("Array of characters: "); for(int i = 0; i < c.length; i++) System.out.print(c[i] + " "); System.out.println();
95 Arrays.java ctd double[] d = new double[5]; System.out.print("Array of real numbers: "); for(int i = 0; i < d.length; i++) { int rnd = (int) (Math.random() * 10000); d[i] = rnd / 100.0; System.out.print(d[i] + " "); System.out.println();
96 FIND MINIMUM Given array of integers, find the smallest value in the array. The algorithm proceeds as follows: [1] Assume min = n [2] 2 < 5 ( true ) min = 2 [3] 4 < 2 ( false ) min = 2 [4] 1 < 2 ( true ) min = 1 [5] 3 < 1 ( false ) min = 1
97 FindMin.java public class FindMin { public static void main(string[] args) { int[] n = new int[10]; for(int i = 0; i < n.length; i++) { n[i] = (int)(math.random() * 100); System.out.print(n[i] + " "); System.out.println(); int min = n[0]; int loc = 0; for(int i = 1; i < n.length; i++) { if(n[i] < min) { min = n[i]; loc = i; System.out.println(min + " at: " + loc);
98 ARRAYS AND METHODS Assume that we declared and initialized array: int[] n = {5, 2, 4; What would be the output of System.out.println(n); It is something like [I@272d7a10 And what the ***k is [I@272d7a10? It is the address of the first item in the array!
99 ARRAYS AND METHODS Method that takes array as an argument might have the prototype: public static int f(int[] n) Method call would consist of specifying method s name and argument as in f(n). Argument is array s name, i.e. the address of the first entry in the array. The consequence of such a call is that any changes made to the array in called method will be reflected in calling method.
100 Scramble.java public class Scramble { public static void main(string[] args) { int[] n = {1, 2, 3, 4, 5; print(n); scramble(n); print(n); public static void print(int[] n) { for(int i = 0; i < n.length; i++) System.out.print(n[i] + " "); System.out.println(); public static void scramble(int[] n) { for(int i = 0; i < n.length; i++) n[i] = (int)(math.random() * 5 + 1);
101 CALL BY REFERENCE Recall that any identifier in Java has two values associated with it: the actual value assigned to identifier and memory address where that value is stored. Since array s name stores the address of the first entry in the array, when we call a method passing array s name as an argument, we actually pass that memory address. Such calls are called calls by reference.
102 CALL BY REFERENCE int[] n = {1, 2, 3; main() { f(n); Function call f(n) passes 272d270c as argument. f(int[] n) { n[0] = 4; addresses ( arbitrary ) Memory 272d2708! 272d270c 41 "# 272d d d2718 Function f now has the access to the same memory segment.
103 SEQUENTIAL SEARCH Given array of integers and a target value, decide whether or not target value is in the array. Assume that int[] n = {5, 2, 4, 1, 3; and target is 1. The algorithm proceeds as follows: [1] 5 == 1 ( false ) n [2] 2 == 1 ( false ) [3] 4 == 1 ( false ) [4] 1 == 1 ( true )
104 SequentialSearch.java import java.util.*; public class SequentialSearch { public static void main(string[] args) { int[] n = {5, 2, 4, 1, 3; Scanner s = new Scanner(System.in); System.out.print("Enter target: "); int target = s.nextint(); if(find(n, target)) System.out.println(target + " is in the array."); else System.out.println(target + " is not in the array.");
105 SequentialSearch.java ctd public static boolean find(int[] n, int target) { boolean found = false; for(int i = 0; i < n.length &&!found; i++) { if(n[i] == target) found = true; return found;
106 INSERTION SORT Input: unsorted array of integers Output: sorted array of integers ( ascending order )
107 InsertionSort.java public class InsertionSort { public static void main(string[] args) { int[] n = new int[10]; generatenumbers(n); print(n); sort(n); print(n);
108 InsertionSort.java ctd public static void generatenumbers(int[] n) { for(int i = 0; i < n.length; i++) { n[i] = (int)(math.random() * 100); public static void print(int[] n) { for(int i = 0; i < n.length; i++) System.out.print(n[i] + " "); System.out.println();
109 InsertionSort.java ctd public static void sort(int[] n) { for(int i = 1; i < n.length; i++) { int pivot = n[i]; for(int j = i - 1; j >= 0; j--) { if(pivot < n[j]) { int temp = n[j + 1]; n[j + 1] = n[j]; n[j] = temp;
110 BINARY SEARCH Sequential search, in the worst case scenario ( i.e., target is not in the array or the last entry in the array ), takes n comparisons, where n is the array s length. If array is sorted, search can be drastically improved. The idea behind the binary search is to represent array as a binary tree-like structure.
111 BINARY SEARCH
112 BINARY SEARCH Assume target is 7. Start in the middle, where middle = ( start + end ) / 2. Start index is 0, end index 4 is 6. So, middle = Since 7 > 4, new start is middle + 1 ( 4 ) and new middle = ( ) / 2 = 5. Since 7 > 6, new start is middle + 1 ( 6 ) and new middle = ( ) / 2 = 6.
113 BINARY SEARCH target = 3. middle = ( ) / 2 = < 4 end = middle - 1 = 2 middle = ( ) / 2 = > 2 start = middle + 1 = 2 middle = ( ) / 2
114 BINARY SEARCH target = 0. middle = ( ) / 2 = 3 0 < 4 end = middle - 1 = 2 middle = ( ) / 2 = 1 0 < 2 end = middle - 1 = 0 middle = ( ) / 2 = 0 0 < 1 end = middle - 1 = -1 start > end! Not found.
115 BinarySearch.java import java.util.*; public class BinarySearch { public static void main(string[] args) { int[] n = {1, 2, 3, 4, 5, 6, 7; Scanner s = new Scanner(System.in); System.out.print("Enter target: "); int target = s.nextint(); if(binsearch(n, target)) System.out.println(target + " is in the array."); else System.out.println(target + " is not in the array.");
116 BinarySearch.java ctd public static boolean binsearch(int[] n, int target) { int start = 0; int end = n.length - 1; int middle = (start + end) / 2; boolean found = false; while(start <= end &&!found) { if(target == n[middle]) found = true;
117 BinarySearch.java ctd else if(target < n[middle]) { end = middle - 1; middle = (start + end) / 2; else { start = middle + 1; middle = (start + end) / 2; return found;
118 2-DIMENSIONAL ARRAYS 2-Dimensional arrays ( in general n-dimensional arrays ) are arrays whose entries are arrays themselves. n[0] So, n[0][0] = 1, n[0][1] = 2, n[1][0] =3, n[1][1] = 4 etc. n[1] In Java, lengths of subarrays need not be the same. n[2]
119 MultArray.java public class MultArray { public static void main(string[] args) { int[][] a = { { 1, 2, { 3, 4, 5, 6, { 7, 8, 9 ; print(a);
120 MultArray.java ctd public static void print(int[][] a) { for(int i = 0; i < a.length; i++) { for(int j = 0; j < a[i].length; j++) { System.out.print(a[i][j] + " "); System.out.println();
121 STRINGS java.lang.string is a built-in class ( API ) that represents character strings, i.e. words. Strings are immutable objects, i.e., they cannot be changed after they are created. In order to create strings, one has to invoke constructor method. Constructor is a special method which has the same name as the class it belongs to.
122 STRING CONSTRUCTORS The most common String constructors are: String s1 = new String(); - creates an empty string. Its length is zero. String s2 = new String("Giddy up!"); - creates a string object representing the same sequence of characters as in its argument. String s3 = new String(ca); - creates a string object representing the sequence of characters contained in character array argument ( ca ).
123 CONSTRUCTORS In general, objects in Java are created through constructors. Unlike regular methods, constructors are invoked once and only once - at the time of object creation. Object o = new Object(arg); creates a new object. The new operator requests memory allocation and stores returned address in object s name. Name ( address ) Data field(s) Constructor(s) Method(s)
124 StringConstructors.java public class StringConstructors { public static void main(string[] args) { String s1 = new String(); String s2 = new String("Giddy up!"); char[] ca = {'a','b','c'; String s3 = new String(ca); String s4 = new String(ca, 1, 2); System.out.println(s1); System.out.println(s2); System.out.println(s3); System.out.println(s4);
125 STRING METHODS Once String is constructed, we can use methods provided in the String class. Some of the most commonly used String methods are: public int length() - Returns the length of this string. public char charat(int index) - Returns the character at specified index. public int indexof(char c) - Returns the index within this string of the first occurrence of the specified character.
126 STRING METHODS public boolean equals(object obj) - Compares this string to specified object. public String substring(int index) - Returns a new string that is a substring of this string starting at index index. public char[] tochararray() - Converts this string to a new character array.
127 STRING METHODS public String tolowercase() - Returns a new string which is this string with all characters converted to lowercase. public String touppercase() - Returns a new string which is this string with all characters converted to uppercase. public String concat(string str) - Returns a new string which is concatenation of this string and the specified string.
128 StringMethods.java public class StringMethods { public static void main(string[] args) { String s = new String("abcde"); int length = s.length(); System.out.println(s + " has " + length + " characters "); char c = s.charat(1); System.out.println("Second character: " + c); int pos = s.indexof('e'); System.out.println("The index of e is " + pos);
129 StringMethods.java ctd char[] chs = s.tochararray(); for(int i = 0; i < chs.length; i++) System.out.println(chs[i]); String p = new String("XYZ"); System.out.println(s + " " + p); if(s.equals(p)) System.out.println("same data fields"); else System.out.println("different data fields");
130 StringMethods.java ctd if(s == p) System.out.println("Same references"); else System.out.println("Different references"); String subs = s.substring(2); System.out.println("Substring: " + subs);
131 StringMethods.java ctd String ccs = s.concat(p); System.out.println("s concat p: " + ccs); String lcs = p.tolowercase(); System.out.println("Lowercase: " + lcs); String ucs = s.touppercase(); System.out.println("Uppercase: " + ucs);
132 == VS equals String s1 = new String("abc"); s1 (@ff0add00) == ( false ) String s2 = new String("abc"); s2 (@ff0addbc) abc Constructors Methods equals ( true ) abc Constructors Methods
133 STRING REFERENCES String s1 = new String("abc"); String s2 = s1; s1 (@ff0add00) == ( true ) abc s2 (@ff0add00) Constructors Methods
134 REVERSE STRING index = 0, length = 5, target index = 4 = a b c d e index = 1, length = 5, target index = 3 = index = 2, length = 5, target index = 2 = index = 3, length = 5, target index = 1 = index = 4, length = 5, target index = 0 =
135 Reverse.java import java.util.*; public class Reverse { public static void main(string[] args) { System.out.print("Enter word: "); Scanner s = new Scanner(System.in); String word = s.next(); String reversedword = reverse(word); System.out.println(reversedWord);
136 Reverse.java ctd public static String reverse(string word) { int length = word.length(); char[] ca = new char[length]; for(int i = 0; i < length; i++) { ca[i] = word.charat(length - i - 1); return new String(ca);
137 Palindrome.java import java.util.*; public class Palindrome { public static void main(string[] args) { System.out.print("Enter word: "); Scanner s = new Scanner(System.in); String word = s.next(); if(ispalindrome(word)) System.out.println(word + " is palindrome"); else System.out.println(word + " is not palindrome");
138 Palindrome.java ctd public static boolean ispalindrome(string word) { String rword = reverse(word); if(rword.equals(word)) return true; else return false;
139 Palindrome.java ctd public static String reverse(string word) { int length = word.length(); char[] ca = new char[length]; for(int i = 0; i < length; i++) { ca[i] = word.charat(length - i - 1); return new String(ca);
140 COMMAND-LINE ARGUMENTS Recall the main method s signature: public static void main(string[] args) What are main method s arguments? Array of strings: String[] args Similarly as we pass argument to javac ( i.e. filename containing the source code ), we can pass command-line arguments to any Java program having the main method.
141 Cla.java public class Cla { public static void main(string[] args) { for(int i = 0; i < args.length; i++) { System.out.println("CLA " + i + " : " + args[i]); Compile and run: java Cla Now run as: java Cla one two three Command line arguments one, two and three are internally stored as args[0], args[1] and args[2]
142 FILES Java File class is used as abstract representation of a file. Constructor takes a pathname to a file as argument as in : File f = new File(args[0]); Java class FileReader can now be used to read the content of a file : FileReader in = new FileReader(f); Method in.read(data) reads the content of a file f and stores it in a character array data whose length is the length of file - f.length().
143 ReadFile.java import java.io.*; public class ReadFile { public static void main(string args[]) throws IOException { if(args.length == 0) System.out.println("usage: java ReadFile filename"); else { File f = new File(args[0]); readfile(f);
144 ReadFile.java ctd. public static void readfile(file f) throws IOException { FileReader in = new FileReader(f); int size = (int) f.length(); char data[] = new char[size]; in.read(data); in.close(); String s = new String(data); System.out.print(s);
145 FILES Similarly, Java class FileWriter can be used to write to a file : FileWriter out = new FileWriter(f); Method out.write(data) writes string data into a file specified by File s constructor. If the file does not exist, it will be created as well.
146 WriteFile.java import java.io.*; public class WriteFile { public static void main(string args[]) throws IOException { if(args.length == 0) System.out.println("usage: java ReadFile filename"); else { File f = new File(args[0]); writefile(f);
147 WriteFile.java ctd public static void writefile(file f) throws IOException { FileWriter out = new FileWriter(f); String s = "This is a FileWriter"; out.write(s); out.close();
Pace University. Fundamental Concepts of CS121 1
Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction
More informationCS 231 Data Structures and Algorithms, Fall 2016
CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard
More informationExpressions and Data Types CSC 121 Spring 2015 Howard Rosenthal
Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types
More informationExpressions and Data Types CSC 121 Fall 2015 Howard Rosenthal
Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and
More informationProgramming with Java
Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules
More informationFull file at
Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class
More informationCS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University
CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University Overview of Source Code Components Comments Library declaration Classes Functions Variables Comments Can
More informationJava Identifiers. Java Language Essentials. Java Keywords. Java Applications have Class. Slide Set 2: Java Essentials. Copyright 2012 R.M.
Java Language Essentials Java is Case Sensitive All Keywords are lower case White space characters are ignored Spaces, tabs, new lines Java statements must end with a semicolon ; Compound statements use
More informationLecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4
Assignments Lecture 6 Complete for Project 1 Reading: 3.1, 3.2, 3.3, 3.4 Summary Program Parts Summary - Variables Class Header (class name matches the file name prefix) Class Body Because this is a program,
More informationIntroduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
More informationOutline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.
OOP in Java 1 Outline 1. Getting started, primitive data types and control structures 2. Classes and objects 3. Extending classes 4. Using some standard packages 5. OOP revisited Parts 1 to 3 introduce
More informationJava is an objet-oriented programming language providing features that support
Java Essentials CSCI 136: Spring 2018 Handout 2 February 2 Language Basics Java is an objet-oriented programming language providing features that support Data abstraction Code reuse Modular development
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 September 30, 2010 G. Lipari (Scuola Superiore Sant Anna) Introduction
More informationCONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2
CONTENTS: Compilation Data and Expressions COMP 202 More on Chapter 2 Programming Language Levels There are many programming language levels: machine language assembly language high-level language Java,
More informationAP Computer Science A
AP Computer Science A 1st Quarter Notes Table of Contents - section links Click on the date or topic below to jump to that section Date : 9/8/2017 Aim : Java Basics Objects and Classes Data types: Primitive
More informationObject oriented programming. Instructor: Masoud Asghari Web page: Ch: 3
Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning
More informationExpressions and Data Types CSC 121 Spring 2017 Howard Rosenthal
Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types
More informationCourse Outline. Introduction to java
Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.
More informationCOE 211/COE 212 Computer/Engineering Programming. Welcome to Exam II Thursday December 20, 2012
1 COE 211/COE 212 Computer/Engineering Programming Welcome to Exam II Thursday December 20, 2012 Instructor: Dr. George Sakr Dr. Wissam F. Fawaz Dr. Maurice Khabbaz Name: Student ID: Instructions: 1. This
More informationDM550 Introduction to Programming part 2. Jan Baumbach.
DM550 Introduction to Programming part 2 Jan Baumbach jan.baumbach@imada.sdu.dk http://www.baumbachlab.net COURSE ORGANIZATION 2 Course Elements Lectures: 10 lectures Find schedule and class rooms in online
More informationLecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4
Assignments Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4 Lecture 6 Complete for Lab 4, Project 1 Note: Slides 12 19 are summary slides for Chapter 2. They overview much of what we covered but are not complete.
More informationWentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics
WIT COMP1000 Java Basics Java Origins Java was developed by James Gosling at Sun Microsystems in the early 1990s It was derived largely from the C++ programming language with several enhancements Java
More informationReview Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013
Review Chapters 1 to 4 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections 2.1 2.5 Instructor:
More informationwww.thestudycampus.com Methods Let s imagine an automobile factory. When an automobile is manufactured, it is not made from basic raw materials; it is put together from previously manufactured parts. Some
More informationCS11 Java. Fall Lecture 1
CS11 Java Fall 2006-2007 Lecture 1 Welcome! 8 Lectures Slides posted on CS11 website http://www.cs.caltech.edu/courses/cs11 7-8 Lab Assignments Made available on Mondays Due one week later Monday, 12 noon
More informationComputer Components. Software{ User Programs. Operating System. Hardware
Computer Components Software{ User Programs Operating System Hardware What are Programs? Programs provide instructions for computers Similar to giving directions to a person who is trying to get from point
More informationBASIC ELEMENTS OF A COMPUTER PROGRAM
BASIC ELEMENTS OF A COMPUTER PROGRAM CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING LOGO Contents 1 Identifier 2 3 Rules for naming and declaring data variables Basic data types 4 Arithmetic operators
More informationIntroduction to Java Applications
2 Introduction to Java Applications OBJECTIVES In this chapter you will learn: To write simple Java applications. To use input and output statements. Java s primitive types. Basic memory concepts. To use
More informationSelec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal
Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program
More informationCOSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan
COSC 123 Computer Creativity Introduction to Java Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Key Points 1) Introduce Java, a general-purpose programming language,
More informationSimple Java Reference
Simple Java Reference This document provides a reference to all the Java syntax used in the Computational Methods course. 1 Compiling and running... 2 2 The main() method... 3 3 Primitive variable types...
More informationCOMP 202 Java in one week
CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator COMP 202 Java in one week The Java Programming Language A programming language
More informationboolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while
CSCI 150 Fall 2007 Java Syntax The following notes are meant to be a quick cheat sheet for Java. It is not meant to be a means on its own to learn Java or this course. For that you should look at your
More informationCMPT 125: Lecture 3 Data and Expressions
CMPT 125: Lecture 3 Data and Expressions Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 3, 2009 1 Character Strings A character string is an object in Java,
More informationDM550 / DM857 Introduction to Programming. Peter Schneider-Kamp
DM550 / DM857 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk http://imada.sdu.dk/~petersk/dm550/ http://imada.sdu.dk/~petersk/dm857/ OBJECT-ORIENTED PROGRAMMING IN JAVA 2 Programming
More informationLoops. CSE 114, Computer Science 1 Stony Brook University
Loops CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Motivation Suppose that you need to print a string (e.g., "Welcome to Java!") a user-defined times N: N?
More informationJava+- Language Reference Manual
Fall 2016 COMS4115 Programming Languages & Translators Java+- Language Reference Manual Authors Ashley Daguanno (ad3079) - Manager Anna Wen (aw2802) - Tester Tin Nilar Hlaing (th2520) - Systems Architect
More informationIndex COPYRIGHTED MATERIAL
Index COPYRIGHTED MATERIAL Note to the Reader: Throughout this index boldfaced page numbers indicate primary discussions of a topic. Italicized page numbers indicate illustrations. A abstract classes
More informationObject-Oriented Programming
Object-Oriented Programming Java Syntax Program Structure Variables and basic data types. Industry standard naming conventions. Java syntax and coding conventions If Then Else Case statements Looping (for,
More information1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199
1 class Lecture5 { 2 3 "Methods" 4 5 } 6 7 / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199 Methods 2 Methods can be used to define reusable code, and organize
More informationWOSO Source Code (Java)
WOSO 2017 - Source Code (Java) Q 1 - Which of the following is false about String? A. String is immutable. B. String can be created using new operator. C. String is a primary data type. D. None of the
More informationCMPS 12A Winter 2006 Prof. Scott A. Brandt Final Exam, March 21, Name:
CMPS 12A Winter 2006 Prof. Scott A. Brandt Final Exam, March 21, 2006 Name: Email: This is a closed note, closed book exam. There are II sections worth a total of 200 points. Plan your time accordingly.
More informationZheng-Liang Lu Java Programming 45 / 79
1 class Lecture2 { 2 3 "Elementray Programming" 4 5 } 6 7 / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch. 2 in HS 11 / Zheng-Liang Lu Java Programming 45 / 79 Example Given a radius
More informationLast Class. While loops Infinite loops Loop counters Iterations
Last Class While loops Infinite loops Loop counters Iterations public class January31{ public static void main(string[] args) { while (true) { forloops(); if (checkclassunderstands() ) { break; } teacharrays();
More informationEntry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process
Entry Point of Execution: the main Method Elementary Programming EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG For now, all your programming exercises will
More informationCS 170 Exam 2. Version: A Fall Name (as in OPUS) (print): Instructions:
CS 170 Exam 2 Version: A Fall 2015 Name (as in OPUS) (print): Section: Seat Assignment: Instructions: Keep your eyes on your own paper and do your best to prevent anyone else from seeing your work. Do
More informationCOMP 202. Java in one week
COMP 202 CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator Java in one week The Java Programming Language A programming language
More informationPrimitive Data, Variables, and Expressions; Simple Conditional Execution
Unit 2, Part 1 Primitive Data, Variables, and Expressions; Simple Conditional Execution Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Overview of the Programming Process Analysis/Specification
More informationCOE318 Lecture Notes Week 4 (Sept 26, 2011)
COE318 Software Systems Lecture Notes: Week 4 1 of 11 COE318 Lecture Notes Week 4 (Sept 26, 2011) Topics Announcements Data types (cont.) Pass by value Arrays The + operator Strings Stack and Heap details
More informationJava provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:
JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators
More informationSTUDENT LESSON A12 Iterations
STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of
More informationA variable is a name for a location in memory A variable must be declared
Variables A variable is a name for a location in memory A variable must be declared, specifying the variable's name and the type of information that will be held in it data type variable name int total;
More informationChapter 1 Introduction to java
Chapter 1 Introduction to java History of java Java was created by by Sun Microsystems team led by James Gosling (1991) It was mainly used for home appliance, it later became a general purpose programming
More informationOutline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors
Outline Overview history and advantage how to: program, compile and execute 8 data types 3 types of errors Control statements Selection and repetition statements Classes and methods methods... 2 Oak A
More informationMore Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements
More Things We Can Do With It! More operators and expression types More s 11 October 2007 Ariel Shamir 1 Overview Variables and declaration More operators and expressions String type and getting input
More informationCSE 114 Computer Science I
CSE 114 Computer Science I Iteration Cape Breton, Nova Scotia What is Iteration? Repeating a set of instructions a specified number of times or until a specific result is achieved How do we repeat steps?
More informationIntroduction to Computer Science Unit 2. Notes
Introduction to Computer Science Unit 2. Notes Name: Objectives: By the completion of this packet, students should be able to describe the difference between.java and.class files and the JVM. create and
More informationReview. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char
Review Primitive Data Types & Variables int, long float, double boolean char String Mathematical operators: + - * / % Comparison: < > = == 1 1.3 Conditionals and Loops Introduction to Programming in
More informationIntroduction to Java & Fundamental Data Types
Introduction to Java & Fundamental Data Types LECTURER: ATHENA TOUMBOURI How to Create a New Java Project in Eclipse Eclipse is one of the most popular development environments for Java, as it contains
More information1 class Lecture4 { 2 3 "Loops" / References 8 [1] Ch. 5 in YDL 9 / Zheng-Liang Lu Java Programming 125 / 207
1 class Lecture4 { 2 3 "Loops" 4 5 } 6 7 / References 8 [1] Ch. 5 in YDL 9 / Zheng-Liang Lu Java Programming 125 / 207 Loops A loop can be used to make a program execute statements repeatedly without having
More informationc) And last but not least, there are javadoc comments. See Weiss.
CSCI 151 Spring 2010 Java Bootcamp The following notes are meant to be a quick refresher on Java. It is not meant to be a means on its own to learn Java. For that you would need a lot more detail (for
More informationCOE 212 Engineering Programming. Welcome to Exam II Monday May 13, 2013
1 COE 212 Engineering Programming Welcome to Exam II Monday May 13, 2013 Instructors: Dr. Randa Zakhour Dr. Maurice Khabbaz Dr. George Sakr Dr. Wissam F. Fawaz Name: Solution Key Student ID: Instructions:
More informationCS2141 Software Development using C/C++ C++ Basics
CS2141 Software Development using C/C++ C++ Basics Integers Basic Types Can be short, long, or just plain int C++ does not define the size of them other than short
More informationReview: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements
Review: Exam 1 9/20/06 CS150 Introduction to Computer Science 1 1 Your First C++ Program 1 //*********************************************************** 2 // File name: hello.cpp 3 // Author: Shereen Khoja
More informationJava in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure.
Java in 21 minutes hello world basic data types classes & objects program structure constructors garbage collection I/O exceptions Strings Hello world import java.io.*; public class hello { public static
More informationCS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8
CS 302: INTRODUCTION TO PROGRAMMING Lectures 7&8 Hopefully the Programming Assignment #1 released by tomorrow REVIEW The switch statement is an alternative way of writing what? How do you end a case in
More informationCSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI
CSCI 2010 Principles of Computer Science Data and Expressions 08/09/2013 CSCI 2010 1 Data Types, Variables and Expressions in Java We look at the primitive data types, strings and expressions that are
More informationCOMP6700/2140 Data and Types
COMP6700/2140 Data and Types Alexei B Khorev and Josh Milthorpe Research School of Computer Science, ANU February 2017 Alexei B Khorev and Josh Milthorpe (RSCS, ANU) COMP6700/2140 Data and Types February
More informationFundamental of Programming (C)
Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering
More informationCS 106 Introduction to Computer Science I
CS 106 Introduction to Computer Science I 05 / 31 / 2017 Instructor: Michael Eckmann Today s Topics Questions / Comments? recap and some more details about variables, and if / else statements do lab work
More informationSection 004 Spring CS 170 Exam 1. Name (print): Instructions:
CS 170 Exam 1 Section 004 Spring 2014 Name (print): Instructions: Keep your eyes on your own paper and do your best to prevent anyone else from seeing your work. Do NOT communicate with anyone other than
More informationTester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time
Tester vs. Controller Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG For effective illustrations, code examples will mostly be written in the form of a tester
More informationDM503 Programming B. Peter Schneider-Kamp.
DM503 Programming B Peter Schneider-Kamp petersk@imada.sdu.dk! http://imada.sdu.dk/~petersk/dm503/! VARIABLES, EXPRESSIONS & STATEMENTS 2 Values and Types Values = basic data objects 42 23.0 "Hello!" Types
More informationMidterm I - CSE11 Fall 2013 CLOSED BOOK, CLOSED NOTES 50 minutes, 100 points Total.
Midterm I - CSE11 Fall 2013 CLOSED BOOK, CLOSED NOTES 50 minutes, 100 points Total. Name: ID: Problem 1) (8 points) For the following code segment, what are the values of i, j, k, and d, after the segment
More informationJava Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing
Java Programming MSc Induction Tutorials 2011 Stefan Stafrace PhD Student Department of Computing s.stafrace@surrey.ac.uk 1 Tutorial Objectives This is an example based tutorial for students who want to
More informationCS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010
CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011 Lectures 1-22 Moaaz Siddiq Asad Ali Latest Mcqs MIDTERM EXAMINATION Spring 2010 Question No: 1 ( Marks: 1 ) - Please
More informationAPCS Semester #1 Final Exam Practice Problems
Name: Date: Per: AP Computer Science, Mr. Ferraro APCS Semester #1 Final Exam Practice Problems The problems here are to get you thinking about topics we ve visited thus far in preparation for the semester
More informationCS212 Midterm. 1. Read the following code fragments and answer the questions.
CS1 Midterm 1. Read the following code fragments and answer the questions. (a) public void displayabsx(int x) { if (x > 0) { System.out.println(x); return; else { System.out.println(-x); return; System.out.println("Done");
More informationCOE 212 Engineering Programming. Welcome to Exam II Thursday April 21, Instructors: Dr. Salim Haddad Dr. Joe Tekli Dr. Wissam F.
1 COE 212 Engineering Programming Welcome to Exam II Thursday April 21, 2016 Instructors: Dr. Salim Haddad Dr. Joe Tekli Dr. Wissam F. Fawaz Name: Student ID: Instructions: 1. This exam is Closed Book.
More informationCOMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string
COMP 202 Built in Libraries and objects CONTENTS: Introduction to objects Introduction to some basic Java libraries string COMP 202 Objects and Built in Libraries 1 Classes and Objects An object is an
More informationICSE Class 10 Computer Applications ( Java ) 2014 Solved Question Paper
1 of 10 05-11-015 16:1 ICSE J Java for Class X Computer Applications ICSE Class 10 Computer Applications ( Java ) 014 Solved Question Paper ICSE Question Paper 014 (Solved) Computer Applications Class
More informationJava Bytecode (binary file)
Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.
More informationAP CS Unit 3: Control Structures Notes
AP CS Unit 3: Control Structures Notes The if and if-else Statements. These statements are called control statements because they control whether a particular block of code is executed or not. Some texts
More informationC Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee
C Language Part 1 (Minor modifications by the instructor) References C for Python Programmers, by Carl Burch, 2011. http://www.toves.org/books/cpy/ The C Programming Language. 2nd ed., Kernighan, Brian,
More informationElementary Programming
Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG Learning Outcomes Learn ingredients of elementary programming: data types [numbers, characters, strings] literal
More informationChapter 4: Control Structures I
Chapter 4: Control Structures I Java Programming: From Problem Analysis to Program Design, Second Edition Chapter Objectives Learn about control structures. Examine relational and logical operators. Explore
More informationSelec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal
Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program
More informationECE 122 Engineering Problem Solving with Java
ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction Outline Problem: How do I input data and use it in complicated expressions Creating complicated expressions
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 EggBasketEnhanced { public static void main(string[]
More informationVisual C# Instructor s Manual Table of Contents
Visual C# 2005 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion Topics Additional Projects Additional Resources Key Terms
More informationMr. Monroe s Guide to Mastering Java Syntax
Mr. Monroe s Guide to Mastering Java Syntax Getting Started with Java 1. Download and install the official JDK (Java Development Kit). 2. Download an IDE (Integrated Development Environment), like BlueJ.
More information1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8
Epic Test Review 1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4 Write a line of code that outputs the phase Hello World to the console without creating a new line character. System.out.print(
More informationProgram Fundamentals
Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java
More informationImportant Java terminology
1 Important Java terminology The information we manage in a Java program is either represented as primitive data or as objects. Primitive data פרימיטיביים) (נתונים include common, fundamental values as
More informationArray. Prepared By - Rifat Shahriyar
Java More Details Array 2 Arrays A group of variables containing values that all have the same type Arrays are fixed length entities In Java, arrays are objects, so they are considered reference types
More informationPlace your name tag here
CS 170 Exam 1 Section 001 Spring 2015 Name: Place your name tag here Instructions: Keep your eyes on your own paper and do your best to prevent anyone else from seeing your work. Do NOT communicate with
More informationcis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1
topics: introduction to java, part 1 cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 cis20.1-fall2007-sklar-leci.2 1 Java. Java is an object-oriented language: it is
More informationChapter 2: Data and Expressions
Chapter 2: Data and Expressions CS 121 Department of Computer Science College of Engineering Boise State University January 15, 2015 Chapter 2: Data and Expressions CS 121 1 / 1 Chapter 2 Part 1: Data
More informationCEN 414 Java Programming
CEN 414 Java Programming Instructor: H. Esin ÜNAL SPRING 2017 Slides are modified from original slides of Y. Daniel Liang WEEK 2 ELEMENTARY PROGRAMMING 2 Computing the Area of a Circle public class ComputeArea
More informationCS321 Languages and Compiler Design I. Winter 2012 Lecture 2
CS321 Languages and Compiler Design I Winter 2012 Lecture 2 1 A (RE-)INTRODUCTION TO JAVA FOR C++/C PROGRAMMERS Why Java? Developed by Sun Microsystems (now Oracle) beginning in 1995. Conceived as a better,
More information