Loops in C# Statement Sequences Do While Loop

Total Page:16

File Type:pdf, Size:1020Kb

Loops in C# Statement Sequences Do While Loop slide 2 gaius Loops in C# while loop do while loop for loop foreach loop choose them wisely,agood choice of loop can make your code cleaner slide 3 slide 4 gaius gaius Statement sequences do while loop in the following slides statementsequences is used syntax of this loop is in C# this can mean do asingle statement statementsequences; while (expr); or a compound statement it should be used when the loop must run at least acompound statement starts with { and ends with a } once individual statements are separated by ; remember the guessing number game, you must makeatleast one guess! slide 5 slide 6 gaius gaius while loop while loop syntax of this loop is { char ch; ch = f.ReadChar (); // the ½ component while (expr) while (ch != ’z’) statementsequences; { ... // the N component ch = f.ReadChar (); } useful if there are occasions when the loop body statementsequence should neverexecute sometimes called a N and a ½ loop Ntimes around the loop, but it requires some set up for the initial conditional expression slide 7 slide 8 gaius gaius forloop forloop allows us to combine the N and ½ loop into one for (int i = 1; i <= 12; i++) compound statement Console.WriteLine ("8 x {0} = {1}", i, 8*i); the syntax is: and for (initialisers;expression; iterators) for (int i = 1; i <= 12; i++) statementsequences; { Console.WriteLine ("8 x {0} = {1}", i, 8*i); } are the same, however we must use { and } if we wanted multiple statements in the loop body slide 9 slide 10 gaius gaius forloop while and do while loops do not abuse the for loop if you look carefully at these loops you will see that theyallowyou to have multiple initialisers, in most cases while and do loops complexexpressions and multiple iterators also have initialise, iterator and expression sections C# allows you to break out of the loop or the programmer can choose where and howthey continue to the next iterator value appear both are considered very bad programming practice in general it is better to use a while or a do while loop than abuse a for loop as a programmer keep and eye on howeasy it is to maintain your code slide 11 slide 12 gaius gaius foreach statement C# functions (methods) useful to iterate overarrays, more about this later try and keep your function length small and have one purpose mercylessly refactor and break functions into smaller sub functions to achieve the above aim it allows you to focus on a smaller set of code lines should reduce the programming time makes it easier to maintain your code or for someone else to read your code slide 13 slide 14 gaius gaius Example function, implementing a delay Example function, implementing a delay function function suppose we want a delay of ¼ of a second in our we can call this in our program, likethis: program we might write: public static void delay () { Thread.Sleep (250); // sleep for 250 milliseconds } slide 15 slide 16 gaius gaius Example function, implementing a delay Example function, implementing a delay function function using System; sometimes it is useful to use a function to change the using System.Threading; name of the action public class test { as in the case above public static void delay () { Thread.Sleep (250); // sleep for 250 milliseconds } public static void Main () { char ch; ConsoleKeyInfo name; do { name = Console.ReadKey (); Console.WriteLine ("you typed {0}", name.KeyChar); delay (); }while (name.KeyChar != ’x’); } } slide 17 slide 18 gaius gaius Example function, implementing a delay Example function, implementing a delay function function we notice that the previous code is the skeleton for a consider the main method (function): game loop public static void Main () it would be interesting to explore whether we can poll { char ch = ’a’; // variable is assigned as not ’x’ the keyboard for input and takeaction if no input is Console.Clear (); // clears screen seen do { it would give usthe ability to produce retro if (GetChar (ref ch)) Console.WriteLine ("you typed {0}", ch); console based games else { Console.WriteLine ("move monster"); delay (); at the same time it allows us to explore howfunctions } operate }while (ch != ’x’); } slide 19 slide 20 gaius gaius Reference parameters Reference parameters we are calling our own function GetChar which will the function must also be declared knowing that this return a bool value indicating whether a keyboard parameter is a reference parameter character has been pressed by the user if true is returned then the parameter, ch,will public static bool GetChar (ref char ch) be the pressed key { otherwise it is left alone if (Console.KeyAvailable) { ConsoleKeyInfo k = Console.ReadKey (); ch = k.KeyChar; notice that we are not passing the value into the return true; } function, but rather the address (or reference) of the return false; variable } the function uses the address to assign a newvalue to the variable which is seen by the caller slide 21 slide 22 gaius gaius Non reference parameters Non reference parameters changing our main function to: public static void MovePlayer (char c) { switch (c) { public static void Main () case ’w’: { // move up char ch = ’a’; // variable is assigned as not ’q’ break; case ’a’: Console.Clear (); // clears screen // move left do { break; if (GetChar (ref ch)) case ’d’: MovePlayer (ch); // move right else break; MoveMonster (); case ’s’: }while (ch != ’q’); // move down } break; default: } } allows the code to be naturally extended by implementing sub functions notice howthe variable ch is passed from main by value and this copy c is tested using the switch slide 23 slide 24 gaius gaius C# Arrays C# Arrays in C# an array is an indexedcollection of objects, all of the same type Clear() clear arange of elements Copy() copyasection of an array to another C# provides native syntax for the declaration of Reverse() reverse order of array Array objects Sort() sort aone dim array which is itself a System.Array object Length() the length of the array Rank() number of dimensions of the array GetLength() get length of particular dim GetLowerBound get lowest bound of dim GetUpperBound get upper bound of dim slide 25 slide 26 gaius gaius Declaring arrays in C# Initialising arrays example declare an integer array int[] myPrimes1 = new int[5] {1, 2, 3, 5, 7}; int[] myPrimes2 = {1, 2, 3, 5, 7}; int[] myArray; int[] myArray2 = new int[10]; for (int i = 0; i < myArray2.Length; i++) { instantiate an array to contain fiveinteger values (all myArray2[i] = 42; zero) } myArray = new int[5]; slide 27 slide 28 gaius gaius Initialising arrays Multidimensional arrays int total = 0; double [,]matrix = new double[3,3]; /* indices 0-2, 0-2 */ foreach (int v in myPrimes2) { for (int i = 0; i < 3 ; i++) { total += v; for (int j = 0; j < 3; j++) { } matrix[i, j] = 0.0; } } slide 29 slide 30 gaius gaius Version 2: An Improvedmethod of Chasing game iterative overanarray returning to our game, we could extend our main double [,]matrix = new double[3,3]; /* indices 0-2, 0-2 */ function to include the concept of a leveland initialise a 2D world from reading a file for (int i = 0; i < matrix.GetLength (0); i++) { for (int j = 0; j < matrix.GetLength (1); j++) { matrix[i, j] = 0.0; } public static void Main () } { if (completed_all ()) Console.WriteLine ("well done, you have completed\ all levels and your score was {0}", score); else Console.WriteLine ("you died with a score of {0}", score); } slide 31 slide 32 gaius gaius Using file input to configurethe game Using file input to configurethe game useful to configure levels using plain ascii text ########################################## #...................##...................# #.########.########.##.########.########.# #.########.########.##.########.########.# #.########......................########.# #..........#########.##########..........# ##.#######.##...............###.###.###### #..#######.##.##....p....##.###.###....### ##.#######....##.........##.....###.###### #..........##.#############.###.........## #.######.####...................#######.## #..#####.####.#############.###.#######.## ##.#####.####......###......###..........# #........#########.###.#################.# #.################.###.#################.# #m.......................................# ########################################## slide 33 slide 34 gaius gaius Using file input to configurethe game Using file input to configurethe game public static bool completed_all () public static bool load_level (int level) { { while (load_level (level)) StringBuilder filename = new StringBuilder (); { string f; if (! completed_level ()) return false; filename.AppendFormat ("level{0}", level); level += 1; f=filename.ToString (); } if (File.Exists (f)) return true; return read_file (f, level); } else return false; } slide 35 slide 36 gaius gaius Using file input to configurethe game Using file input to configurethe game public static bool read_file (string filename, int no) public static bool completed_level () { { int row = 0; Console.Clear (); FileInfo f = new FileInfo (filename); while (! level_finished ()) StreamReader r = f.OpenText (); { string line; char ch = ’z’; blank_grid (); redraw (); if (GetCharTimeout (ref ch)) line = r.ReadLine (); process_input (ch); while (line != null) else { if (! move_monster ()) process_line (line, row); return false; row++; } line = r.ReadLine (); return gathered_food (); } } Console.WriteLine ("finished reading file"); return true; } slide 37 slide 38 gaius gaius Using file input to configurethe game Using file input to configurethe game public static bool gathered_food () public static bool GetCharTimeout (ref
Recommended publications
  • C++ Programming: Program Design Including Data Structures, Fifth Edition
    C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition) Objectives In this chapter, you will: • Learn about repetition (looping) control structures • Explore how to construct and use count- controlled, sentinel-controlled, flag- controlled, and EOF-controlled repetition structures • Examine break and continue statements • Discover how to form and use nested control structures C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2 Objectives (cont'd.) • Learn how to avoid bugs by avoiding patches • Learn how to debug loops C++ Programming: From Problem Analysis to Program Design, Fifth Edition 3 Why Is Repetition Needed? • Repetition allows you to efficiently use variables • Can input, add, and average multiple numbers using a limited number of variables • For example, to add five numbers: – Declare a variable for each number, input the numbers and add the variables together – Create a loop that reads a number into a variable and adds it to a variable that contains the sum of the numbers C++ Programming: From Problem Analysis to Program Design, Fifth Edition 4 while Looping (Repetition) Structure • The general form of the while statement is: while is a reserved word • Statement can be simple or compound • Expression acts as a decision maker and is usually a logical expression • Statement is called the body of the loop • The parentheses are part of the syntax C++ Programming: From Problem Analysis to Program Design, Fifth Edition 5 while Looping (Repetition)
    [Show full text]
  • Control Flow Statements
    Control Flow Statements http://docs.oracle.com/javase/tutorial/java/nutsandbolts/flow.html http://math.hws.edu/javanotes/c3/index.html 1 Control Flow The basic building blocks of programs - variables, expressions, statements, etc. - can be put together to build complex programs with more interesting behavior. CONTROL FLOW STATEMENTS break up the flow of execution by employing decision making, looping, and branching, enabling your program to conditionally execute particular blocks of code. Decision-making statements include the if statements and switch statements. There are also looping statements, as well as branching statements supported by Java. 2 Decision-Making Statements A. if statement if (x > 0) y++; // execute this statement if the expression (x > 0) evaluates to “true” // if it doesn’t evaluate to “true”, this part is just skipped // and the code continues on with the subsequent lines B. if-else statement - - gives another option if the expression by the if part evaluates to “false” if (x > 0) y++; // execute this statement if the expression (x > 0) evaluates to “true” else z++; // if expression doesn’t evaluate to “true”, then this part is executed instead if (testScore >= 90) grade = ‘A’; else if (testScore >= 80) grade = ‘B’; else if (testScore >= 70) grade = ‘C’; else if (testScore >= 60) grade = ‘D’; else grade = ‘F’; C. switch statement - - can be used in place of a big if-then-else statement; works with primitive types byte, short, char, and int; also with Strings, with Java SE7, (enclose the String with double quotes);
    [Show full text]
  • Chapter 3: Control Statements
    Chapter 3: Control Statements 3.1 Introduction In this chapter, you will learn various selection and loop control statements. Java provides selection statements that let you choose actions with two or more alternative courses. Java provides a powerful control structure called a loop, which controls how many times an operation or a sequence of operation is performed in succession. 3.2 Selection Statements Java has several types of selection statements: if Statements, if … else statements, nested if statements switch Statements Conditional Expressions 3.2.1 Simple if Statements if (booleanExpression) { statement(s); } // execution flow chart is shown in Figure (A) Example if (radius >= 0) { area = radius*radius*PI; System.out.println("The area for the circle of radius " + radius + " is " + area); } // if the Boolean expression evaluates to T, the statements in the block are executed as shown in figure (B) false false Boolean (radius >= 0) Expression true true Statement(s) area = radius * radius * PI; System.out.println("The area for the circle of " + "radius " + radius + " is " + area); (A) (B) FIGURE 3.1 An if statement executes statements if the Boolean Expression evaluates as true Note: The Boolean expression is enclosed in parentheses for all forms of the if statement. Thus, the outer parentheses in the previous if statements are required. Outer parentheses required Braces can be omitted if the block contains a single statement if ((i > 0) && (i < 10)) { Equivalent if ((i > 0) && (i < 10)) System.out.println("i is an " + System.out.println("i is an " + + "integer between 0 and 10"); + "integer between 0 and 10"); } (a) (b) Caution: o Adding a semicolon at the end of an if clause is a common mistake.
    [Show full text]
  • C Programming Tutorial
    C Programming Tutorial C PROGRAMMING TUTORIAL Simply Easy Learning by tutorialspoint.com tutorialspoint.com i COPYRIGHT & DISCLAIMER NOTICE All the content and graphics on this tutorial are the property of tutorialspoint.com. Any content from tutorialspoint.com or this tutorial may not be redistributed or reproduced in any way, shape, or form without the written permission of tutorialspoint.com. Failure to do so is a violation of copyright laws. This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the accuracy of the site or its contents including this tutorial. If you discover that the tutorialspoint.com site or this tutorial content contains some errors, please contact us at [email protected] ii Table of Contents C Language Overview .............................................................. 1 Facts about C ............................................................................................... 1 Why to use C ? ............................................................................................. 2 C Programs .................................................................................................. 2 C Environment Setup ............................................................... 3 Text Editor ................................................................................................... 3 The C Compiler ............................................................................................ 3 Installation on Unix/Linux ............................................................................
    [Show full text]
  • Iterating in Perl: Loops
    Iterating in Perl: Loops - Computers are great for doing repetitive tasks. - All programming languages come with some way of iterating over some interval. - These methods of iteration are called ‘loops’. - Perl comes with a variety of loops, we will cover 4 of them: 1. if statement and if-else statement 2. while loop and do-while loop 3. for loop 4. foreach loop if statement Syntax: - if the conditional is ‘true’ then the if(conditional) body of the statement (what’s in { between the curly braces) is …some code… executed. } #!/usr/bin/perl -w $var1 = 1333; Output? if($var1 > 10) 1333 is greater than 10 { print “$var1 is greater than 10\n”; } exit; if-else statement Syntax: -if the conditional is ‘true’ then execute if(conditional) the code within the first pair of curly { braces. …some code… } - otherwise (else) execute the code in else the next set of curly braces { …some different code… } Output? #!/usr/bin/perl -w 13 is less than 100 $var1 = 13; if($var1 > 100) { print “$var1 is greater than 100\n”; } else { print “$var1 is less than 100\n”; } exit; Comparisons that are Allowed - In perl you can compare numbers and strings within conditionals - The comparison operators are slightly different for each one - The most common comparison operators for strings: syntax meaning example lt Less than “dog” lt “cat” False! d > c gt Greater than “dog” gt “cat” True! d > c le Less than or equal to “dog” le “cat” False! d > c ge Greater than or equal to “dog” ge “cat” True! d > c eq Equal to “cat” eq “cat” True! c = c ne Not equal to “cat” eq “Cat”
    [Show full text]
  • Chapter 4 Loops
    Chapter 4 Loops 4.1 Introduction • Loops are structures that control repeated executions of a block of statements. • Java provides a powerful control structure called a loop, which controls how many times an operation or a sequence of operation is performed in succession. • Java provides three types of loop statements while loops, do-while loops, and for loops. 4.2 The while Loop • The syntax for the while loop is as follows: while (loop-continuation-condition) { // loop-body Statement(s); } • The braces enclosing a while loop or any other loop can be omitted only if the loop body contains one or no statement. The while loop flowchart is in Figure (a). • The loop-continuation-condition, a Boolean expression, must appear inside the parentheses. It is always evaluated before the loop body is executed. • If its evaluation is true, the loop body is executed; if its evaluation is false, the entire loop terminates, and the program control turns to the statement that follows the while loop. CMPS161 Class Notes (Chap 04) Page 1 /25 Kuo-pao Yang • For example, the following while loop prints Welcome to Java! 100 times. int count = 0; while (count < 100) { System.out.println("Welcome to Java!"); count++; } count = 0; Loop false false Continuation (count < 100)? Condition? true true Statement(s) System.out.println("Welcome to Java!"); (loop body) count++; (A) (B) FIGURE 4.1 The while loop repeatedly executes the statements in the loop body when the loop-continuation-condition evaluates to true. Caution • Make sure that the loop-continuation-condition eventually becomes false so that the program will terminate.
    [Show full text]
  • Week 6: Intro to Loops Control Flow (Order of Execution) 5.2 the While
    Control Flow Week 6: Intro to Loops (order of execution) • So far, control flow in our programs has included: ‣ sequential processing (1st statement, then 2nd statement…) Gaddis: 5.2-6 ‣ branching (conditionally skip some statements). CS 1428 Fall 2015 • Chapter 5 introduces loops, which allow us to conditionally repeat execution of some Jill Seaman statements. ‣ while loop ‣ do-while loop ‣ for loop 1 2 5.2 The while loop while syntax and semantics ! As long as the relational expression is true, repeat • The while statement is used to repeat the statement statements: while (expression) statement • How it works: ‣ expression is evaluated: ‣ If it is true, then statement is executed, then it starts over (and expression is evaluated again). ‣ If it is false, then statement is skipped (and the loop is done). 3 4 while example 5.3 Using while for input validation • Example: • Inspect user input values to make sure they are Hand trace! valid. int number = 1; • If not valid, ask user to re-enter value: while (number <= 3) { int number; This expression is true when cout << “Student” << number << endl; number is OUT of range. number = number + 1; cout << “Enter a number between 1 and 10: “; } cin >> number; Explain the valid values in the prompt cout << “Done” << endl; while (number < 1 || number > 10) { cout << “Please enter a number between 1 and 10: “; cin >> number; } Don’t forget to input • Output Student1 the next value Student2 // Do something with number here Student3 Done 5 6 Input Validation 5.4 Counters ! Checking for valid characters: ! Counter: a variable that is incremented (or char answer; decremented) each time a loop repeats.
    [Show full text]
  • If Statement in While Loop Javascript
    If Statement In While Loop Javascript If aerolitic or petitionary Jerald usually sail his lemonade liberated hence or react pettishly and loud, how ungoverned is Weylin? CompartmentalLinguiform Winifield and arbitratessubvertical unremittently Chancey always while admonishes Dwayne always disastrously salary his and sensationists cackle his bolus.expelled lengthily, he whangs so contrapuntally. You need to give it runs again and then perform this site is used. Before executing and website in. This type counter flow is called a loop because the quality step loops back around to attain top data that tow the scoop is False upon first time through the assert the. If false and be incorrect value of code again, you must be no conditions. No issue what pristine condition evaluates to it otherwise always inspire the feast of code once In short the mental-while loop executes the oven of statements before checking if. Loops while lovely for JavaScript The Modern JavaScript. Loops can either true, you need to the value of the block shows a while loop is true. If they sound like if that? Do have loop & While necessary in JavaScript with break statement. Conditionals and Loops. How hackers are finding creative assets on an empty. No such as adding another python. Boolean expression in this blog post that we use of factorial x counter variable being used in between while expression increment or more in this image. Since different actions for each iteration, what else block as a whimsical field cannot select a volume given. It has saw a single condition that many true causes the code inside the sure to.
    [Show full text]
  • For Each Loop Java Example
    For Each Loop Java Example designativeErhard is grapier or cabbalistic and transports Buddy bareleggedusually directs while his thermometric muffin evanishes Jean ninefolddisfigures or andindulges contend. toothsomely If perpetualitiesand philosophically, reputably how and gynaecological inboard. is Terrance? Speakable Kelsey exteriorize: he elasticizes his But simple desktop, loop for each The first example returns a copy of the entire string. Get occassional tutorials, Map, And Schedule. What is a Switch Case In Java? Infinite for loops is something that may happen due to a flawed logic. Every part of the loop is optional. WARNING: You can access array elements with the foreach loop, the loop exits. Iterable to iterate through collection elements. Set to an array. In the example above, iterator, the temp variable must be of the same type as the element in the collection or array. Operations, instead of declaring and initializing a loop counter variable, now you cannot use method reference now because we are doing something with lambda parameters. Not unlike in while loop that we have to declare the values separately. The type of collection being iterated will dictate the item returned with each iteration. Lists have that arrays do not. Your inbox and coding style guide on this syntax to access each loop? For example, articles, rent or share your email address. This code is editable. Specified email is already registered. If you have created rather a value of iterating over as the script however, just the loop and time through loop for example java. The official style guide does however madate the use of braces for safety.
    [Show full text]
  • CSCI-344 Programming Language Concepts (Section 3)
    CSCI-344 Programming Language Concepts (Section 3) Lecture 1 Course Overview Instructor: Hossein Hojjat August 22, 2016 1 Why Study Programming Languages? 1 2 3 What is programming? • Programming is way of communication: • Between human and computer: tell the machine what to do • Between humans: describe ideas about computation and algorithms \Programming is explaining to another human being what you want a computer to do." Donald Knuth (Renowned Computer Scientist) 4 • \Prince of Persia", was released in 1989 after over four years of work • Jordan Mechner wrote the program in machine language * Is there floor underfoot? If not, start to fall onground lda Fcheck and #fcheckmark beq ]rts ;0--no need to check jsr getunderft cmp #block bne :1 jsr InsideBlock ;If "inside" block, bump him outside :1 jsr cmpspace bne ]rts https://github.com/jmechner/Prince-of-Persia-Apple-II Early Programming • The first programs were hand-written directly in machine instructions 5 Early Programming • The first programs were hand-written directly in machine instructions • \Prince of Persia", was released in 1989 after over four years of work • Jordan Mechner wrote the program in machine language * Is there floor underfoot? If not, start to fall onground lda Fcheck and #fcheckmark beq ]rts ;0--no need to check jsr getunderft cmp #block bne :1 jsr InsideBlock ;If "inside" block, bump him outside :1 jsr cmpspace bne ]rts https://github.com/jmechner/Prince-of-Persia-Apple-II 5 C++ (C with Classes) 1980 Python (one of the first widely used scripting languages) 1991
    [Show full text]
  • C++ LOOP TYPES Rialspo Int.Co M/Cplusplus/Cpp Lo O P Types.Htm Copyrig Ht © Tutorialspoint.Com
    C++ LOOP TYPES http://www.tuto rialspo int.co m/cplusplus/cpp_lo o p_types.htm Copyrig ht © tutorialspoint.com There may be a situation, when you need to execute a block of code several number of times. In g eneral statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Prog ramming lang uag es provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or g roup of statements multiple times and following is the g eneral from of a loop statement in most of the prog ramming lang uag es: C++ prog ramming lang uag e provides the following types of loop to handle looping requirements. Click the following links to check their detail. Loop Type Description while loop Repeats a statement or g roup of statements while a g iven condition is true. It tests the condition before executing the loop body. for loop Execute a sequence of statements multiple times and abbreviates the code that manag es the loop variable. do...while loop Like a while statement, except that it tests the condition at the end of the loop body nested loops You can use one or more loop inside any another while, for or do..while loop. Loop Control Statements: Loop control statements chang e execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. C++ supports the following control statements. Click the following links to check their detail.
    [Show full text]
  • Control Structures
    Control Structures Most of the programming languages use control structures to control the flow of a program. The control structures include decision-making and loops. Decision-making is done by applying different conditions in the program. If the conditions are true, the statements following the condition are executed. The values in a condition are compared by using the comparison operators. The loops are used to run a set of statements several times until a condition is met. If the condition is true, the loop is executed. If the condition becomes false, the loop is terminated and the control passes to the next statement that follows the loop block. The control structures that are used in JavaScript are as follows: The if statement: The if statement is a simple decision-making statement that is used to apply conditions in the program. If a condition is true, the statement in the if block is executed; otherwise, the statement following the if block is executed. The syntax of the if statement is as follows: if(condition) { //statements } The following example will demonstrate the use of the if statement: <script language="javascript"> function ifdemo() { var a=prompt("Enter a number") var b= prompt("Enter a number") if(a>b) { document.write(a) } } </script> The above code will execute only if the value of the variable a is greater than the value of the variable b, and the value of the variable a will be printed. The if-else statement: The if-else statement is used to apply a condition in the program. If the condition is true, the statement in the if block is executed.
    [Show full text]