COMP Introduction to Programming If-Else Statement, Switch Statement and Loops

Similar documents
COMP 110 Introduction to Programming. What did we discuss?

COMP 110 Introduction to Programming. What did we discuss?

COMP Introduction to Programming Midterm Review

COMP Flow of Control: Branching 2. Yi Hong May 19, 2015

Flow of Control Branching 2. Cheng, Wei COMP May 19, Title

COMP 110 Introduction to Programming. What did we discuss?

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

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 Fall 2016 Howard Rosenthal

Flow of Control: Loops

4. Flow of Control: Loops

4. Flow of Control: Loops. Objectives. Java Loop Statements 10/10/12. Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich

Flow of Control. Chapter 3. Chapter 3 1

Chapter 3. Flow of Control. Branching Loops exit(n) method Boolean data type and expressions

COMP Introduction to Programming Primitive Types, Strings and Console I/O

Darrell Bethea May 25, 2011

Flow of Control: Loops. Objectives. Java Loop Statements: Outline 6/27/2014. Chapter 4

Control Structures in Java if-else and switch

CONDITIONAL EXECUTION: PART 2

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

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

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

School of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn

Flow of Control. Branching Loops exit(n) method Boolean data type and expressions

Flow of Control: Loops. Chapter 4

Control Structures in Java if-else and switch

Loops. CSE 114, Computer Science 1 Stony Brook University

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

4. Flow of Control: Loops. Objectives. Java Loop Statements: Outline 10/3/11. Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich

4. Flow of Control: Loops

Repetition Structures

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

Flow Control. CSC215 Lecture

Quiz Determine the output of the following program:

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Flow of Control: Loops

Chapter Goals. Contents LOOPS

Programming for Engineers Iteration

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

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

LAB 4.1 Relational Operators and the if Statement

REPETITION CONTROL STRUCTURE LOGO

Flow of Control. Chapter

Information Science 1

Announcements. HW0 is posted on schedule, due next Friday at 9pm (pretty easy)

switch case Logic Syntax Basics Functionality Rules Nested switch switch case Comp Sci 1570 Introduction to C++

int j = 0, sum = 0; for (j = 3; j <= 79; j++) { sum = sum + j; System.out.println(sum); //Show the progress as we iterate thru the loop.

Accelerating Information Technology Innovation

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Repetition, Looping. While Loop

Selections. CSE 114, Computer Science 1 Stony Brook University

Repetition, Looping CS101

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

Logic & program control part 3: Compound selection structures

Decision Structures. Selection. Selection options (in Java) Plain if s (3 variations) Each action could be any of: if else (3 variations)

Stepwise Refinement. Lecture 12 COP 3014 Spring February 2, 2017

Information Science 1

McGill University School of Computer Science COMP-202A Introduction to Computing 1

Module 2: Choice and Iteration

8. Control statements

Spring 2013 COMP Midterm Exam Solutions March 07, 2013

Handout 4 Conditionals. Boolean Expressions.

Problem Solving With Loops

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

Selection Statements. Pseudocode

DECISION CONTROL AND LOOPING STATEMENTS

5. Control Statements

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

CISC-124. Casting. // this would fail because we can t assign a double value to an int // variable

bool bool - either true or false

Computer Programming I - Unit 5 Lecture page 1 of 14

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

Announcements. Homework 0: using cin with 10/3 is NOT the same as (directly)

1007 Imperative Programming Part II

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

Chapter 2. Flow of Control. Copyright 2016 Pearson, Inc. All rights reserved.

In this lab, you will learn more about selection statements. You will get familiar to

STUDENT LESSON A12 Iterations

Flow of Control: Programs can control the order in which their instructions are executed. Four types of flow:

Introduction. C provides two styles of flow control:

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Topics. Chapter 5. Equality Operators

3chapter C ONTROL S TATEMENTS. Objectives

In this chapter, you will:

More Programming Constructs -- Introduction

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.

Text Input and Conditionals

Type Conversion. and. Statements

Unit 3 Decision making, Looping and Arrays

COMP 202 Java in one week

Lecture 4. CS118 Term planner. The simple if statement. Control flow: selection. The if... else statement cont... The if... else statement.

Claremont McKenna College Computer Science

Introduction to Object-Oriented Programming

Following is the general form of a typical decision making structure found in most of the programming languages:

1. The programming language C is more than 30 years old. True or False? (Circle your choice.)

Glossary. (Very) Simple Java Reference (draft, v0.2)

ECE 122. Engineering Problem Solving with Java

CS1004: Intro to CS in Java, Spring 2005

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

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

Transcription:

COMP 110-003 Introduction to Programming If-Else Statement, Switch Statement and Loops February 5, 2013 Haohan Li TR 11:00 12:15, SN 011 Spring 2013

Announcement Office hour is permanently changed Wednesday, 12:30PM 2:30PM I ll try to be at office before 3:30PM

Review: If-Else Statement If statement if (boolean expression) { statements; } other statements; If-else statement if (boolean expression) { statements 1; } else { statement 2; }

Review: If-Else Statement Pay attention to the brackets {} You can discard them if there is only one statement in them if (inputint > 0) System.out.println( Positive ); else System.out.println( Negative or zero );

Review: If-Else Statement Pay attention to the brackets {} You can discard them if there is only one statement in them Discarding it may cause problems if (inputint > 0) System.out.println( Positive ); else System.out.println( Negative or zero ); System.out.println( What s happening? ); // will always be executed

Review: If-Else Statement Pay attention to the brackets {} You can discard them if there is only one statement in them Discarding it may cause problems if (inputint > 0) System.out.println( Positive ); System.out.println( What s happening now? ); // Will cause a syntax error else System.out.println( Negative or zero );

Review: If-Else Statement Pay attention to the brackets {} You can discard them if there is only one statement in them Discarding it may cause problems As a good habit, don t discard them, even if you have only one statement in it The only exception: multibranch if-else

Review: If-Else Statement Never put a semicolon after if or else if (inputint > 0); System.out.println( What s happening now? ); Compiler will interpret it as if (inputint > 0) { ;} System.out.println( What s happening now? );

Review: If-Else Statement Never put a semicolon after if or else if (inputint > 0) System.out.println( Positive ); else; System.out.println( What s happening? ); Compiler will interpret it as if (inputint > 0) { System.out.println( Positive );} else { ;} System.out.println( What s happening? );

Review: Boolean Expression Assignment vs. equal to if ( n1 = n2 ) Error!!!! It s an assignment statement! if ( n1 == n2 ) Correct. It s a boolean expression now. Use equals() to compare Strings One_String.equals(Other_String) One_String.equalsIgnoreCase(Other_String)

Nested If-Else Statement Without brackets, every else will automatically match the nearest if if (time < 7) if (!fridge.isempty()) grab something from the fridge; else go to school; Is this piece of code correct?

Nested If-Else Statement Without brackets, every else will automatically match the nearest if if (time < 7){ if (!fridge.isempty()) grab something from the fridge; else go to school; } // Otherwise? Use brackets to avoid such errors

Multibranch If-Else Statement Example Write a program that takes as input your year in college (as an integer) and outputs your year as freshman, sophomore, junior, senior, or super senior

Multibranch If-Else Statement Flow chart: Prompt user for year 1 2 Which year? 3 4 5 freshman sophomore junior senior super senior

Multibranch If-Else Statement We can write a program like this if (year == 1) System.out.println("freshman"); else { if (year == 2) System.out.println("sophomore"); else { if (year == 3) System.out.println("junior"); else { if (year == 4) System.out.println("senior"); else { if (year == 5) System.out.println("super senior"); else System.out.println("huh?"); } } } }

Multibranch If-Else Statement Because the previous version is too ugly, we use the multibranch statement instead It is not a new syntax rule. We only ignore the brackets so that the logical structure is clear. if (year == 1) System.out.println("freshman"); else if (year == 2) System.out.println("sophomore"); else if (year == 3) System.out.println("junior"); else if (year == 4) System.out.println("senior"); else if (year == 5) System.out.println("super senior"); else System.out.println("huh?");

Multibranch If-Else Statement Though all the branches look equal, there is a precedence order among them Only the first satisfied branch will be executed

Multibranch If-Else Statement You can think the program flow as a highway. When you are driving on it, you always check the first exit and then exit if possible. If the exists are not listed properly, you will be lost

Multibranch If-Else Statement What s wrong with this piece of code? if (time < 7) grab something from the fridge; else if (time < 6) cook hams and scramble eggs; else go to school;

Multibranch If-Else Statement What s wrong with this piece of code? if (time < 7) grab something from the fridge; else if (time < 6) cook hams and scramble eggs; else go to school; Will this branch get executed?

Switch Statement if (year == 1) System.out.println("freshman"); else if (year == 2) System.out.println("sophomore"); else if (year == 3) System.out.println("junior"); else if (year == 4) System.out.println("senior"); else if (year == 5) System.out.println("super senior"); else System.out.println("huh?"); switch (year) { case 1: System.out.println("freshman"); break; case 2: System.out.println("sophomore"); break; case 3: System.out.println("junior"); break; case 4: System.out.println("senior"); break; case 5: System.out.println("super senior"); break; default: System.out.println("unknown"); break; }

Switch Statement Syntax rules: If controlling expression == case_label_n, then execute statements_n; The break means jumping out of the statement. Without the break, next statement will also be executed switch (controlling expression /variable) { case case_label_1: statements_1; break; case case_label_2: statements_2; break; default: statements; break; }

Switch Statement Without a break (after case A and case C ), the program will continue to the next case and execute that statement Pay attention to colons and semicolons switch (egggrade) { case 'A': case 'a': System.out.println("Grade A"); break; case 'C': case 'c': System.out.println("Grade C"); break; default: System.out.println("We only buy grade A and grade C."); break; }

Switch Statement The default case is optional It means everything else The case labels must be of the same type as controlling expression The controlling expression can only be int, short, byte or char Why not float or double? Why not String? Hint: Think about ==

Switch Statement The controlling expression can only be int, short, byte or char Why not float or double? float and double are only approximate values They are inaccurate for == Why not String? You can not use == to compare Strings

Multibranch vs. Switch Switch statement is more straightforward if you only use == to check a single expression/variable Using proper break can have shorter code Multibranch if-else statement is more powerful You can use it to check the range of a variable You can use it to check the value of float/double/string You can check more than one variable

Loop Statement Loop statements are designed to repeat instructions Think about the requirement: Print number 1 to 10 It s easy System.out.println( 1 ); System.out.println( 2 ); Think about the requirement: Print number 1 to 100 We can still do this Let the user input a value n, then print 1 to n We are in trouble

Loop Statement What is the pseudo code to fulfill the requirement? Count to 1, if 1<=n, write it down, otherwise stop Count to 2, if 2<=n, write it down, otherwise stop Count to 3, if 3<=n, write it down, otherwise stop Count to i, if i<=n, write it down, otherwise stop Count to i+1, if i+1<=n, write it down, otherwise stop While a counter<=n, write it down, increase the counter. Otherwise stop

While Statement Flow of while statement Start from expression evaluation As long as it s true, repeat instructions in brackets while (count <= number) { System.out.println(count); count++; }

While Statement You have to do some initialization before the statement The loop body typically contains an action that ultimately causes the controlling boolean expression to become false. number = keyboard.nextint(); count = 1; while (count <= number) { System.out.println(count); count++; }

While Statement Usually there is a counter variable in the statement You can use it in different ways Requirement: print the odd numbers from 1 to 10000 int count = 1; while (count < 10000) { System.out.println(count); count += 2; } int count = 1; while (count * 2-1 < 10000) { System.out.println(count * 2-1); count++; }

Do-While Statement Another pseudo code to fulfill the requirement? Write down 1 and count to 2, continue if 2<=n, otherwise stop Write down 2 and count to 3, continue if 3<=n, otherwise stop Write down 3 and count to 4, continue if 4<=n, otherwise stop See the difference? Count to 1, if 1<=n, write it down, otherwise stop Count to 2, if 2<=n, write it down, otherwise stop Count to 3, if 3<=n, write it down, otherwise stop

Do-While Statement The main difference: do-while statement will at least execute the body statements once If start from count = 1 and number = 0 While statement will output nothing Do-While statement will output 1, then stop while (count <= number) { System.out.println(count); count++; } do { System.out.print(count); count++; } while (count <= number);

Do-While Statement Flow of do-while statement Start from body statements Repeat instructions in brackets as long as the expression is true do { System.out.print(count); count++; } while (count <= number);

Do-While Statement Don t forget the semicolon after the whole statement Not recommended, unless you really need the body statement to be executed once do { System.out.print(count); count++; } while (count <= number);

While and Do-While Statements These two pieces of code perform identically initialization; do { body_statments } while (boolean_expression); initialization; body_statements; while (boolean_expression) { body_statements; }

Infinite Loops Q: How did the programmer die in the shower? A: He read the shampoo bottle instructions: Lather, Rinse, Repeat. If the controlling boolean expression never becomes false, a while loop or a do-while loop will repeat without ending

Infinite Loops Always make sure that your loop will end Never forget to change the counter while (count <= number) { System.out.println(count); } while (count <= number); { System.out.println(count); } while (count <= number) { ; } System.out.println(count);

Infinite Loops Always make sure that your loop will end Never forget to change the counter Use comparison instead of == or!= in the control expression Know whether your counter is increasing or decreasing while (count!= number) { System.out.println(count); count+=2; } while (count < number) { System.out.println(count); count--; }

Infinite Loops If you wrote an infinite loop and executed it Use the terminate button of eclipse If it is red, the program is running

Infinite Loops Infinite loop is not a syntax error. It s a logical error eclipse will not help you in this case Write pseudo code, think, and rethink before coding