Accelerating Information Technology Innovation

Similar documents
ECE 122. Engineering Problem Solving with Java

Loops. CSE 114, Computer Science 1 Stony Brook University

Instructor: SIR MUHAMMAD NAVEED Created by: ARSLAN AHMED SHAAD ( ) MUHAMMAD BILAL ( ) ISIT:

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

Flow Control. CSC215 Lecture

Flow Control: Branches and loops

Advanced Computer Programming

LECTURE 5 Control Structures Part 2

Lecture 14. 'for' loops and Arrays

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

Problem Solving With Loops

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

DELHI PUBLIC SCHOOL TAPI

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

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

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

Unit 3 Decision making, Looping and Arrays

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

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

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

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Information Science 1

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

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

CHAPTER 5 FLOW OF CONTROL

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

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

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

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

Selections. CSE 114, Computer Science 1 Stony Brook University

CompSci 125 Lecture 11

REPETITION CONTROL STRUCTURE LOGO

Repetition Structures

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

CSEN 202 Introduction to Computer Programming

10/30/2010. Introduction to Control Statements. The if and if-else Statements (cont.) Principal forms: JAVA CONTROL STATEMENTS SELECTION STATEMENTS

CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad

Repetition, Looping. While Loop

CSC Java Programming, Fall Java Data Types and Control Constructs

Information Science 1

Lecture 7: General Loops (Chapter 7)

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal

Lecture 7 Tao Wang 1

Combo Lecture Lecture 14/15. Instructor: Craig Duckett

CS 112 Introduction to Programming

More Programming Constructs -- Introduction

Flow of Control of Program Statements CS 112 Introduction to Programming. Basic if Conditional Statement Basic Test: Relational Operators

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Chapter 4 Loops. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk

Java Loop Control. Programming languages provide various control structures that allow for more complicated execution paths.

( &% class MyClass { }

Language Reference Manual

Programming for Engineers Iteration

3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition)

CP FAQS Q-1) Define flowchart and explain Various symbols of flowchart Q-2) Explain basic structure of c language Documentation section :

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

CS1004: Intro to CS in Java, Spring 2005

Computer Programming

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

COMP 202 Java in one week

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

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

Computer Programming I - Unit 5 Lecture page 1 of 14

PROGRAMMING FUNDAMENTALS

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

Introduction to Java & Fundamental Data Types

Subject: PIC Chapter 2.

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

CS1150 Principles of Computer Science Loops (Part II)

Chapter 3. Selections

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

The Java language has a wide variety of modifiers, including the following:

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

Iteration statements - Loops

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

Chapter Goals. 3.1 The if Statement. Contents 1/30/2013 DECISIONS

COMP-202: Foundations of Programming. Lecture 6: Conditionals Jackie Cheung, Winter 2016

Lecture Transcript While and Do While Statements in C++

CS 102 / CS Introduction to Programming Midterm Exam #1 - Prof. Reed Fall 2010

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

Object-Oriented Programming in Java

Accelerating Information Technology Innovation

204111: Computer and Programming

The for Loop. Lesson 11

Object Oriented Programming with Java

Introduction to the Java Basics: Control Flow Statements

13 th Windsor Regional Secondary School Computer Programming Competition

Control Structures in Java if-else and switch

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

Overview. Iteration 4 kinds of loops. Infinite Loops. for while do while foreach

Loops (while and for)

CS 251L Review Quiz Key

Name Section: M/W T/TH Number Definition Matching (8 Points)

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

Example: Monte Carlo Simulation 1

Conditional Execution

Add Subtract Multiply Divide

Numerical Computing in C and C++ Jamie Griffin. Semester A 2017 Lecture 2

Module 4: Decision-making and forming loops

Transcription:

Accelerating Information Technology Innovation http://aiti.mit.edu Cali, Colombia Summer 2012 Lección 03 Control Structures

Agenda 1. Block Statements 2. Decision Statements 3. Loops 2

What are Control Structures? Without control structures, a computer would evaluate all instructions in a program sequentially Allow you to control: the order in which instructions are evaluated which instructions are evaluated the flow of the program Use pre-established code structures: block statements (anything contained within curly brackets) decision statements ( if, if-else, switch ) Loops ( for, while ) 3

Block Statements Statements contained within curly brackets { statement1; statement2; Evaluated sequentially when given instruction to enter curly brackets Most basic control structure (building block of other control structures) 4

Decision Statements: if-then The if decision statement causes a program to execute a statement conditionally* if (condition) { statement; next_statement; *Executes a statement when a condition is true 5

Dissecting if-then if (condition) { statement; next_statement; The condition must produce either true or false, also known as a boolean value If condition returns true, statement is executed and then next_statement If condition returns false, statement is not executed and the program continues at next_statement 6

if-then Statement Flow Chart if (condition) { statement; next_statement; condition true? yes execute statement no execute next_statement 7

if-then Example int price = 5; if (price > 3) { System.out.println( Too expensive ); //continue to next statement Output: Too expensive 8

if-then-else Statements The basic if statement can be extended by adding the else clause in order to do something if expression is false if (condition) { statement1; else { statement2; next_statement; Again, the condition must produce a boolean value If condition returns true, statement1 is executed and then next_statement is executed. If condition returns false, statement2 is executed and then next_statement is executed. 9

if-then-else Statement Flow Chart if (condition){ statement1; else { statement2; next_statement; yes execute statement1 condition TRUE? no execute statement2 execute next_statement 10

if-then-else Example int price = 2; if (price > 3) { System.out.println( Too expensive ); else { System.out.println( Good deal ); //continue to next statement Output: Good deal 11

Chained if-then Statements Note that you can combine if-else statements below to make a chain to deal with more than one case if (grade == 'A') System.out.println("You got an A."); else if (grade == 'B') System.out.println("You got a B."); else if (grade == 'C') System.out.println("You got a C."); else System.out.println("You got an F."); 12

Chained if-then-else Statement Flow Chart if (condition1) { statement1; else if (condition2) { statement2; else if (condition3) { statement3; else { statement_else; next_statement; condition1? no condition2? no condition3? yes yes yes execute statement1 execute statement2 execute statement3 no execute statement_else execute next_statement 13

switch Statements The switch statement is another way to test several cases generated by a given expression. The expression must produce a result of type char, byte, short or int, but not long, float, or double. switch (expression) { case value1: statement1; break; case value2: statement2; break; default: default_statement; break; The break; statement exits the switch statement 14

switch Statement Flow Chart switch (expression){ case value1: // Do value1 thing break; expression equals value1? n y Do value1 thing break case value2: // Do value2 thing break;... default: // Do default action break; // Continue the program expression equals value2? n y Do value2 thing break Do default action break Continue the program 15

Remember the Example Here is the example of chained if-else statements: if (grade == 'A') System.out.println("You got an A."); else if (grade == 'B') System.out.println("You got a B."); else if (grade == 'C') System.out.println("You got a C."); else System.out.println("You got an F."); 16

Chained if-then-else as switch Here is the previous example as a switch switch (grade) { case 'A': System.out.println("You got an A."); break; case 'B': System.out.println("You got a B."); break; case 'C': System.out.println("You got a C."); break; default: System.out.println("You got an F."); 17

What if there are no breaks? Without break, switch statements will execute the first statement for which the expression matches the case value AND then evaluate all other statements from that point on For example: switch (expression) { case value1: statement1; case value2: statement2; default: default_statement; NOTE: Every statement after the true case is executed 18

Switch Statement Flow Chart w/o breaks switch (expression){ case value1: // Do value1 thing expression equals value1? y Do value1 thing case value2: // Do value2 thing n... default: // Do default action // Continue the program expression equals value2? n y Do value2 thing Do default action Continue the program 19

Loops A loop allows you to execute a statement or block of statements repeatedly. There are 4 types of loops in Java: 1. while loops 2. do-while loops 3. for loops 4. foreach loops (coming soon!) 20

The while Loop while (condition){ statement This while loop executes as long as condition is true. When condition is false, execution continues with the statement following the loop block. The condition is tested at the beginning of the loop, so if it is initially false, the loop will not be executed at all. 21

while Loop Flow Chart The while loop Test condition is true? no while (expression){ statement yes Execute loop statement(?) Next statement 22

Example int limit = 4; int sum = 0; int i = 1; while (i < limit){ sum += i; i++; i = 1 i = 2 i = 3 i = 4 sum = 1 sum = 3 sum = 6 What is the value of sum? 6 23

do-while Loops Similar to while loop but guarantees at least one execution of the body do { statement; while(condition) 24

do-while Flowchart execute statement do { statement; while(condition) next_statement; condition true? yes no execute next_statement 25

do-while Example boolean test = false; do { System.out.println( Hey! ) while(test) Output: Hey! 26

for Loop Control structure for capturing the most common type of loop i = start; while (i <= end) {... i++; for (i = start; i <= end; i++) {... 27

Dissecting the for Loop for (initialization; condition; update) { statement; The control of the for loop appear in parentheses and is made up of three parts. 1. The first part, the initialization, sets the initial conditions for the loop and is executed before the loop starts. 2. Loop executes so long as the condition is true and exits otherwise 3. The third part of the control information, the update, is used to increment (update) the loop counter. This is executed at the end of each loop iteration. 28

for Loop Flow Chart The for loop initialization condition == true yes statements no for (initialization; condition; update) { //statements next_statement; update next_statement 29

Example int limit = 4; int sum = 0; for(int i = 1; i<=limit; i++ ) { sum += i; What is the value of sum? 10 i = 1 i = 2 i = 3 i = 4 i = 5 sum = 1 sum = 3 sum = 6 sum = 10 -- -- 30

Another Example for ( int div = 0; div < 1000; div++ ) { if ( div % 12 == 0 ){ System.out.println(div+"is divisible by 12"); This loop will display every number from 0 to 999 that is evenly divisible by 12. 31

Other Possibilities If there is more than one variable to set up or increment they are separated by a comma. for (i=0, j=0; i*j<1000; i++, j+=2) { System.out.println(i+"*"+j+"="+i*j); You do not have to fill every part of the control of the for loop but you must still have two semi-colons. for (int i=0; i<100; ) { sum += i; i++; *Straying far from convention may make code difficult to understand and thus is not common 32

Using the break Statement in Loops We have seen the use of the break statement in the switch statement. In loops, you can use the break statement to exit the current loop you are in. Here is an example: int index = 0; index = 1 The index is 1 while (index <= 4) { index = 2 The index is 2 index++; index = 3 if (index == 3) break; System.out.println("The index is + index); 33

Using the continue Statement in Loops Continue statement causes the loop to jump to the next iteration Similar to break, but only skips to next iteration; doesn t exit loop completely index = 1 The index is 1 int index = 0; index = 2 The index is 2 while (index <= 4){ index++; index = 3 -- -- if (index == 3) continue; Index = 4 The index is 4 System.out.println("The index is + index); 34

Nested Loops Example Printing a triangle for (int i=1; i<=5; i++){ for (int j=1; j<=i; j++){ System.out.println( * ); * * * * * * * * * * * * * * * 35

Control Structures Review Questions You are withdrawing money from a savings account. How do you use an If Statement to make sure you do not withdraw more than you have? if ( amount < balance ) { balance = balance amount; //next statement 36

Which Control Structure? As a programmer, you will never be asked something like: Write a for loop to You will need to implement logic in your program that meets your specification and requirements With experience, you will know which control structure to use. 37