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

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. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

Information Science 1

Conditionals and Loops

Computational Expression

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

Introduction. C provides two styles of flow control:

Loops / Repetition Statements

Lecture 7 Tao Wang 1

Module 4: Decision-making and forming loops

Information Science 1

STUDENT LESSON A12 Iterations

Repetition, Looping CS101

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

CS110D: PROGRAMMING LANGUAGE I

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.

Chapter 4: Conditionals and Loops

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

Chapter 3: Program Statements

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

Repetition, Looping. While Loop

In this chapter you will learn:

Structured Program Development in C

Flow Control. CSC215 Lecture

Lecture Transcript While and Do While Statements in C++

C Programming for Engineers Structured Program

COP 1220 Introduction to Programming in C++ Course Justification

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

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

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

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

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

Computer Programming I - Unit 5 Lecture page 1 of 14

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

Chapter 3 Structured Program Development

Unit 7. 'while' Loops

Programming for Engineers Iteration

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

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

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

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

Chapter 5: Control Structures

3 The L oop Control Structure

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

Chapter 4 C Program Control

Chapter 2: Functions and Control Structures

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

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

Chapter 5: Control Structures II (Repetition)

Chapter 4: Control structures

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

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

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

204111: Computer and Programming

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

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

Lecture 5 Tao Wang 1

Chapter Goals. Contents LOOPS

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

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

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

Repetition and Loop Statements Chapter 5

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

Introduction to C Programming

CS1004: Intro to CS in Java, Spring 2005

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

The following expression causes a divide by zero error:

Accelerating Information Technology Innovation

CT 229 Java Syntax Continued

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

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.

CSE123 LECTURE 3-1. Program Design and Control Structures Repetitions (Loops) 1-1

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

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

Why Is Repetition Needed?

Pace University. Fundamental Concepts of CS121 1

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

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

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

3chapter C ONTROL S TATEMENTS. Objectives

All about flow control

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

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

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

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

Chapter 3. Selections

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

Transcription:

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 and conditional statements l Selection structures if else statement switch statement l Repetition structures counter-controlled loops event (sentinel) -controlled loops l Quiz 2

Recall Week 10 l Boolean logic, algebra, variables, expressions l Relational and logic operators l Logical NOT, negation l Logical OR, Boolean sum, disjunction l Logical AND, Boolean product, conjunction l Truth table l De Morgan s laws 3

Class objectives l Learn about selection structures in high-level programming languages l Learn about repetition structures in high-level programming languages 4

Flow of control l Unless specified otherwise, the order of statement execution through a method is linear: one statement after another in sequence l 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 l These statements are based on Boolean expressions that evaluate to either true or false l The (overall) order of statement execution in an algorithm is called the flow of control 5

Two-way selection l The most basic selection structure is the if else conditional statement that has the following format: if ( condition ) clauseif; else clauseelse; Previous Statements Yes Is condition true? No Execute rest of program Execute clauseif Execute clauseelse 6

if else syntax l The condition is interpreted as a boolean expression (i.e. is evaluated to TRUE or FALSE), and it must be enclosed in parentheses l No semicolon is required after the condition parenthesis, but clauseif and clauseelse may require them l The condition can have a side effect (i.e. change a variable s value) l clauseif and clauseelse can be any expression, even another if else statement l clauseif and clauseelse can each only be one statement, but it may be a compound statement or block l else is optional 7

Bugs in condition l Note that you should never check if a boolean variable is true (or false) in the following way: if (myboolean == TRUE) l Indeed, think what happens if you mistyped and instead wrote: if (myboolean = TRUE) l Statements with the relational equality operator == are a huge source of bugs! l Therefore, you should simply write: if (myboolean) 8

Nested if else statements l l l l The statements executed as a result of clauseif and clauseelse could be other if else statements These are called nested if else statements A clauseelse is optional, but it is always matched to the last unmatched if Nested if else statements are most useful when you are categorizing something, e.g. student grades: if (90 <= numbergrade) lettergrade = A+ ; else if (80 <= numbergrade) lettergrade = A ; else if (70 <= numbergrade) lettergrade = B ; else if (60 <= numbergrade) lettergrade = C ; else lettergrade = F ; 9

Nested if else statements l l l l The statements executed as a result of clauseif and clauseelse could be other if else statements These are called nested if else statements A clauseelse is optional, but it is always matched to the last unmatched if Nested if else statements are most useful when you are categorizing something, e.g. student grades: if (90 <= numbergrade) lettergrade = A+ ; else if (80 <= numbergrade) lettergrade = A ; else if (70 <= numbergrade) lettergrade = B ; else if (60 <= numbergrade) lettergrade = C ; else lettergrade = F ; 10

Indentation l The clause controlled by the if else 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; else anothervalue = MAX/2; Or the same source code but indented: if ((1 <= value) && (value <= MAX)) anothervalue = value; else anothervalue = MAX/2; l Remember that indentation (white space) is for the human reader, but is ignored by the computer 11

Bugs in a nested if else l Since else is optional, nested if else statements can be confusing, e.g. if (testa) if (testb) if (testc) else print( abc ); print( now what? ); l Despite indentation, else belongs to if (testc) because when evaluated, an else will always be paired to the closest if 12

Multiple choice l l if else 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 else 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){ case CONSTANT_1: statements_1; } case CONSTANT_2: statements_2; break; case CONSTANT_n: statements_n; default: statements_d; 13

switch syntax l Selector should not be a boolean value, a floating point value, or other complex data types l The CONSTANTs must be constants, and not variables! l No two case labels can have the same CONSTANT l For a given case label (i.e. CONSTANT), one or more statements can be sequentially executed l statements can include a special statement break that transfers control to outside the switch statement l The default label is optional it is equivalent to else. Only one default is allowed, and it can go anywhere (good to place it at the end) 14

Repetition structures l Repetition structures allow us to execute a statement multiple times. Similar to selection structures, they are based on Boolean expressions conditions l Repetition structures are often called loops: groups of instructions a computer executes repeatedly while some conditions remain true l Thus, there are three parts of a loop: 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 15

Loop classification l 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 16

The while statement l A while statement has the following format: while(condition) statement; l If the condition is true, the statement is executed l Then the condition is evaluated again, and if it is still true, the statement is executed again l The statement is executed repeatedly until the condition becomes false l The statement will, thus, be executed zero or more times l It is the most basic repetition structure 17

Infinite loops l 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 l This is one of the most common logical errors. E.g. consider the following loop: int counter = 1; while ( counter <= 10 ) { Print counter; } l We forgot counter++ and this loop would run forever 18

Nested loops l Similar to nested if else statements, loops can be nested as well the body of a loop can contain another loop l For each iteration of the outer loop, the inner loop iterates completely l 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; } 19

The do/while statement l A do/while statement has the following format: do statement; while(condition) l The statement is executed once initially, and then the condition is evaluated l The statement will, thus, be executed at least 1 time l The statement is executed repeatedly until the condition becomes false (i.e. remains true) 20

The for statement l A for statement has the following format: for(initialization; condition; increment) statement; l 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( ; ; )statement; 21

Event-controlled loops l An example (a class-averaging algorithm in pseudocode) with sentinel-controlled repetition: 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 } else Print No grades were entered 22

Summary l All programs can be broken down into 3 structures: Sequence: handled automatically by compiler Selection: if else or switch Repetition: while, do/while or for l The structures can only be combined in 2 ways: Sequencing Nesting l Any selection can be rewritten as an if else statement, and any repetition can be rewritten as a while statement 23

Concepts you need to know after this class l Flow of control l Selection statements l Repetition statements (including event-controlled) l Indentation 24

l Read these slides again l Do the self-preparation assignments l Learn the vocabulary Homework l Consult, whenever necessary, the textbook materials 25

Next class l Fundamental Programming Constructs (2) Structural decomposition Program models and parameter passing 26