Control Statements Review CSC 123 Fall 2018 Howard Rosenthal

Size: px
Start display at page:

Download "Control Statements Review CSC 123 Fall 2018 Howard Rosenthal"

Transcription

1 Control Statements Review CSC 123 Fall 2018 Howard Rosenthal

2 Lesson Goals Review some of Java s control structures Review how to control the flow of a program via selection mechanisms Understand if, if-else, else-if and switch statements Build programs with nested layers of decision making Building blocks of execution code Review how to deal with the dangling else Understand the conditional operator Review the following three repetition structures in Java, their syntax, their similarities and differences, and how to avoid common errors when using them: while do-while for Review nested looping Review how to use break statements to exit a loop Review and expand knowledge of blocks and scope 2

3 3

4 Control Structures in Java There are three control structures in Java Sequence Structure Built into Java Ensures that statements execute one after the other in the order they are written, unless directed otherwise Selection Structure Based on truth or falsity In Java includes the if, if else, if... else if, and switch statements Repetition Structure Allows for repetition of the same group of statements multiple times, as long as a condition is met In Java includes the do, do while, for, and enhanced for statements Also known as iteration statements or looping statements 4

5 Two Way Decisions Windshield wipers are controlled with an ON-OFF switch. The flowchart at right shows how this decision is made. Start at the top of the chart then follow the line to the question: is it raining? The answer is either true or false. If the answer is true, follow the line labeled True, perform the instructions in the box "wipers on", follow the line to "continue". If the answer is false, follow the line labeled False, perform the instructions in the box "wipers off", follow the line to "continue". The windshield wiper decision is a two-way decision (sometimes called a binary decision). The decision seems small, but in programming, complicated decisions are made by executing many small decisions. 5

6 The Basic Syntax of the if Statement if (boolean expression) statement 1; statement 2; o 0 o statement n; The statements inside the block (delineated by a pair of braces) are executed only if the boolean statement (in parentheses) is true You should use the braces even if there is only a single statement inside the block even though this isn t required No semicolon on the if statement An if with a single statement following it does not require curly braces, however, it is best to use them all the time at first if (boolean expression) statement 1; 6

7 Basic Terminology An if statement is also called a conditional or selection statement The phrase if (boolean expression) is called the if clause The boolean expression itself is called the condition The statements inside the curly braces comprise a block You can nest if statements inside each other Write out the statements that will add 3 to int x initialized to 4 if the boolean value y is true. Initialize y to either true or false. 7

8 Answer boolean y = true; int x = 4; if (y == true) x = x+3; 8

9 A Very Simple Example public class SimpleIfStatementDemo1 public static void main(string [] args) //Declaring a variable "test" and initializing it with a value 10 int test = 10; //Checking if "test" is greater than 5 if (test > 5) //This block will be executed only if "test" is greater than 5 System.out.printf("Success\n"); //The if block ends. System.out.printf("Executed successfully\n"); 9

10 The Basic Syntax of the if-else Statement Similar to the if statement, but exclusively executes an alternative set of statement(s) if the conditional is false if (boolean expression) // always evaluates to either true or false statement 1; statement 2; o 0 o statement n; else statement a; statement b; o 0 o statement x; Note: Once again if there is only a single statement then braces are not required if (boolean expression) // always evaluates to either true or false statement 1; else statement a; 10

11 A Simple Example of if-else import java.util.scanner; public class NumberTester public static void main (String[] args) Scanner keyboard = new Scanner( System.in ); int num; System.out.printf ("Enter an integer: "); num = keyboard.nextint(); if ( num < 0 ) System.out.printf("The number is %d negative\n, num); num = num +5; else System.out.printf("The number %d is zero or positive\n, num); num = num -4; System.out.printf("The number is now %d, num ); System.out.printf("Good-bye for now\n"); 11

12 if else if Syntax Allows for testing for multiple different conditions Only the first case that tests as true will be executed If there is no else statement at the end then it is possible that none of the blocks are executed if (boolean expression) // always evaluates to either true or false statement 1; statement 2; o 0 statement n; else if (boolean expression) // always evaluates to true or false statement a; statement b; o 0 statement x; else //optional statement a; statement b; o 0 statement x; 12

13 An else if Example //This program assigns a letter grade based on a character grade import java.util.scanner; class IfElseIfDemo public static void main(string[] args) Scanner keyboard = new Scanner(System.in); System.out.printf("Enter the grade: "); int testscore = keyboard.nextint(); char grade; if (testscore >= 90) grade = 'A'; else if (testscore >= 80) grade = 'B'; else if (testscore >= 70) grade = 'C'; else if (testscore >= 60) else grade = 'D'; grade = 'F'; System.out.printf("Grade = %c\n, grade); Note: If you reverse the order then you would need to compare from bottom to top using <= Be careful in use of > vs. >=, etc. Remember, for any particular level of if, else-if, else, only the block after the first true statement is executed 13

14 A Note On boolean Expressions Be careful when using float or double type variables in boolean expressions Since there is always limited precision the possibility of an execution error exists, especially after more complex mathematical operations Example: (7.13*2.9)/(3.6*2.95) may be different than (7.13/(3.6*2.95))*2.9 See DecimalCompare.java and DecimalCompare2.java With DecimalCompare and println you can see where the difference shows up, which is far beyond the second decimal place 14

15 The Dangling if (1) Rule - An else matches with the nearest, previous, unmatched if that's not in a block. if ( num > 0 ) if ( num < 10 ) // Previous unmatched if System.out.printf( "aaa\n" ); else // Matches with previous unmatched if System.out.printf( "bbb\n" ); In the example above, the else is indented with the inner if statement. It prints "bbb" only if num > 0 and num >= 10, which means it prints only if num is 10 or greater. In the example below, the else is indented with the outer if statement. if ( num > 0 ) if ( num < 10 ) // Previous unmatched if System.out.printf( "aaa\n" ) ; else // Matches with previous unmatched if System.out.printf( "bbb\n" ) ; Which one does else match with? It picks the closest if unless there is a further clarification with the use of braces. This phenomenon of having to pick between one of two possible if statements is called the dangling else. Depending on which if the else is paired with, you can get different results. By now, you should know that Java doesn't pay attention to indentation. So both examples above are the same to Java, which means that it makes its determination based strictly on the syntax. To the Java Compiler there is no ambiguity (You can t say That s not what I really meant ) The compiler doesn t care about indenting. But you should for clarity 15

16 The Dangling if (2) What if we wanted the else to match with the first if? Then, we need braces. if ( num > 0 ) // Previous unmatched if if ( num < 10 ) // Unmatched, but in block System.out.printf( "aaa\n" ) ; else // Matches with previous unmatched if not in block System.out.printf( "bbb\n" ) ; //This prints if num <= 0. The else above matches with the previous, unmatched if not in the lower level block. This happens to be the outer if. There is an unmatched if that's the inner if, but that's in a block, so you can't match to it. Notice the else sits outside of the block. An else does not match to a previous if if the else is outside the block, where the closest if is found. 16

17 Dangling if Flows F if num > 0 if num > 0 F T T if num <10 F F if num <10 T Print aaa Print bbb T Print aaa Print bbb 17

18 The Dangling if The Rules Summarized Every else must match with a unique if. You can't have two or more else matching to the same if. If there is no matching if for an else, then your program won't compile. Each else must be preceded by a valid if Fortunately, your program fails to compile if you don't do this. Use Braces If you always use a block for if body and else body, then you can avoid confusion. However, it's useful to know the correct rules. 18

19 The switch Statement The syntax of a switch statement looks like: switch ( expr ) case literal1: case literal1 body case literal2: case literal2 body case literal3: case literal3 body default: default body Unlike if statements which contain a condition in the parentheses, switch contains an expression. This expression must be type byte, short, int, char or String. (Note: String is a newer feature, and the book says only int or char). Wrapper classes or an evaluation of an enumeration type can also be The semantics of switch are: Evaluate the expression Begin looking at each case, starting top to bottom If the value of the expression matches the case, then run the body Note: The case keyword has to be followed by a literal or a constant expression. It can't be a range If you run a break statement, you then exit the switch If you don't run a break statement, and you are at the end of a body, run the next body. Keep running bodies until you exit or hit a break statement If no match is made to the cases, run the default, if it exists. The default case is always run last, no matter where it appears. (It should be placed last, though). It is not mandatory to have a default statement. 19

20 Examples of the switch Statement int x = 4 ; switch ( x ) case 2: System.out.printf( "TWO\n" ) ; break ; case 4: System.out.printf( "FOUR\n" ) ; break ; case 6: System.out.printf( "SIX\n" ) ; break ; default: System.out.printf( "DEFAULT\n" ) ; See SwitchExample.java for full program This evaluates x to 4. It skips case 2 since the value 4 doesn't match 2. It does match case 4. It runs the body and prints FOUR". Then it runs break and exits the switch. 20

21 Examples of the switch Statement (2) Most of the times, you will end each case with break. Let's see what happens when you leave it out. int x = 4 ; switch ( x ) case 2: System.out.printf( "TWO\n" ) ; case 4: System.out.printf( "FOUR\n" ) ; case 6: System.out.printf( "SIX\n" ) ; default: System.out.printf( "DEFAULT\n" ) ; This prints out: FOUR SIX DEFAULT That's probably not what the user had in mind. Without the break, each time a body runs, it falls through and starts running the next body, and the next, after it matches the correct case. However, there are cases where you will want to execute multiple statements from multiple cases (see next example) See full program in SwitchExample2.java 21

22 Examples of the switch Statement (3) You can combine cases together. int x = 4 ; switch ( x ) case 1: case 3: case 5: System.out.printf( "ODD\n" ) ; break ; case 2: case 4: case 6: System.out.printf( "EVEN\n" ) ; break ; default: System.out.printf( "DEFAULT\n" ) ; See full program as SwitchExample3.java 22

23 A Few Additional Notes On the switch Statement Every switch statement can be implemented as an if/if else type statement It doesn t always work the other way around Obviously if the if/else is doing more complex comparisons or using boolean values or floating point numbers, then this can t be implemented in a switch statement 23

24 The Conditional Operator (1) The conditional operator is used like this: true-or-false-condition? value-if-true : value-if-false Here is how it works: The true-or-false-condition evaluates to true or false. That value selects one choice: If the true-or-false-condition is true, then evaluate the expression between? and : If the true-or-false-condition is false, then evaluate the expression between : and the end. The result of evaluation is the value of the entire conditional expression. This approach can be used in assignment statements 24

25 The Conditional Operator (2) int a = 7, b = 21; System.out.printf ("The min is: %d\n,(a < b? a : b ) ); The output would be: The min is 7 25

26 The Conditional Operator (3) double value = ; double absvalue; absvalue = ((value < 0 )? -value : value) ; The constant value is assigned to absvalue 26

27 An Example Using String Features import java.util.scanner; class RainTester public static void main (String[] args) Scanner keyboard = new Scanner( System.in ); String answer; System.out.printf("Is it raining? (Y or N): "); answer = keyboard.nextline(); if ( answer.equals("y") ) // is answer exactly "Y"? System.out.printf("Wipers On\n ); // true branch else System.out.printf("Wipers Off\n"); // false branch 27

28 A Few Note For Good Programming Always check your programs through each of the else cases, switch gates etc. To do this you need to develop a set of test cases A test case has components that describe an input, action or event and an expected response, to determine if a feature of an application is working correctly Your test cases must be expansive enough to cover the full range of possibilities For instance if there is a statement if (x>4) you don t need to test for every possibility greater than 4, but you need to test for at least one that is greater than 4, one that equals 4 and one that is less than 4. Typically we build a software test verification matrix 28

29 Sample Test Matrix Y X 1 R1 R2 R3 2 R4 R5 R6 5 R7 R8 R9 7 R10 R11 R12 Test for all possible combinations When there are multiple variables break the testing into smaller pieces Always test for different and outlying conditions Positive, zero and negative numbers First and last number and some element in the middle when processing a list 29

30 30

31 Introduction to Loops Many of the tasks performed by computers require repetition, often massive repetition Using repetitive syntax can make your code more concise and easier to write and debug Java has three types of repetitive constructs (also known as loops): while, dowhile or for Loops are built out of several fundamental statements because there are three things (in each of the three types of loops) that must be done correctly: The variables used to control the loop must be initialized correctly The ending condition for the loop must be tested correctly The body of the loop or the loop statement must change the condition that is tested otherwise you can wind up with an infinite loop Overlooking one of these aspects results in a defective loop and a sometimes difficult to find program bug! Usually each of these three considerations is located in a different spot. No wonder that loops often go wrong! You have to plan out the logic of your program in order to effectively use loops and conditionals Anything that can be done with one loop structure can be done with either of the other two, but sometimes the logic makes one preferable to the other 31

32 Types of Loops Type counting loop sentinel-controlled loop result-controlled loop Description Uses a loop control variable to count upwards or downwards (usually by an integer increment.) Example: Keep going until you run 100 miles. Loop keeps going until a special value is encountered in the data. Example: Keep going until you hit a red light. Loop keeps going until a test determines that the desired result has been achieved. Example. Keep going until you reach your home. 32

33 The while Statement Here is a program with a loop. It contains a while statement, followed by a block of code. Remember, a block is a group of statements enclosed in braces. // Example of a while loop public class WhileLoopExample1 public static void main (String[] args ) // start count out at one int count = 1; while ( count <= 3 ) System.out.printf( Count is: %d\n, count ); count = count + 1; // add one to count System.out.printf( "Done with the loop\n ); 33

34 The Basic Syntax of the while Statement while (condition) statement 1; statement 2; o 0 o statement n; You execute through the entire block repetitively until the condition is false unless you encounter a break statement The break will typically occur based on a separate condition tested with an if statement 34

35 Basic Terminology of the while Statement The condition is a boolean expression: something that evaluates to true or false The condition can be complicated, using many relational operators and logical operators. Due to the precision of integers, integers are almost always used as counters for loops A single statement is allowed Without braces only one statement is executed inside the loop The block or single executable statement is sometimes called the loop body If one of the statements in the while block doesn t eventually change the value of the condition then the loop goes on forever The while loop may not be executed at all if the initial condition is false There is no semi-colon after the while statement If you put one there you will end the loop before it executes anything 35

36 Counters Can Be Decremented Rather Than Incremented When The Need Arises Here is a program with a loop It contains a while statement, followed by a block of code The condition is checked when entering the loop, and for each iteration If the condition is false the loop is skipped over Remember, a block is a group of statements enclosed in braces. // Pseudocode example public class WhileLoopExample2 public static void main (String[] args ) int count = 2; // count is initialized while ( count >= 0 ) // count is tested System.out.printf( Count is: %d\n, count ); count = count - 1; // count is changed by -1 System.out.printf( "Done counting down\n" ); 36

37 Using a Flag To Guarantee Execution Of a While Statement Sometimes you want to ensure at least one execution of a loop so you use a boolean flag set to true (or false depending on the statement) /// Example of a while loop with flag import java.util.scanner; public class WhileLoopFlag public static void main (String[] args ) int number, sum = 0; boolean flag = true; // flag is initialized Scanner keyboard = new Scanner(System.in); while ( flag == true) // flag is tested System.out.printf( Enter an integer value, with a zero ending the accumulation: ); number =keyboard.nextint(); if (number == 0) flag = false; else sum = sum+number; System.out.printf( Sum is %d\n, sum); 37

38 The do-while Statement Here is a program with a loop It contains a do statement, followed by a block of code, followed by a while statement The condition is checked at the end of each execution of the loop which is always executed at least once // Example of a do-while loop that executes only once public class DoWhileLoopExample public static void main (String[] args ) int count = 1000; // initialize do System.out.printf( Count is: %d\n, count ); count++ ; while ( count < 10 ); // test System.out.printf( "Done with the loop\n" ); 38

39 The Basic Syntax of the do-while Statement do statement1; statement2; o 0 0 statementn; while (condition); 39

40 Basic Terminology of the do-while Statement The condition is a boolean expression: something that evaluates to true or false The condition can be complicated, using many relational operators and logical operators A single statement is allowed Without braces to create a block only one statement is executed inside the loop The block or single executable statement is sometimes called the loop body. The do-while is always executed at least once, if the do statement is executed There is a semi-colon after the while statement in a dowhile 40

41 The for Statement Here is a program with a loop. It contains a for statement, followed by a block of code. A block is a group of statements enclosed in braces. // Example of a for loop public class ForLoopExample public static void main (String[] args ) int sum=0; for ( int count = 0; count <= 5; count++ ) sum = sum + count ; System.out.printf( Count is: %d, count); System.out.printf( \nsum is: %d\n, sum ); sum = 0 Initialization count = 0 loop condition count <= 5 sum = sum + count Print count count++ Print sum false 41

42 The Basic Syntax of the for Statement for (initialization; loop condition; update statements) statement1; statement2; o 0 0 statementn; 42

43 Basic Terminology of the for Statement initialization Used to initialize basic variables used in the loop condition More than one variable can be set, separated by commas You can declare the variable in the for statement, but then it is only valid within the for loop within which it is created for (int j=3, k=4; ; ) If no variables are set, you must have a ; before the loop condition this typically means that the variable has been set prior to the for statement The initialization portion of the for statement is only executed once, each time you enter the loop. This allows you to nest loops loop condition A boolean expression evaluates as true or false Evaluated at the beginning of each loop Although this statement can be left out, leaving it out could lead to an infinite do loop, unless you execute a break statement inside the loop 43

44 Basic Terminology of the for Statement (2) update statement(s) Increases or decreases a value, typically one or more used in the loop condition Always executed at the end of the loop body Can include more than one statement, separated by commas for( ; ; i++, j= j+5) Usually use postfix notation, but in this case prefix work exactly the same Notes: If you are eliminating multiple parts of a for statement it may be better to use a while or do-while Don t stuff too many extraneous things into the for statement, you ll confuse yourself Most people use for statements when executing a loop a specific number of times 44

45 Nested Loops A nested loop is a (inner) loop that appears in the loop body of another (outer) loop. The inner or outer loop can be any type: while, do while, or for. For example, the inner loop can be a while loop while an outer loop can be a for loop. Of course, they can be the same kind of loops too. Inner loops always stay completely inside their outer loops An inner loop may be skipped over during the execution of an outer loop If the inner loop has a tested condition that starts out false or If the loop is inside of an if block that isn t executed, then that loop wouldn t be executed 45

46 Nested Loop Example // Example of nested loop that prints a rectangle of stars public class NestedLoops public static void main (String[] args ) int height =5; int width = 4; for ( int i = 0 ; i < height ; i++ ) for ( int j = 0 ; j< width ; j++ ) System.out.printf( %s, "*" ) ; System.out.printf( \n" ) ; 46

47 The Multiplication Table Is A Good Example Of Nested Looping

48 How Can We Use Loops To Help Construct This Table 1. Write the Top Row a. Use a loop to write the numbers Draw a horizontal line line 3. For each row a. Write the row number b. Draw a vertical line c. For each column 1) Calculate the product 2) Write the product d. Skip to the next row Now we ll look at the solution in MultTable.java and MultTablePrintln.java 48

49 The break Statement Used to immediately exit the innermost loop that the break is found within, unless the loop is labeled Loop is labeled with looplabelname: followed by the loop the name begins with an alpha character followed by alphas, number, $, _ characters The next statement executed is the first statement beyond the scope of that loop If you label a loop the break statement can be used to exit through an outer nesting We ll look at SimpleBreakLoop.java and BreakLabeledLoop.java Note: any bock can be labeled, not just iterations label: You can then use a break label; to to exit out of the block with the name label 49

50 The continue Statement When executed in a repetition statement, the remainder of the statements in that iteration of the loop body are skipped, and the next iteration test is executed. In the for statement the update statements are executed We ll look at the ContinueExample.java 50

51 The flag or sentinel A flag or sentinel is a value appended to a data collection that signals the end of the data. The idea of a sentinel controlled loop is that there is a special value (the sentinel) that is used to control when the loop is done. In following code fragment, the user enters a zero when the sum is complete. Zero is the sentinel. Here is how the program should work import java.util.scanner; // Add up integers entered by the user. // After the last integer, the user enters a 0 class AddUpNumbers public static void main (String[] args ) Scanner keyboard = new Scanner( System.in ); int value, sum = 0; System.out.printf("Enter first integer (enter 0 to quit): ); value = keyboard.nextint(); //we initialize value before entering the loop while ( value!= 0 ) sum = sum + value; System.out.printf( Enter next integer (enter 0 to quit): ); value = keyboard.nextint(); //update value inside the loop System.out.printf("Sum of the integers is: %d\n, sum); 51

52 The hasnext() Method of the Scanner class The hasnext() method keeps reading data unto there is no more data to read When there is no more data to read it returns false Once we start reading from files (Chapter 9), that means that it will test to see if we have reached the end of the file Working interactively we can use a while or do while and enter <Ctrl> z on a Windows System or <Ctrl> d on a Mac to indicate end of data See HasNextTest.java 52

53 Bad Input Data There are cases when erroneous data is entered There are many options Request revised data - preferred Exit the program In order to do either you must check the data first Note: Some inputs will cause the program to crash Can you name 0ne? We will learn how to capture error conditions and perform soft exits Look at ErroneousData.java We will look at GeneralAverage.java in a few minutes 53

54 Scope of a Variable (1) A variable s scope is determined by the highest level of braces within which it is defined. It works at that level and all nested level If you use the same variable name in an outer and nested blocks, an error will occur. In Java you cannot have local variables with the same name in overlapping scope If you exit a block where a variable is defined you can reuse the variable name It s values are separate from the originally named variable Don t use the same variable name twice in a program it only confuses things. (exception may reuse loop counters) You are allowed to continuously redeclare a variable in the same statement within a loop again this allows for nesting Scope is extremely important to understand in nested loops. Once you leave the loop a variable declared in the loop no longer exists. 54

55 Scope of a Variable (2) // Demonstrate block scope. public class Scope public static void main(string args[]) int n1; // Visible in main n1 = 10; if (n1 == 10) // start new scope int n2 = 20; // visible only to this block // n1 and n2 both visible here. System.out.printf( n1 = %d n2 = %d\n, n1, n2); // n2 = 100; // Error! n2 not known here // n1 is still visible here. System.out.printf("n1 is %d\n, n1); 55

56 Scope of a Variable (3) public class LifeTime public static void main(string args[]) int i; for(i = 0; i < 3; i++) int y = -1; System.out.printf("y is : %d\n, y); Variable y is declared inside for loop block Each time when control goes inside for loop block the y variable is declared and used in loop When control goes out of the for loop then the variable becomes inaccessible 56

57 Scope of a Variable (4) public class ScopeInvalid public static void main(string args[]) int num = 1; // creates a new scope int num = 2; // Compile-time error // num already defined public class ScopeValid public static void main(string args[]) // creates a new scope int num = 1; // creates a new scope int num = 2; Okay doesn t overlap with the num in the prior b;ock 57

58 58

59 Programming Exercise 1 Sort Three Write a program that requests the entry of three integers and displays the numbers in order from lowest to highest. Note: You will need to test all possible cases 59

60 Programming Exercise 2 TollFreeNumbers As of the year 2008, a 10 digit number that begins with 800, 888, 877, or 866 has been toll free. Write a program that reads in a 10 digit phone number and displays a message that states whether the number is toll free or not. Hints: Use long as the variable type, extract first three digits with integer arithmetic 60

61 Programming Exercises 3 GradeConversion A certain school assigns number grades ranging from Write a program that queries the user for a numerical score and converts the score to a letter grade according to thee following criteria: 0-59:F; D: 70-72, C-: 73-76, C: C+; 80-82: B-; 83-86: B; 87-89: B+; 90-92: A-; 93-96: A; A+ 61

62 Programming Exercise 4 GeneralAverage Write a program that calculates the average of n test scores, such that each score is an integer in the range 0 to 100. There should be a minimum of two scores. Your program should first prompt for an integer n and then request n scores. There should be a minimum of two scores. Your program should also test for invalid data. If a user enters a number outside the correct range, the program should prompt for another value. Round the average to the closest integer. 62

63 Programming Exercise 5 MorePictures Write a program that accepts an integer n and prints out the following picture of a diamond with 2n-1 rows 1 X 2 X X X 3 X X X X X n XXXXXXXXXXX (2n-1 times). 2n-1 X 63

64 Pseudo Code for More Pictures Read in n to determine total number of rows as 2n-1 Calculate the width = 2*n-1 For each row in top half up from 1 to n Calculate the number of x s (2*rowNumber-1) Calculate the blanks = (width numexes)/2 Print the blanks (a loop) Print the X s (a loop) Skip to next line For each row in the bottom half from n-1 to 1 Calculate the number of x s (2*rowNumber-1) Calculate the blanks = (width numexes)/2 Print the blanks (a loop) Print the x s (a loop) Skip to next line 64

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Repe$$on CSC 121 Spring 2017 Howard Rosenthal Repe$$on CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Learn the following three repetition structures in Java, their syntax, their similarities and differences, and how to avoid common errors when

More information

Selec%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 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 information

Selec%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 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 information

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Repe$$on CSC 121 Fall 2015 Howard Rosenthal Repe$$on CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while

More information

Repetition CSC 121 Fall 2014 Howard Rosenthal

Repetition CSC 121 Fall 2014 Howard Rosenthal Repetition CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while

More information

REPETITION CONTROL STRUCTURE LOGO

REPETITION CONTROL STRUCTURE LOGO CSC 128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING REPETITION CONTROL STRUCTURE 1 Contents 1 Introduction 2 for loop 3 while loop 4 do while loop 2 Introduction It is used when a statement or a block of

More information

Chapter 3. Selections

Chapter 3. Selections Chapter 3 Selections 1 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator 6. The Switch Statement 7. Useful Hints 2 1. Flow of

More information

Introduction. C provides two styles of flow control:

Introduction. C provides two styles of flow control: Introduction C provides two styles of flow control: Branching Looping Branching is deciding what actions to take and looping is deciding how many times to take a certain action. Branching constructs: if

More information

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003 Control Flow COMS W1007 Introduction to Computer Science Christopher Conway 3 June 2003 Overflow from Last Time: Why Types? Assembly code is typeless. You can take any 32 bits in memory, say this is an

More information

STUDENT LESSON A12 Iterations

STUDENT 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 information

Flow Control. CSC215 Lecture

Flow Control. CSC215 Lecture Flow Control CSC215 Lecture Outline Blocks and compound statements Conditional statements if - statement if-else - statement switch - statement? : opertator Nested conditional statements Repetitive statements

More information

Repetition Structures

Repetition Structures Repetition Structures Chapter 5 Fall 2016, CSUS Introduction to Repetition Structures Chapter 5.1 1 Introduction to Repetition Structures A repetition structure causes a statement or set of statements

More information

Chapter 4: Making Decisions

Chapter 4: Making Decisions Chapter 4: Making Decisions 4.1 Relational Operators Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than or equal to

More information

Chapter 4: Making Decisions

Chapter 4: Making Decisions Chapter 4: Making Decisions CSE 142 - Computer Programming I 1 4.1 Relational Operators Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >=

More information

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I CS 106 Introduction to Computer Science I 06 / 04 / 2015 Instructor: Michael Eckmann Today s Topics Questions / comments? Calling methods (noting parameter(s) and their types, as well as the return type)

More information

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan Lecture 08-1 Programming in C++ PART 1 By Assistant Professor Dr. Ali Kattan 1 The Conditional Operator The conditional operator is similar to the if..else statement but has a shorter format. This is useful

More information

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the

More information

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution. Repetition Structures Introduction to Repetition Structures Chapter 5 Spring 2016, CSUS Chapter 5.1 Introduction to Repetition Structures The Problems with Duplicate Code A repetition structure causes

More information

Full file at

Full 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 information

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements COMP-202 Unit 4: Programming With Iterations CONTENTS: The while and for statements Introduction (1) Suppose we want to write a program to be used in cash registers in stores to compute the amount of money

More information

Chapter 4: Making Decisions. Copyright 2012 Pearson Education, Inc. Sunday, September 7, 14

Chapter 4: Making Decisions. Copyright 2012 Pearson Education, Inc. Sunday, September 7, 14 Chapter 4: Making Decisions 4.1 Relational Operators Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than or equal to

More information

Program Development. Chapter 3: Program Statements. Program Statements. Requirements. Java Software Solutions for AP* Computer Science A 2nd Edition

Program Development. Chapter 3: Program Statements. Program Statements. Requirements. Java Software Solutions for AP* Computer Science A 2nd Edition Chapter 3: Program Statements Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition Program Development The creation of software involves four basic activities: establishing

More information

Chapter 3: Program Statements

Chapter 3: Program Statements Chapter 3: Program Statements Presentation slides for Java Software Solutions for AP* Computer Science 3rd Edition by John Lewis, William Loftus, and Cara Cocking Java Software Solutions is published by

More information

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false. CS101, Mock Boolean Conditions, If-Then Boolean Expressions and Conditions The physical order of a program is the order in which the statements are listed. The logical order of a program is the order in

More information

LECTURE 04 MAKING DECISIONS

LECTURE 04 MAKING DECISIONS PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 04 MAKING DECISIONS

More information

Conditionals and Loops

Conditionals and Loops Conditionals and Loops Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing steps in a loop Chapter 5 focuses on: boolean expressions conditional

More information

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18 Assignment Lecture 9 Logical Operations Formatted Print Printf Increment and decrement Read through 3.9, 3.10 Read 4.1. 4.2, 4.3 Go through checkpoint exercise 4.1 Logical Operations - Motivation Logical

More information

Repetition, Looping. While Loop

Repetition, Looping. While Loop Repetition, Looping Last time we looked at how to use if-then statements to control the flow of a program. In this section we will look at different ways to repeat blocks of statements. Such repetitions

More information

Introduction to Java & Fundamental Data Types

Introduction 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 information

Conditional Statement

Conditional Statement Conditional Statement 1 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition Also called Branching How do we specify conditions?

More information

3 The L oop Control Structure

3 The L oop Control Structure 3 The L oop Control Structure Loops The while Loop Tips and Traps More Operators The for Loop Nesting of Loops Multiple Initialisations in the for Loop The Odd Loop The break Statement The continue Statement

More information

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting Unit 2, Part 2 Definite Loops Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting Let's say that we're using a variable i to count the number of times that

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All for repetition statement do while repetition statement switch multiple-selection statement break statement continue statement Logical

More information

CS 251 Intermediate Programming Java Basics

CS 251 Intermediate Programming Java Basics CS 251 Intermediate Programming Java Basics Brooke Chenoweth University of New Mexico Spring 2018 Prerequisites These are the topics that I assume that you have already seen: Variables Boolean expressions

More information

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Java 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 information

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs PDS Lab Section 16 Autumn-2017 Tutorial 3 C Programming Constructs This flowchart shows how to find the roots of a Quadratic equation Ax 2 +Bx+C = 0 Start Input A,B,C x B 2 4AC False x If 0 True B x 2A

More information

5. Control Statements

5. Control Statements 5. Control Statements This section of the course will introduce you to the major control statements in C++. These control statements are used to specify the branching in an algorithm/recipe. Control statements

More information

printf( Please enter another number: ); scanf( %d, &num2);

printf( Please enter another number: ); scanf( %d, &num2); CIT 593 Intro to Computer Systems Lecture #13 (11/1/12) Now that we've looked at how an assembly language program runs on a computer, we're ready to move up a level and start working with more powerful

More information

Topics. Chapter 5. Equality Operators

Topics. Chapter 5. Equality Operators Topics Chapter 5 Flow of Control Part 1: Selection Forming Conditions if/ Statements Comparing Floating-Point Numbers Comparing Objects The equals Method String Comparison Methods The Conditional Operator

More information

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017 Loops! Loops! Loops! Lecture 5 COP 3014 Fall 2017 September 25, 2017 Repetition Statements Repetition statements are called loops, and are used to repeat the same code mulitple times in succession. The

More information

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator. Chapter 5: Looping 5.1 The Increment and Decrement Operators Copyright 2009 Pearson Education, Inc. Copyright Publishing as Pearson 2009 Addison-Wesley Pearson Education, Inc. Publishing as Pearson Addison-Wesley

More information

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation Program Development Java Program Statements Selim Aksoy Bilkent University Department of Computer Engineering saksoy@cs.bilkent.edu.tr The creation of software involves four basic activities: establishing

More information

4.1. Chapter 4: Simple Program Scheme. Simple Program Scheme. Relational Operators. So far our programs follow a simple scheme

4.1. Chapter 4: Simple Program Scheme. Simple Program Scheme. Relational Operators. So far our programs follow a simple scheme Chapter 4: 4.1 Making Decisions Relational Operators Simple Program Scheme Simple Program Scheme So far our programs follow a simple scheme Gather input from the user Perform one or more calculations Display

More information

DECISION STRUCTURES: USING IF STATEMENTS IN JAVA

DECISION STRUCTURES: USING IF STATEMENTS IN JAVA DECISION STRUCTURES: USING IF STATEMENTS IN JAVA S o far all the programs we have created run straight through from start to finish, without making any decisions along the way. Many times, however, you

More information

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

COP 2000 Introduction to Computer Programming Mid-Term Exam Review he exam format will be different from the online quizzes. It will be written on the test paper with questions similar to those shown on the following pages. he exam will be closed book, but students can

More information

Controls Structure for Repetition

Controls Structure for Repetition Controls Structure for Repetition So far we have looked at the if statement, a control structure that allows us to execute different pieces of code based on certain conditions. However, the true power

More information

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 5. Repetition in Programs. Notes. Notes. Notes. Lecture 05 - Loops

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 5. Repetition in Programs. Notes. Notes. Notes. Lecture 05 - Loops Computer Science & Engineering 150A Problem Solving Using Computers Lecture 05 - Loops Stephen Scott (Adapted from Christopher M. Bourke) 1 / 1 Fall 2009 cbourke@cse.unl.edu Chapter 5 5.1 Repetition in

More information

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class CS0007: Introduction to Computer Programming Review General Form of a switch statement: switch (SwitchExpression) { case CaseExpression1:

More information

Pace University. Fundamental Concepts of CS121 1

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 information

Decisions. Arizona State University 1

Decisions. Arizona State University 1 Decisions CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 4 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

Flow of Control: Loops. Chapter 4

Flow of Control: Loops. Chapter 4 Flow of Control: Loops Chapter 4 Java Loop Statements: Outline The while statement The do-while statement The for Statement Java Loop Statements A portion of a program that repeats a statement or a group

More information

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++ Repetition Contents 1 Repetition 1.1 Introduction 1.2 Three Types of Program Control Chapter 5 Introduction 1.3 Two Types of Repetition 1.4 Three Structures for Looping in C++ 1.5 The while Control Structure

More information

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG Selections EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG Learning Outcomes The Boolean Data Type if Statement Compound vs. Primitive Statement Common Errors

More information

CS112 Lecture: Repetition Statements

CS112 Lecture: Repetition Statements CS112 Lecture: Repetition Statements Objectives: Last revised 2/18/05 1. To explain the general form of the java while loop 2. To introduce and motivate the java do.. while loop 3. To explain the general

More information

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Primitive 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 information

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved. Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the

More information

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite

More information

CSCE150A. Introduction. While Loop. Compound Assignment. For Loop. Loop Design. Nested Loops. Do-While Loop. Programming Tips CSCE150A.

CSCE150A. Introduction. While Loop. Compound Assignment. For Loop. Loop Design. Nested Loops. Do-While Loop. Programming Tips CSCE150A. Chapter 5 While For 1 / 54 Computer Science & Engineering 150A Problem Solving Using Computers Lecture 05 - s Stephen Scott (Adapted from Christopher M. Bourke) Fall 2009 While For 2 / 54 5.1 Repetition

More information

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto CS 170 Java Programming 1 The Switch Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Menu-Style Code With ladder-style if-else else-if, you might sometimes find yourself writing menu-style

More information

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Java application programming } Use tools from the JDK to compile and run programs. } Videos at www.deitel.com/books/jhtp9/ Help you get started

More information

2.8. Decision Making: Equality and Relational Operators

2.8. Decision Making: Equality and Relational Operators Page 1 of 6 [Page 56] 2.8. Decision Making: Equality and Relational Operators A condition is an expression that can be either true or false. This section introduces a simple version of Java's if statement

More information

Loops (while and for)

Loops (while and for) Loops (while and for) CSE 1310 Introduction to Computers and Programming Alexandra Stefan 1 Motivation Was there any program we did (class or hw) where you wanted to repeat an action? 2 Motivation Name

More information

Chapter 4: Conditionals and Loops

Chapter 4: Conditionals and Loops Chapter 4: Conditionals and Loops CS 121 Department of Computer Science College of Engineering Boise State University August 21, 2017 Chapter 4: Conditionals and Loops CS 121 1 / 69 Chapter 4 Topics Flow

More information

Java Coding 3. Over & over again!

Java Coding 3. Over & over again! Java Coding 3 Over & over again! Repetition Java repetition statements while (condition) statement; do statement; while (condition); where for ( init; condition; update) statement; statement is any Java

More information

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Review what an array is Review how to declare arrays Review what reference variables are Review how to pass arrays to methods Review

More information

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops COMP-202 Unit 4: Programming with Iterations Doing the same thing again and again and again and again and again and again and again and again and again... CONTENTS: While loops Class (static) variables

More information

Chapter 4: Loops and Files

Chapter 4: Loops and Files Chapter 4: Loops and Files Chapter Topics Chapter 4 discusses the following main topics: The Increment and Decrement Operators The while Loop Using the while Loop for Input Validation The do-while Loop

More information

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Loops and Files Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Chapter Topics o The Increment and Decrement Operators o The while Loop o Shorthand Assignment Operators o The do-while

More information

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Learn about repetition (looping) control structures Explore how to construct and use: o Counter-controlled

More information

Module 4: Decision-making and forming loops

Module 4: Decision-making and forming loops 1 Module 4: Decision-making and forming loops 1. Introduction 2. Decision making 2.1. Simple if statement 2.2. The if else Statement 2.3. Nested if Statement 3. The switch case 4. Forming loops 4.1. The

More information

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

! definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. ! We often use language like Indefinite loops while loop! indefinite loop: A loop where it is not obvious in advance how many times it will execute.! We often use language like " "Keep looping as long as or while this condition is

More information

Programming with Java

Programming 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 information

Chapter 3: Operators, Expressions and Type Conversion

Chapter 3: Operators, Expressions and Type Conversion 101 Chapter 3 Operators, Expressions and Type Conversion Chapter 3: Operators, Expressions and Type Conversion Objectives To use basic arithmetic operators. To use increment and decrement operators. To

More information

Programming for Engineers Iteration

Programming for Engineers Iteration Programming for Engineers Iteration ICEN 200 Spring 2018 Prof. Dola Saha 1 Data type conversions Grade average example,-./0 class average = 23450-67 893/0298 Grade and number of students can be integers

More information

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

More information

Loops. CSE 114, Computer Science 1 Stony Brook University

Loops. 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 information

Decision Making in C

Decision Making in C Decision Making in C Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed

More information

LECTURE 5 Control Structures Part 2

LECTURE 5 Control Structures Part 2 LECTURE 5 Control Structures Part 2 REPETITION STATEMENTS Repetition statements are called loops, and are used to repeat the same code multiple times in succession. The number of repetitions is based on

More information

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017 Control Structures Lecture 4 COP 3014 Fall 2017 September 18, 2017 Control Flow Control flow refers to the specification of the order in which the individual statements, instructions or function calls

More information

Fundamental of Programming (C)

Fundamental 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 information

Lecture 7 Tao Wang 1

Lecture 7 Tao Wang 1 Lecture 7 Tao Wang 1 Objectives In this chapter, you will learn about: Interactive loop break and continue do-while for loop Common programming errors Scientists, Third Edition 2 while Loops while statement

More information

Loops and Files. of do-while loop

Loops and Files. of do-while loop L E S S O N S E T 5 Loops and Files PURPOSE PROCEDURE 1. To introduce counter and event controlled loops 2. To work with the while loop 3. To introduce the do-while loop 4. To work with the for loop 5.

More information

Chapter 17. Iteration The while Statement

Chapter 17. Iteration The while Statement 203 Chapter 17 Iteration Iteration repeats the execution of a sequence of code. Iteration is useful for solving many programming problems. Interation and conditional execution form the basis for algorithm

More information

Chapter 5: Control Structures

Chapter 5: Control Structures Chapter 5: Control Structures In this chapter you will learn about: Sequential structure Selection structure if if else switch Repetition Structure while do while for Continue and break statements S1 2017/18

More information

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva All copyrights reserved - KV NAD, Aluva Dinesh Kumar Ram PGT(CS) KV NAD Aluva Overview Looping Introduction While loops Syntax Examples Points to Observe Infinite Loops Examples using while loops do..

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All rights reserved. Java application A computer program that executes when you use the java command to launch the Java Virtual Machine

More information

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Learn about repetition (looping) control structures Explore how to construct and use: o Counter-controlled

More information

Computer Programming I - Unit 5 Lecture page 1 of 14

Computer Programming I - Unit 5 Lecture page 1 of 14 page 1 of 14 I. The while Statement while, for, do Loops Note: Loop - a control structure that causes a sequence of statement(s) to be executed repeatedly. The while statement is one of three looping statements

More information

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018 Motivating Examples (1.1) Selections EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG 1 import java.util.scanner; 2 public class ComputeArea { 3 public static void main(string[] args)

More information

Control Structures in Java if-else and switch

Control Structures in Java if-else and switch Control Structures in Java if-else and switch Lecture 4 CGS 3416 Spring 2017 January 23, 2017 Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 1 / 26 Control Flow Control flow refers to the specification

More information

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Hello, in this lecture we will learn about some fundamentals concepts of java.

More information

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 5: Control Structures II (Repetition) Why Is Repetition Needed? Repetition allows you to efficiently use variables Can input,

More information

Introduction to Java Applications

Introduction 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 information

Chapter 5: Loops and Files

Chapter 5: Loops and Files Chapter 5: Loops and Files 5.1 The Increment and Decrement Operators The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++; is the same as val = val + 1;

More information

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

Flow of Control. Flow of control The order in which statements are executed. Transfer of control 1 Programming in C Flow of Control Flow of control The order in which statements are executed Transfer of control When the next statement executed is not the next one in sequence 2 Flow of Control Control

More information

Text Input and Conditionals

Text Input and Conditionals Text Input and Conditionals Text Input Many programs allow the user to enter information, like a username and password. Python makes taking input from the user seamless with a single line of code: input()

More information

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed Programming in C 1 Flow of Control Flow of control The order in which statements are executed Transfer of control When the next statement executed is not the next one in sequence 2 Flow of Control Control

More information

Information Science 1

Information Science 1 Information Science 1 Fundamental Programming Constructs (1) Week 11 College of Information Science and Engineering Ritsumeikan University Topics covered l Terms and concepts from Week 10 l Flow of control

More information

Chapter 4: Loops and Files

Chapter 4: Loops and Files Chapter 4: Loops and Files Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter Topics Chapter 4 discusses the following main topics: The Increment and Decrement

More information

Lesson 6A Loops. By John B. Owen All rights reserved 2011, revised 2014

Lesson 6A Loops. By John B. Owen All rights reserved 2011, revised 2014 Lesson 6A Loops By John B. Owen All rights reserved 2011, revised 2014 Topic List Objectives Loop structure 4 parts Three loop styles Example of a while loop Example of a do while loop Comparison while

More information