Chapter 8 Statement-Level Control Structure

Similar documents
Iterative Statements. Iterative Statements: Examples. Counter-Controlled Loops. ICOM 4036 Programming Languages Statement-Level Control Structure

Chapter 8. Statement-Level Control Structures

Chapter 8. Statement-Level Control Structures ISBN

Control Structures. Outline. In Text: Chapter 8. Control structures Selection. Iteration. Gotos Guarded statements. One-way Two-way Multi-way

Statement level control structures

Chapter 7. - FORTRAN I control statements were based directly on IBM 704 hardware

Chapter 8. Statement-Level Control Structures

Chapter 8. Statement-Level Control Structures

Chapter 8 Statement-Level Control Structures

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

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

Ch. 7: Control Structures

Flow of Control Execution Sequence

Why Is Repetition Needed?

Expressions vs statements

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

CHAPTER 4 CONTROL STRUCTURES

CSE 452: Programming Languages. Outline of Today s Lecture. Expressions. Expressions and Control Flow

8. Control statements

CS1100 Introduction to Programming

Decision Making -Branching. Class Incharge: S. Sasirekha

Introduction. C provides two styles of flow control:

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Programming with C++ Language

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS240 BRANCHING STATEMENTS

Manual. Subject Code: CS593. Computer Science and Engineering

Relational Expressions. Boolean Expressions. Boolean Expressions. ICOM 4036 Programming Languages. Boolean Expressions

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Input And Output of C++

C++ Final Exam 2017/2018

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

REPETITION CONTROL STRUCTURE LOGO

n Group of statements that are executed repeatedly while some condition remains true

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

Chapter 2: Basic Elements of C++

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

CPSC 3740 Programming Languages University of Lethbridge. Control Structures

Quick Reference Guide

The following expression causes a divide by zero error:

Lab Instructor : Jean Lai

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

Flow Control. CSC215 Lecture

C++/Java. C++: Hello World. Java : Hello World. Expression Statement. Compound Statement. Declaration Statement

Objectives. In this chapter, you will:

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

( &% class MyClass { }

Chapter 4 - Notes Control Structures I (Selection)

C++ Programming Lecture 1 Software Engineering Group

Increment and the While. Class 15

In this chapter you will learn:

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

causing a set of statements (the body) to be executed repeatedly. C++ provides three control structures to support iteration (or looping).

causing a set of statements (the body) to be executed repeatedly. C++ provides three control structures to support iteration (or looping).

1 Lexical Considerations

Basics of C++ // my first program in C++ Hello World! #include <iostream> using namespace std; int main () { cout << "Hello World!

Control Statements. If Statement if statement tests a particular condition

Introduction to Programming

Chapter7 Expression and Assignment Statement. Introduction

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

6.096 Introduction to C++ January (IAP) 2009

5. Selection: If and Switch Controls

C: How to Program. Week /Mar/05

LECTURE NOTES ON PROGRAMMING FUNDAMENTAL USING C++ LANGUAGE

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2

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

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

Expressions and Statements. Department of CSE, MIT, Manipal

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

Biyani's Think Tank. Concept based notes. C Language M.C.A. Neha Jain M.C.A Lecturer Deptt. of Information Technology Biyani Girls College, Jaipur

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

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

CS242 COMPUTER PROGRAMMING

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each):

5. Assuming gooddata is a Boolean variable, the following two tests are logically equivalent. if (gooddata == false) if (!

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

MODULE 2: Branching and Looping

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

PROGRAMMING FUNDAMENTALS

Repetition Structures

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

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

G Programming Languages - Fall 2012

CSCI 1061U Programming Workshop 2. C++ Basics

Building on the foundation. Now that we know a little about cout cin math operators boolean operators making decisions using if statements

Lexical Considerations

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

Unit 7. 'while' Loops

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

1. In C++, reserved words are the same as predefined identifiers. a. True

1. C++ Overview. C++ Program Structure. Data Types. Assignment Statements. Input/Output Operations. Arithmetic Expressions.

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

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

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

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

COMP 208 Computers in Engineering

CHAPTER : 9 FLOW OF CONTROL

C++ PROGRAMMING BASICS

DHA Suffa University CS 103 Object Oriented Programming Fall 2015 Lab #01: Introduction to C++

Transcription:

Chapter 8 Statement-Level Control Structure To make programs more flexible and powerful: Some means of selecting among alternative control flow paths. Selection statement (conditional statements) Unconditional statement Some means of repeating execution of certain collection of statements. Iterative statement Selection Statements Provides the means of choosing between two or more paths of execution Two general categories: Two-way selectors Multiple-way selectors 1

Two-Way Selection Statements General form: if control_expression then clause else clause if (sum == 0) if (count == 0) result = 0; else result = 1; <== which if gets the else? Java/C/C++/C# rule is else matches nearest if To force an alternative semantics, compound statements may be used: usually surrounded by braces ({... ), but some languages use begin... end or other bracketing keywords. if (sum == 0) { if (count == 0) result = 0; else result = 1; 2

Perl requires that all then and else clauses to be compound Ada solution closing special words Advantage: readability if... then if... then if... then if... then...... else end if... else end if... end if end if 3

Multiple-Way Selection Statements Allow the selection of one of any number of statements or statement groups In the C-based languages: if (test1) statement1 else if (test2) statement2... else if (testn) statementn else default-statement switch and case are reserve d The C, C++, and Java switch switch ( expression ) { case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case... default: If expression matches value1, control jumps to here 4

Given the following switch statement where x is an int, switch (x) { case 3 : x = x+1; case 4 : x = x+2; break; case 5 : x = x+3; case 6 : x=x+1; case 7 : x = x+2; case 8 : x=x-1; case 9 : x=x+1 ; (1) x = 4? (2) x = 3? (3) x = 7? Put break statements after the group of statements that we want to be executed for a specific condition. Otherwise the remainder statements will be executed until the end of the switch selective block or a break statement is reached. 5

The Ada case statement 1. Constant lists can include Subranges e.g., 10..15 Boolean OR operators for example, 1..5 7 15..20 2. Lists of constants must be exhaustive Often accomplished with others clause This makes it more reliable case k is end case; when 1 => j := 1; when 4 40 => j := 4; when 50..59 => j := 50; when others => put ("Error in case, k ="); put (k); new_line; 6

Iterative Statements Causes a statement or collection of statements to be executed zero, or more times Counter controlled loops (for) Logically controlled loops (while, do-while) Iteration based on data structures (iterator) Counter controlled loops (for) C Syntax for ([expr_1] ; [expr_2] ; [expr_3]) statement The expressions can be whole statements, or even statement sequences, with the statements separated by commas The first expression is evaluated once, but the other two are evaluated with each iteration. for ( i = 5, j = 10 ; i + j < 20; i++, j++ ) printf( "\n i + j = %d", (i + j) ); If the second expression is absent, it is an infinite loop 7

C++ and Java Differs from C: The initial expression can include variable definitions (scope is from the definition to the end of the loop body) Pascal s for statement for variable := initial (to downto) final do statement program next_example; const MAX_STUDENTS = 100; var i: integer; grades: array [1..MAX_STUDENTS] of char; num: 1..MAX_STUDENTS; begin write('enter number of students: '); readln(num); assert((num > 0) and (num <= MAX_STUDENTS)); for i := 1 to num do begin write('enter grade for student ', i: 3, ': '); readln(grades[i]) end; end; 8

Iterating over Collections and Arrays with Enhanced for In the Java 5.0, a new kind of for statement was created especially for collections and arrays. public class ForEachDemo { public static void main(string[] args) { int[] arrayofints = { 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 ; for (int element : arrayofints) { System.out.print(element + " "); Iterative Statements: Logically-Controlled Loops General forms: while (ctrl_expr) loop body do loop body while (ctrl_expr) Pascal has separate pre-test and post-test logical loop statements (while-do and repeat-until) FORTRAN 77 and 90 have neither Perl has pre-test logical loop, while and until, but no post-test logical loop 9

Loop Forever loops forever, until an exit statement is executed within its body. In C, it may be simulated by while (true) statement or for (;;;) statement while (true) { input := read(file); if (input == eof) exit; process(input); Loops Based on Data Types Ada's for statement has the format for variable in discrete_range loop statements end loop; Where discrete_range is subrange of an integer or enumeration type. for d in Mon.. Fri loop printschedule(d); end loop; 10

Iterative Based on Data Structures Control mechanism is a call to an iterator function that returns the next element in some chosen order, if there is one; else loop is terminate. C's for statement can be used to build a user-defined iterator: suppose the nodes of a binary tree are to be processed. If the tree root is pointed by a variable named root. for (p=root; p==null; traverse(p)){ C# s foreach statement iterates on the elements of arrays and other collections: Strings[] strlist = { Bob, Carol, Ted ; foreach (Strings name in strlist) Console.WriteLine ( Name:, name); 11

Iterators in Java Java supports iterator() method in most of its container classes this method returns an iterator over the elements of the given collection. iterator An iterator object has a hasnext method that returns true if there is at least one more item to process The next method returns the next item The syntax for iter ating over the elements in a Vector is as follows Vector vec = new Vector; // Populate it... Then later, iterate over its elements Iterator it = vec.iterator (); while (it.hasnext ()) { Object o = it.next (); 12

Unconditional Branching Transfers execution control to a specified place in the program Well-known mechanism: goto statement Major concern: Readability Some languages do not support goto statement (e.g., Module-2 and Java) C, C++, C# offers goto statement (can be used in switch statements) 13

Tutorial of C++ (part2: control structures) Conditional structure: if and else if (x > 0) cout << "x is positive"; else if (x < 0) cout << "x is negative"; else cout << "x is 0"; Iteration structures (loops) The while loop #include <iostream> using namespace std; int main (){ int n; cout << "Enter the starting number > "; cin >> n; while (n>0) { cout << n << ", "; --n; cout << "FIRE!\n"; return 0; Enter the starting number > 8 8, 7, 6, 5, 4, 3, 2, 1, FIRE! 14

The do-while loop do statement while (condition); #include <iostream> using namespace std; int main (){ unsigned long n; do { cout << "Enter number (0 to end): "; cin >> n; cout << "You entered: " << n << "\n"; while (n!= 0); return 0; Enter number (0 to end): 12345 You entered: 12345 Enter number (0 to end): 160277 You entered: 160277 Enter number (0 to end): 0 You entered: 0 The for loop for (initialization; condition; increase) statement; for ( n=0, i=100 ; n!=i ; n++, i-- ) { // whatever here... 15

Jump statements. The break statement #include <iostream> using namespace std; int main (){ int n; for (n=10; n>0; n--) { cout << n << ", "; if (n==3) { cout << "countdown aborted!"; break; return 0; 10, 9, 8, 7, 6, 5, 4, 3, countdown aborted! The continue statement The continue statement causes the program to skip the rest of the loop in the current iteration as if the end of the statement block had been reached, causing it to jump to the start of the following iteration. 16

#include <iostream> using namespace std; 10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE! int main (){ for (int n=10; n>0; n--) { if (n==5) continue; cout << n << ", "; cout << "FIRE!\n"; return 0; The goto statement #include <iostream> using namespace std; 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE! int main (){ int n=10; loop: cout << n << ", "; n--; if (n>0) goto loop; cout << "FIRE!\n"; return 0; 17

The exit function Terminate the current program with a specific exit code. void exit (int exitcode); The exitcode is used by some operating systems and may be used by calling programs. By convention, an exit code of 0 means that the program finished normally and any other value means that some error or unexpected results happened. The selective structure: switch. switch (expression){ case constant1: group of statements 1; break; case constant2: group of statements 2; break;.. default: default group of statements 18