Information Science 1

Similar documents
Information Science 1

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

Repetition Structures

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

Information Science 1

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

Information Science 1

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

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

REPETITION CONTROL STRUCTURE LOGO

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

Loops / Repetition Statements

Conditionals and Loops

Information Science 1

CS110D: PROGRAMMING LANGUAGE I

Repetition, Looping CS101

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

Introduction. C provides two styles of flow control:

Computational Expression

Module 4: Decision-making and forming loops

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

Loops. In Example 1, we have a Person class, that counts the number of Person objects constructed.

STUDENT LESSON A12 Iterations

Lecture 7 Tao Wang 1

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

C Programming for Engineers Structured Program

Structured Program Development in C

Chapter 4: Conditionals and Loops

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

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

Chapter 3: Program Statements

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

Chapter 3 Structured Program Development

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Repetition, Looping. While Loop

In this chapter you will learn:

Selection Statements. Pseudocode

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

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

Chapter 4: Control structures. Repetition

Programming Language. Control Structures: Repetition (while) Eng. Anis Nazer Second Semester

Lecture Transcript While and Do While Statements in C++

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

Flow Control. CSC215 Lecture

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

Chapter 4: Control structures

Example. CS 201 Selection Structures (2) and Repetition. Nested if Statements with More Than One Variable

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

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

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

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 8: SEP. 29TH INSTRUCTOR: JIAYIN WANG

Computer Programming I - Unit 5 Lecture page 1 of 14

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

Programming for Engineers Iteration

Chapter 5 Selection Statements. Mr. Dave Clausen La Cañada High School

Unit 7. 'while' Loops

COP 1220 Introduction to Programming in C++ Course Justification

3 The L oop Control Structure

Repetition and Loop Statements Chapter 5

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

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

Chapter 5: Control Structures

Chapter 4 C Program Control

The following expression causes a divide by zero error:

Chapter 5: Control Structures II (Repetition)

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

204111: Computer and Programming

Chapter 2: Functions and Control Structures

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

3chapter C ONTROL S TATEMENTS. Objectives

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

Chapter Goals. Contents LOOPS

Loops (while and for)

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

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

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

All about flow control

Introduction to C Programming

CS1004: Intro to CS in Java, Spring 2005

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

C++ Programming Lecture 7 Control Structure I (Repetition) Part I

CS106X Handout 03 Autumn 2012 September 24 th, 2012 Getting Started

Pace University. Fundamental Concepts of CS121 1

CT 229 Java Syntax Continued

Looping. Arizona State University 1

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1

Repetition CSC 121 Fall 2014 Howard Rosenthal

Algorithms and Conditionals

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

2.8. Decision Making: Equality and Relational Operators

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.

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

Transcription:

Topics covered Information Science 1 Fundamental Programming Constructs (1) Week 11 Terms and concepts from Week 10 Flow of control and conditional statements Selection structures if statement switch statement counter-controlled loops event (sentinel) -controlled loops College of Information Science and Engineering Ritsumeikan University Repetition structures Quiz Recall Week 10 Boolean logic, algebra, variables, expressions Relational and logic operators Logical NOT, negation Logical OR, Boolean sum, disjunction Logical AND, Boolean product, conjunction Truth table De Morgan s laws Class objectives Learn about selection structures in high-level programming languages Learn about repetition structures in high-level programming languages Flow of control Unless specified otherwise, the order of statement execution through a method is linear: one statement after another in sequence To change this order, there are, however, special programming constructs conditional statements which allow us to: decide whether or not to execute a particular statement, or execute a statement over and over, repetitively These statements are based on Boolean expressions that evaluate to either true or false The (overall) order of statement execution in an algorithm is called the flow of control Two-way selection The most basic selection structure is the if conditional statement that has the following format: if ( condition ) clauseif; clauseelse; Previous Statements Yes Is No condition true? Execute rest of program Execute clauseif Execute clauseelse

if syntax The condition is interpreted as a boolean expression (i.e. is evaluated to TRUE or FALSE), and it must be enclosed in parentheses No semicolon is required after the condition parenthesis, but clauseif and clauseelse may require them The condition can have a side effect (i.e. change a variable s value) clauseif and clauseelse can be any expression, even another if statement clauseif and clauseelse can each only be one statement, but it may be a compound statement or block is optional Bugs in condition Nested if statements The statements executed as a result of clauseif and clauseelse could be other if statements These are called nested if statements A clauseelse is optional, but it is always matched to the last unmatched if Nested if statements are most useful when you are categorizing something, e.g. student grades: if (90 <= numbergrade) lettergrade = A+ ; if (80 <= numbergrade) lettergrade = A ; if (70 <= numbergrade) lettergrade = B ; if (60 <= numbergrade) lettergrade = C ; lettergrade = F ; Indentation Since is optional, nested if statements can be confusing, e.g. if (testa) if (testb) if (testc) print( abc ); print( now what? ); Despite indentation, belongs to if (testc) because when evaluated, an will always be paired to the closest if The clause controlled by the if statements is usually indented by the programmer. The use of a consistent indentation style makes a program easier to read and understand, e.g. if ((1 <= value) && (value <= MAX)) anothervalue = value; anothervalue = MAX/2; Or the same source code but indented: if ((1 <= value) && (value <= MAX)) anothervalue = value; anothervalue = MAX/2; Bugs in a nested if Note that you should never check if a boolean variable is true (or false) in the following way: if (myboolean == TRUE) Indeed, think what happens if you mistyped and instead wrote: if (myboolean = TRUE) Statements with the relational equality operator == are a huge source of bugs! Therefore, you should simply write: if (myboolean) Remember that indentation (white space) is for the human reader, but is ignored by the computer Multiple choice if provides the most general way to make choices in a program. Another way is using the switch statement that is a very special form of nested if switch is used when a discrete variable of type char or int (or other integer-compatible type) specifies what should be done, and it has the following format: switch (selector){ statements_1; case CONSTANT_1: case CONSTANT_2: statements_2; break; case CONSTANT_n: statements_n; default: statements_d;

switch syntax Selector should not be a boolean value, a floating point value, or other complex data types The CONSTANTs must be constants, and not variables! No two case labels can have the same CONSTANT For a given case label (i.e. CONSTANT), one or more statements can be sequentially executed statements can include a special statement break that transfers control to outside the switch statement The default label is optional it is equivalent to. Only one default is allowed, and it can go anywhere (good to place it at the end) Repetition structures Initialization that sets values which need to be set before the repetition begins, Test condition that sets the repetition to continue if the condition is true, and Update that updates the test condition to see whether to continue the repetition Loop classification In general, loops can be classified in one of two categories: Counter-Controlled Loops are used when we need to perform an action a particular number of time consists of initializing, testing, and updating a counter the number of iterations may or may not be constant Event (or sentinel) -Controlled Loops are used when actions should be performed until a particular event occurs or a particular state is reached The while statement Infinite loops The body of a loop should eventually make the condition false. If not, it is called an infinite loop, which will execute forever, or until the user interrupts the program This is one of the most common logical errors. E.g. consider the following loop: int counter = 1; while ( counter <= 10 ) { Print counter; We forgot counter++ and this loop would run forever Repetition structures allow us to execute a statement multiple times. Similar to selection structures, they are based on Boolean expressions conditions Repetition structures are often called loops: groups of instructions a computer executes repeatedly while some conditions remain true Thus, there are three parts of a loop: A while statement has the following format: while(condition) If the condition is true, the statement is executed Then the condition is evaluated again, and if it is still true, the statement is executed again The statement is executed repeatedly until the condition becomes false The statement will, thus, be executed zero or more times It is the most basic repetition structure Nested loops Similar to nested if statements, loops can be nested as well the body of a loop can contain another loop For each iteration of the outer loop, the inner loop iterates completely Example: What is the value of count3 after execution of the following code? int count1 = count2 = count3 = 1; while (count1 <= 10) //Outer loop { while (count2 <= 20) //Inner loop { count3++; count2++; count1++;count2=1;

The do/while statement A do/while statement has the following format: do while(condition) The statement is executed once initially, and then the condition is evaluated The statement will, thus, be executed at least 1 time The statement is executed repeatedly until the condition becomes false (i.e. remains true) The for statement A for statement has the following format: for(initialization; condition; increment) Each expression in the header of a for loop is optional: If the initialization is missed, no initialization is performed If the condition is missed, it is always considered to be true, and therefore creates an infinite loop If the increment is missed, no increment operation is performed (which may cause an infinite loop) You can even miss them all: for( ; ; ) Event-controlled loops An example (a class-averaging algorithm in pseudocode) with sentinel-controlled repetition: Summary Initialize total to zero Initialize counter to zero Input the first grade (possibly the sentinel) While the user has not as yet entered the sentinel { Add this grade into the running total Add one to the grade counter Input the next grade (possibly the sentinel) If the counter is not equal to zero { Set the average to the total divided by the counter Print the average Print No grades were entered Concepts you need to know after this class Flow of control Selection statements Repetition statements (including event-controlled) Indentation All programs can be broken down into 3 structures: Sequence: handled automatically by compiler Selection: if or switch Repetition: while, do/while or for The structures can only be combined in 2 ways: Sequencing Nesting Any selection can be rewritten as an if statement, and any repetition can be rewritten as a while statement Homework Read these slides again Do the self-preparation assignments Learn the vocabulary Consult, whenever necessary, the textbook materials

Fundamental Programming Constructs (2) Structural decomposition Program models and parameter passing Next class Quiz 05 Write your name (in English), student ID number, and solve the following problems (write only answers):