Repeating Instructions. C# Programming: From Problem Analysis to Program Design 2nd Edition. David McDonald, Ph.D. Director of Emerging Technologies

Similar documents
CIS 3260 Intro to Programming in C#

204111: Computer and Programming

Making Decisions. C# Programming: From Problem Analysis to Program Design 2nd Edition. David McDonald, Ph.D. Director of Emerging Technologies

Lecture 7 Tao Wang 1

Arrays and Collections. C# Programming: From Problem Analysis to Program Design 2nd Edition. David McDonald, Ph.D. Director of Emerging Technologies

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

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

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

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

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

Repetition and Loop Statements Chapter 5

ECE 122. Engineering Problem Solving with Java

REPETITION CONTROL STRUCTURE LOGO

An Introduction to Programming with C++ Sixth Edition. Chapter 7 The Repetition Structure

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

Chapter 5: Loops and Files

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

Internet & World Wide Web How to Program, 5/e by Pearson Education, Inc. All Rights Reserved.

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

CSc Introduc/on to Compu/ng. Lecture 8 Edgardo Molina Fall 2011 City College of New York

Repetition Structures

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

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

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

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

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

Topics. Introduction to Repetition Structures Often have to write code that performs the same task multiple times. Controlled Loop

PLD Semester Exam Study Guide Dec. 2018

Chapter 4: Control structures. Repetition

Computer Programming I - Unit 5 Lecture page 1 of 14

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

Chapter 4: Control structures

Repetition, Looping CS101

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

CS112 Lecture: Repetition Statements

Indicate the answer choice that best completes the statement or answers the question. Enter the appropriate word(s) to complete the statement.

While Loops CHAPTER 5: LOOP STRUCTURES. While Loops. While Loops 2/7/2013

Increment and the While. Class 15

Example: Monte Carlo Simulation 1

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

Flow Control. CSC215 Lecture

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

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

CS110D: PROGRAMMING LANGUAGE I

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

Chapter Goals. Contents LOOPS

CS112 Lecture: Loops

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

First Name: Last: ID# 1. Hexadecimal uses the symbols 1, 2, 3, 4, 5, 6, 7 8, 9, A, B, C, D, E, F,G.

Making Decisions Chp. 5

Why Is Repetition Needed?

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

Looping. Arizona State University 1

Repetition, Looping. While Loop

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

Introduction. C provides two styles of flow control:

Islamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.

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

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

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

IT 374 C# and Applications/ IT695 C# Data Structures

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

Chapter 5: Control Structures II (Repetition)

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

CSCE150A. Introduction. While Loop. Compound Assignment. For Loop. Loop Design. Nested Loops. Do-While Loop. Programming Tips CSCE150A.

Introduction to C# Applications

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 5. Repetition in Programs. Notes. Notes. Notes. Lecture 05 - Loops

Loops / Repetition Statements

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0

Repetition CSC 121 Fall 2014 Howard Rosenthal

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

Repetition Structures II

Quiz Determine the output of the following program:

STUDENT LESSON A12 Iterations

Functions. Lecture 6 COP 3014 Spring February 11, 2018

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

CSCE 206: Structured Programming in C++

Information Science 1

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Structured Programming. Dr. Mohamed Khedr Lecture 9

Information Science 1

AP Programming - Chapter 6 Lecture

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

CSC Java Programming, Fall Java Data Types and Control Constructs

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

Advanced Computer Programming

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

Problem Solving and 'C' Programming

MARK SCHEME for the May/June 2011 question paper for the guidance of teachers 9691 COMPUTING. 9691/23 Paper 2 (Written Paper), maximum raw mark 75

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output:

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

Dept. of CSE, IIT KGP

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

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

Handout 5 cs180 - Programming Fundamentals Spring 15 Page 1 of 8. Handout 5. Loops.

3 The L oop Control Structure

Control Structures II. Repetition (Loops)

Transcription:

6 Repeating Instructions C# Programming: From Problem Analysis to Program Design 2nd Edition David McDonald, Ph.D. Director of Emerging Technologies Chapter Objectives Learn why programs use loops Write counter-, state-, and sentinel-controlled while loops Examine the conditional expressions that make up a for loop Compare the do while looping structure with the predefined forms of loops Write loops nested inside other loops 1

Why Use A Loop? Repeat instructions with many data sets Repetition or iteration structures Rich set of looping structures while do while for foreach statements covered later under Arrays Using the while Statement Simplest and most frequently used loop while (conditional expression) statement(s); Expression sometimes called loop condition Returns a Boolean result of true or false No semicolon after the conditional expression Null body empty bodied loop infinite loop Enclose multiple statements for body in 2

Pretest If the conditional expression evaluates to true, statement(s) performed If the conditional expression evaluates to false, statement(s) skipped while Statement Figure 6-1 Pretest loop C# Programming: From Problem Analysis to Program Design Counter-Controlled Loop Loop control variable Variable simulating a counter Initialized Conditional expression designed so that you can exit the loop after a certain number of iterations Increment counter with each iteration Otherwise, infinite loop 3

Counter-Controlled Loop Example /* SummedValues.cs Author: McDonald*/ int sum = 0; //Line 1 int number = 1; //Line 2 while (number < 11) //Line 3 //Line 4 sum = sum + number; //Line 5 number++; //Line 6 //Line 7 Console.WriteLine( Sum of values //Line 8 + 1 through 10 //Line 9 + is + sum); //Line 10 Counter-Controlled Loop (continued) Common problem Off-by-one error Loop body not executed for the last value OR Loop body executed one too many times 4

Sentinel-Controlled Loop Exact number of times loop body should execute not known Often used for inputting data Prime read on outside of loop Also referred to as indefinite loops Select a sentinel value Eteme Extreme value aleor dmm dummy value ale Sentinel value used as operand in conditional expression Tells user what value to type to end loop Sentinel-Controlled Loop Example /* InputValuesLoop.cs Author: McDonald*/ static void Main( ) string invalue = ""; //Initialized to empty body Console.Write("This program will let you enter value after value."); Console.WriteLine("To Stop, enter = -99"); while (invalue!= "-99") Console.WriteLine("Enter value (-99 to exit)"); invalue = Console.ReadLine(); 5

Sentinel-Controlled Loop (continued) Useful for loops that process data stored in a file Sentinel is placed as last entry in file Conditional expression must match selected sentinel value Sentinel-Controlled Loop (continued) /* PrimeRead.cs Author: McDonald*/ static void Main( ) string invalue = ""; //Initialized to null int sum = 0, intvalue; Console.Write("This program will let you enter"); Console.Write(" value after value. To Stop, enter"); Console.WriteLine(" -99"); Console.WriteLine("Enter value (-99 to exit)"); invalue = Console.ReadLine(); // Priming read 6

Sentinel-Controlled Loop (continued) /* PrimeRead.cs continued */ while (invalue!= "-99") intvalue = Convert.ToInt32(inValue); sum += intvalue; Console.WriteLine("Enter value (-99 to exit)"); invalue = Console.ReadLine(); Console.WriteLine("Total values entered 0", sum); Windows Applications Using Loops Event-driven model Manages the interaction between user and GUI by handling repetition for you Designed with graphical user interface (GUI) Predefined class called MessageBox Used to display information to users through its Show( ) method 7

Windows Applications Example /* SquaredValues.cs Author: McDonald*/ using System; using System.Windows.Forms; //Namespace for Windows Form class namespace SquaredValues class SquaredValues static void Main( ) int counter = 0; string result =""; Windows Applications Example (continued) /* SquaredValues.cs - continued */ while (counter < 10) counter++; result += " \t + counter + " \t" // Notice use of += to build + Math.Pow(counter, 2) + "\n"; // string for MessageBox MessageBox.Show(result, 1 through 10 and their squares ); 8

Windows Applications Example (continued) Figure 6-3 MessageBox dialog output Windows Applications To use MessageBox class in console application Add a reference to System.Windows.Forms.dll View > Solutions Explorer Right-click on the Reference folder Add Reference e e Add using directive to System.Windows.Forms namespace in program using System.Windows.Forms; 9

Windows Applications (continued) Figure 6-4 Add a reference to a project Windows Applications (continued) Add Reference to System.Windows.F orms.dll Figure 6-5 Class libraries of.net 10

Windows MessageBox Class MessageBox dialog box MessageBox.Show( ) method is overloaded First argument string displayed in window Second argument caption for Window title bar Third argument type of dialog button Fourth argument button type MessageBox.Show( ) Method MessageBox.Show("Do you want another number?", "State Controlled Loop", MessageBoxButtons.YesNo, MessageBoxIcon.Question) 1 st argument 2 nd argument 4 th argument 3 rd argument Figure 6-7 State-controlled loop of random numbers 11

MessageBox class MessageBox.Show("Do you want another number?", "State Controlled Loop", MessageBoxButtons.YesNo, MessageBoxIcon.Question) MessageBox class (continued) MessageBox.Show("Do you want another number?", "State Controlled Loop", MessageBoxButtons.YesNo, MessageBoxIcon.Question) 12

State-Controlled Loops Similar to sentinel-controlled loop Referred to as flag-controlled loops Instead of requiring a dummy or extreme value, use flag variable Can be Boolean variable (not a requirement) Variable must be initialized For each new iteration, evaluate to see when it changes state Change its value inside the loop to stop the loop State-Controlled Loops Example bool moredata = true; while (moredata) // moredata is updated inside the loop condition changes if (MessageBox.Show("Do you want another number?", "State Controlled Loop", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) // Test to see if No clicked moredata = false; // End of if statement // More loop body statements // End of while loop 13

For Loop Pretest form of loop (like the while) Considered specialized form of while statement Usually associated with counter-controlled types Packages initialization, test, and update all on one line General form is: for (statement; conditional expression; statement) statement; Interpreted as: for (initialize; test; update) statement; For Loop (continued) Figure 6-8 Flow of control with a for statement 14

For Loop (continued) For loop is executed as shown in the numbered steps Figure 6-9 Step of the for statement Comparison of While and For Statement Replace above while loop with for loop below does same int counter = 0; while (counter < 11) Console.WriteLine("0\t1\t2", counter, Math.Pow(counter,2), Math.Pow(counter,3)); counter++; for (int counter = 0; counter < 11; counter++) Console.WriteLine("0\t1\t2", counter, Math.Pow(counter,2), Math.Pow(counter,3)); C# Programming: From Problem Analysis to Program Design 15

For Loop (continued) counter out of SCOPE Figure 6-10 Syntax error Ways to Initialize, Test, and Update For Statements for (int counter = 0, val1 = 10; counter < val1; counter++) for ( ; counter < 100; counter+=10) // No initialization iti for (int j = 0; ; j++) // No conditional expression for ( ; j < 10; counter++, j += 3) // Compound update for (int anum = 0; anum < 101; sum += anum, anum++) ; // Null loop body for (int j = 0,k = 10; j < 10 && k > 0; counter++, j += 3) 16

Ways to Initialize, Test, and Update For Statements Floating-point variables can be used for initialization, expressions, and update for (double d=15.0; d<20.0; d+=0.5) Console.Write(d + \t ); The output produced 15 15.5 16 16.5 17 17.5 18 18.5 19 19.5 Ways to Initialize, Test, and Update For Statements Can change the loop control variable inside the loop for (double d = 15.0; d < 20.0; d += 0.5) Console.Write(d + \t ); C# lets you change the conditional d += 2.0 The output produced 15 17.5 expression endvalue inside the loop body BUT, be careful here 17

Do While Statements Posttest General form do statement; while ( conditional expression); Figure 6-12 Do while loop C# Programming: From Problem Analysis to Program Design Do While Example int counter = 10; do // No semicolon on this line Console.WriteLine(counter + "\t" + Math.Pow(counter, 2)); counter--; while (counter > 6); The output of this code is: 10 100 9 81 8 64 7 49 18

15 lines printed Nested Loops Loop can be nested inside an outer loop Inner nested loop is totally completed before the outside loop is tested a second time int inner; for (int outer = 0; outer < 3; outer++) for(inner = 10; inner > 5; inner --) Console.WriteLine("Outer: 0\tInner: 1", outer, inner); 19