1 / 37

MSI 692: Special Topics in Information Technology Lecture 2 Sanjay Goel University at Albany, SUNY

MSI 692: Special Topics in Information Technology Lecture 2 Sanjay Goel University at Albany, SUNY Fall 2004. Outline for the Class Topics. Review Statements and Control Flow Boolean Expressions Logical Operators Logical Statements if, else if, nesting, switch Loops (while, for, break)

emilioe
Download Presentation

MSI 692: Special Topics in Information Technology Lecture 2 Sanjay Goel University at Albany, SUNY

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. MSI 692: Special Topics in Information Technology Lecture 2 Sanjay Goel University at Albany, SUNY Fall 2004

  2. Outline for the ClassTopics • Review • Statements and Control Flow • Boolean Expressions • Logical Operators • Logical Statements • if, else if, nesting, switch • Loops (while, for, break) • Object-oriented Programming

  3. Statements and Control Flow

  4. Statements and Control FlowIntroduction • We have learned how to write words in a language. • We need to learn how to make sentences and paragraphs now. • What do you need to do when you are doing a complex problem? • You have certain process to follow you have decision points where you use your mind to make decisions. • To build your own logic into a computer program you need to write statements that capture your logic. • How to introduce logic into the program?

  5. Statements and Control FlowStatements • Statements are roughly equivalent to sentences in natural languages. • A statement forms a complete unit of execution. • It has many different types • Variable Declaration Statement • Expression Statement • Assignment Statement • Method Call Statement • Control Flow Statement

  6. Statements and Control FlowVariable declaration statements • Variable declaration statements are used to identify the type of the variable that is being declared • start with a type and end with a semicolon e.g. int width, height, area; String myString;

  7. Statements and Control FlowExpressions • An expression is a series of variables, operators, and method calls (constructed according to the syntax of the language) that evaluates to a single value. • Also defined as segments of code that perform computations and return values. • Data type of the value returned by an expression depends on the elements used in the expression. • Compound expressions and statements can be constructed from various smaller expressions as long as the data types required by one part of the expression matches the data types of the other. • If the order in which the operations in a compound expression need to be performed is not explicitly indicated, the order is determined by the precedence assigned to the operators

  8. Statements and Control FlowExpression Statements • Expression statements are formed by adding a semicolon at end of expression. • These are used to compute and to assign values to variables and to help control the execution flow of a program. • The following types of expressions can be made into a statement by terminating the expression with a semicolon (;): • Assignment expressions • Any use of ++ or – • Method calls • Object creation expressions • Examples • aValue = 8933.234; //assignment statement • aValue++; //increment statement • System.out.println(aValue); //method call statement • Integer integerObject = new Integer(4); //object creation statement

  9. Statements and Control FlowAssignment Statements • Assignment statement can be any expression involving the assignment operator. • e.g. area = length * width; • Method Call Statement invokes other functions • Method call expression involves assignment when the method returns a statement. • e.g. System.out.println(“This is a test”);

  10. Statements and Control FlowBlocks • Block is a group of statements enclosed in braces. • Blocks can occur within blocks and are called nested blocks e.g. { float length = 2; float width = 2; float area = length * width; System.out.println(“area = “ + area);}  • Empty or Null Statement • It is just a semicolon all by itself and results in no action. e.g. Consider the following program – lines 2 & 3 are null statement x = 2;  Line 1 ;  Line 2 ;  Line 3

  11. Boolean & Logical Expressions

  12. Boolean ExpressionsIntroduction • These are expressions which evaluate to true or false. • The simplest Boolean expressions are true and false • All conditional statements require Boolean expressions to decide flow of logic

  13. Boolean ExpressionsRelational & Equality Operators • Relational & Equality Operators • used for comparing numeric values < > <=>=== != • These operators can be used between any two numeric values, e.g. int a = 10; int b = 20; int c = 15 a > b  false a < b  true c < 10  false

  14. Logical ExpressionsOperators • These are used for combining multiple logical statements • Three logical operators • && - and • ! - not • || - or • Examples: (See next page)

  15. Boolean & Logical ExpressionsExercises • Assume the following: • int i, j, k; boolean b; k = 10; j = 6; b = true; • Give the values of the following expressions, or state if illegal. • b • !b • !!!!!!b • b || !b • b && !b • b ^ true • b++ • b = 1 • b = 1 > 2 • true || 1234/26%3==1 • true | 1234/26%3==1 • !b & (j < 100) • k > j > 3 • k > j && > 3 • k > j && k > 3 • b ||= false • b |= false • k = (k>j)?k:j+1 • (b && !b) | (!b & b) • 1 > 2 > 3 • b = j > 0 && (i = k/j)!=0 Source: http://leepoint.net/notes-java/20language/20expressions/60booleanex.html

  16. Boolean ExpressionsExercises - Solutions 15truek > j && k > 3 16illegalb ||= false 17trueb |= false 1810k = (k>j)?k:j+1 19false(b && !b) | (!b & b) 20illegal1 > 2 > 3 21trueb = j > 0 && (i = k/j)!=0 1trueb 2false!b 3true!!!!!!b 4trueb || !b 5falseb && !b 6falseb ^ true 7illegalb++ 8illegalb = 1 9falseb = 1 > 2 10truetrue || 1234/26%3==1 11truetrue | 1234/26%3==1 12false!b & (j < 100) 13illegalk > j > 3 14illegalk > j && > 3 Source: http://leepoint.net/notes-java/20language/20expressions/60booleanex.html

  17. Logical Statements

  18. Logical StatementsIf Statement • If statement is a conditional statement which proceeds based on the evaluation of an expression, e.g. if ( temp < 32) System.out.println(“It is below freezing today”); System.out.println(“Temperature = “ + temp);  • For multiple statements depending on a conditional we use blocks, e.g. if (temp < 32) { System.out.println(“It is below freezing”); System.out.println(“Keep all the windows closed”); }

  19. Logical StatementsSorting Algorithm • Example to sort three numbers if (b > c) { // swap b & c t = b; b = c; c = t; } if (a > b) { // Swap a & b t = a; a = b; b = t; } System.out.println(“The sorted numbers are: “ + a + “ “ + b + “ “ + c); } /* Bubble Sort Algorithm. In this * algorithm the smallest number */bubbles to the top public static void main(String[] args) { int a = Console.in.readInt(); int b = Console.in.readInt(); int c = Console.in.readInt(); int t; // Temporary variable if (a > b) { // Swap a and b t = a; a = b; b = t; }

  20. Logical StatementsIf else Statement • If else statement is a bi-directional logic expression • Syntax: if (Boolean expression) { Statement1 } else { Statement2 } • Example: if (temp < 32) { System.out.println(“Close all the windows); } else { System.out.println(“Open all the windows”);  }

  21. Logical StatementsNesting • Nesting is allowed within if and if else statements if (temp < 32) { System.out.println(“Below Freezing”); if (temp < 20) System.out.println(“School is off”); else System.out.println(“Go To School”); } else { if (temp > 70) System.out.println(“Go to the beach”); else System.out.println(“Go to school”); }

  22. Logical StatementsDangling Else • else goes with the closest if statement if (temp < 32) if (temp < 20) { System.out.println(“Stay indoors”); } else { System.out.println(“Keep Warm”); } Here the else statement goes with the second if statement

  23. Logical StatementsSwitch • Switch statement conditionally executes statements based on an integer expression • it is a multidirectional logic statement that can replace multiple if statements If (day == 1) { System.out.println(“Sunday”); } If (day == 2) {System.out.println(“Monday”); } If (day == 3) {System.out.println(“Tuesday”); } If (day == 4) {System.out.println(“Wednesday”); } If (day == 5){System.out.println(“Thursday”); } If (day == 6) {System.out.println(“Friday”); } If (day == 7) {System.out.println(“Saturday”); } switch (day) { case 1: System.out.println(“Sunday”); break; case 2: System.out.println(“Monday”); break; case 3: System.out.println(“Tuesday”); break; case 4: System.out.println(“Wednesday”); break; case 5: System.out.println(“Thursday”); break; case 6: System.out.println(“Friday”); break; case 7: System.out.println(“Saturday”); break; default: System.out.println(“Illegal Value ” + day); }

  24. Logical StatementsWhile • While statement is used to continually execute a block of statements while a condition remains true. • Syntax • while (expression) { statement } • Operation • First, the while statement evaluates expression, which must return a boolean value. • If the expression returns true, then the while statement executes the statement(s) associated with it. • The while statement continues testing the expression and executing its block until the expression returns false. int i = 0; while (i < 100) { System.out.println(i); i++; }

  25. Logical Statementsdo-while • do-while is similar to while statement that instead of evaluating the expression at the top of the loop, evaluates the expression at the bottom. • Statements associated with a do-while are executed at least once • Syntax • do { statement(s) } while (expression); • Operation • First the do statement executes the statement(s) associated with it. • Then the while statement evaluates expression that must return a boolean. • The do statement continues executing its block and the while statement continues testing the expression until the expression returns false. • Example int i = 0; do { System.out.println(i); i++; } while (i < 100)

  26. Logical StatementsFor • for statement provides a compact way to iterate over a range of values. • Syntax • for (initialization; termination; increment) { statement } • The initialization is an expression that initializes the loop-it's executed once at the beginning of the loop. • The termination expression determines when to terminate the loop. This expression is evaluated at the top of each iteration of the loop. When the expression evaluates to false, the loop terminates. • Finally, increment is an expression that gets invoked after each iteration through the loop. • e.g. Example for (int i = 0; i < 10; i++) { System.out.println(“My value is “+i); }

  27. Logical StatementsBreak • Break causes an exit from the innermost enclosing loop. • Break statements in loops should usually be avoided as they alter the flow of control associated with loop statements • from a clear "in at the top" to "out at the bottom" to something which is less obvious. • A break statement can sometimes be used "legitimately" to "break out" of a continuous loop. • However, in most cases there is an alternative strategy that will avoid the use of a break. • Continue: causes the current iteration of the program to stop and the next to continue. e.g. for (int i=0; i<100; i++) { System.out.println(“ Square of “ + i + “ = “ + i*i); if (i*i > 10000) break; }

  28. Logical StatementsContinue • A continue statement returns to the beginning of the innermost enclosing loop without completing the rest of the statements in the body of the loop (for, while and do-while). • If you're in a for loop, the counter is incremented. • Rarely used in practice • e.g. for (int i = 0; i < m.length; i++) { if (m[i] % 2 == 0) continue; // process odd elements... System.out.println(“Square of “ + i + “ = “ + i*i); }

  29. Recap

  30. RecapStatements • Statements are roughly equivalent to sentences in natural languages. • A statement forms a complete unit of execution. • It has many different types • Variable Declaration Statement • Expression Statement • Assignment Statement • Method Call Statement • Control Flow Statement • Variable declaration statements are used to identify the type of the variable that is being declared • These statements start with a type and end with a semicolon

  31. RecapExpression Statements • Expression is a series of variables, operators, and method calls (constructed according to the syntax of the language) that evaluates to a single value. • Expression Statements are formed by adding a semicolon at end of expression. • Assignment statement • Any expression involving the assignment operator. • e.g. area = length * width; • Method Call Statement • Method call expression does not involve assignment. • e.g. System.out.println(“This is a test”);

  32. RecapBlocks and Empty/Null Statements • Block is a group of statements enclosed in braces. Blocks can occur within blocks and are called nested blocks e.g. { float length = 2; float width = 2; float area = length * width; System.out.println(“area = “ + area);}  • Empty or Null Statement – It is just a semicolon all by itself and results in no action. e.g. x = 2; ; ;

  33. RecapRelational & Equality Operators • Boolean Expressions • Evaluate to true or false • All conditional statements require Boolean expressions to decide flow of logic • Relational & Equality Operators • used for comparing numeric values < > <=>=== != • These operators can be used between any two numeric values, e.g. int a = 10; int b = 20; int c = 15 a > b  false a < b  true c < 10  false

  34. RecapLogical Operators • These are used for combining multiple logical statements • Three logical operators • && - and • ! - not • || - or

  35. RecapLogical Statements • if statement • conditional statement which proceeds based on the evaluation of an expression   • if (boolean-expression) then statement • if-else statement • bi-directional logic expression • if (boolean expression) Statement11 else Statement2 • Nesting of if and if else statements • Allows complex logic to be modeled • Dangling else • else goes with the closest if statement

  36. RecapSwitch Statement • Switch is a multidirectional logic statement. • Switch(op) { • case a: statementa; • break; • case b: statementb; • break; • … • default: • statement; • } • Notes • Only one default statement in the switch • Case and Default cannot occur outside of the switch • break – exits the switch statement • Without break execution falls to next statement in the succeeding case • By not using break, you can combine multiple cases

  37. RecapLoops or iterations • while Statement while (expression) statement • do-while is similar to while where expression evaluated at bottom. • do { statement(s) } while (expression); • for Statement for(init statement; termination expression; increment statement) { block of statements } • break and continue • break: causes an exit from the innermost enclosing loop. • continue: causes the current iteration of the program to stop and the next to continue.

More Related