C# Programming Fundamentals Control Flow Jim Warren, COMPSCI 280 S2 2015 Enterprise Software Development.

Slides:



Advertisements
Similar presentations
Flow of Control Chapter 3.
Advertisements

Fundamental Programming Structures in Java: Control Flow, Arrays and Vectors.
1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
Control Structures Corresponds with Chapters 3 and 4.
8-May-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
PHP Functions and Control Structures. 2 Defining Functions Functions are groups of statements that you can execute as a single unit Function definitions.
Additional control structures. The if-else statement The if-else statement chooses which of two statements to execute The if-else statement has the form:
16-Jun-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Slides prepared by Rose Williams, Binghamton University Chapter 3 Flow of Control Loops in Java.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
C++ for Engineers and Scientists Third Edition
Slides prepared by Rose Williams, Binghamton University Chapter 3 Flow of Control if-else and switch statements.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
The switch Statement, DecimalFormat, and Introduction to Looping
UNIT II Decision Making And Branching Decision Making And Looping
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
COIT29222 Structured Programming Slide 1 COIT29222-Structured Programming Lecture Week 06  Reading: Study Guide Book 2, Modules 9 & 10 Textbook (4 th.
Jaeki Song ISQS6337 JAVA Lecture 04 Control Structure - Selection, and Repetition -
Loops Repeating Code Multiple Times SoftUni Team Technical Trainers Software University
PHP Conditional Statements Conditional statements in PHP are used to perform different actions based on different conditions. Conditional Statements Very.
PHP Programming with MySQL Slide 4-1 CHAPTER 4 Functions and Control Structures.
Chapter 2 Functions and Control Structures PHP Programming with MySQL 2 nd Edition.
Controlling Execution Dong Shao, Nanjing Unviersity.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
CSCI 3328 Object Oriented Programming in C# Chapter 5: C# Control Statement – Part II – Exercises 1 Xiang Lian The University of Texas Rio Grande Valley.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 5: Introduction to C: More Control Flow.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Fundamental Programming Fundamental Programming for Loops.
1-Dec-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
Flow of Control Chapter 3. Outline Branching Statements Java Loop Statements Programming with Loops The Type boolean.
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Application development with Java Lecture 6 Rina Zviel-Girshin.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
Iteration & Loop Statements 1 Iteration or Loop Statements Dept. of Computer Engineering Faculty of Engineering, Kasetsart University Bangkok, Thailand.
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Flow of Control Joe McCarthy CSS 161: Fundamentals of Computing1.
W E E K F I V E Control Flow. Copyright © 2006 Addison-Wesley. All rights reserved.1-2 Chapter 8 Topics Introduction Selection Statements Iterative Statements.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Today… Preparation for doing Assignment 1. Invoking methods overview. Conditionals and Loops. Winter 2016CMPE212 - Prof. McLeod1.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Chapter 7 Control Structures. Java has very flexible three looping mechanisms. You can use one of the following three loops:  while Loop  do...while.
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
The switch Statement, and Introduction to Looping
Statements (6 of 6) A statement causes an action to be performed by the program. It translates directly into one or more executable computer instructions.
Flow of Control.
Chapter 3 Loops Section 3.3 Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
JavaScript: Control Statements.
Objectives Explain selection constructs Describe loop constructs
In this class, we will cover:
CSC215 Lecture Control Flow.
Chapter8: Statement-Level Control Structures April 9, 2019
In this class, we will cover:
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
CSC215 Lecture Control Flow.
Controlling Program Flow
Chapter 3 Flow of Control Loops in Java.
CSS 161: Fundamentals of Computing
Presentation transcript:

C# Programming Fundamentals Control Flow Jim Warren, COMPSCI 280 S Enterprise Software Development

Outline COMPSCI 2802  Learn to use the C# language for controlling program flow  Decision-making statements:  if, if-else, nested if-else, if-else-if, switch  Loops  while, do-while, for,  Nested Loops  Others  break, continue, goto  return, using

Hello World in C# Vs Java  Java  C# (Console application template)  C# Vs Java  Main not main  Doesn’t need parameters to Main  Different methods for IO COMPSCI 2803 public class Hello { public static void main(String[] args) { System.out.println("Hello world."); } public class Hello { public static void Main() { System.Console.WriteLine("Hello World."); }

Decision-Making Statements  Decision-Making statements evaluate conditions and execute statements based on that evaluation  C# includes two decision-making statements:  If statement  Evaluates an expression  Executes one or more statements if expression is true  Can execute another statement or group of statements if expression is false  Switch statement  Evaluates a variable for multiple values  Executes a statement or group of statements, depending on contents of the variable being evaluated COMPSCI 2804 Condition Conditional Code True False Flow chart of a typical decision structure Just like in Java!

if & if-else COMPSCI 2805  The if statement  The block governed by it is executed if a condition is true  The Boolean_Expression must be enclosed in parentheses  The statement_when_true branch of an if can be a made up of a single statement or a compound statement  Note:  A compound statement is made up of a list of statements and must always be enclosed in a pair of braces ({ })  The If-else statement  It is two-way selection.  The else block is executed if the if part is false.  Again, the statements_when_true or statements_when_false can be a made of a single statement or many statements. if (boolean_expression) statement_when_true; etc. true if if (boolean_expression) { statementS_when_true;... } if (boolean_expression) statement_when_true; else statement_when_false; if (boolean_expression){ statements_when_true;... } else { statements_when_false;... } etc. truefalse if-else Just like in Java!

Nested if-else COMPSCI 2806  Nested if-else  If-else or if statement can be used as a subpart of another if-else or if statement.  The else clause matches the most recent if clause in the same block.  Nested statement can be tricky to code (or read)  Indentation can improve readability  To force the else clause to match the first if clause, you must add a pair of braces: if (i > j) if (i > k) Console.WriteLine("A"); else Console.WriteLine("B"); if (i > j) if (i > k) Console.WriteLine("A"); else Console.WriteLine("B"); Incorrect indentation if (i > j) { if (i > k) Console.WriteLine("A"); } else Console.WriteLine("B"); Just like in Java! Note: Ctrl+K, Ctrl+F applies autoformatting according to the settings in Tools/Options for the Text Editor settings of C#’s Formatting pane

Multiway if-else COMPSCI 2807  The multiway if-else statement is simply a normal if-else statement that nests another if-else statement at every else branch  The Boolean_Expressions are evaluated in order until one that evaluates to true is found. If none of them are true then the else block is executed.  The final else is optional  Note:  It is indented differently from other nested statements. All of the Boolean_Expressions are aligned with one another. if (Boolean_Expression) Statement_1; else if (Boolean_Expression) Statement_2; else if (Boolean_Expression_n) Statement_n; else Statement; if (Boolean_Expression) { Statements_1;... } else if (Boolean_Expression) { Statements_n;... } else { Statements;... } Just like in Java!

Switch COMPSCI 2808  Switch  Acts like a multiple-way if statement  Transfers control to one of several statements, depending on the value of an expression  No two case statements can have the same value.  Value must be an integer or a string  Execution of the statement body begins at the selected statement and proceeds until the break statement transfers control out of the case body  Implicit fall through from one case to another if a case statement has no code.  The default statement is optional C1C1 C2C2 C3C3 Statement(s) 1 True Statement(s) 2 True Statement(s) 3 True False switch (n) { case value1: statement1; break; case value2: case value3: statement2; break;... default: statementn; break; } if (Boolean_Expression) Statement_1; else if (Boolean_Expression_n) Statement_n; else Statement; Implicit fall through Just like in Java!

Writing Loops Handout 06COMPSCI 2809  Loops  Repeated execution of one or more statements until a terminating condition occurs  Pre-test and post-test loops  Types of loops:  Pre-test loops  while  for  foreach (will cover in Arrays)  Post-test loop  do…while true false

while COMPSCI  The while statement is used to repeat a portion of code (i.e., the loop body) based on the evaluation of a Boolean expression  The Boolean expression is checked before the loop body is executed  When false, the loop body is not executed at all  Before the execution of each following iteration of the loop body, the Boolean expression is checked again  If true, the loop body is executed again  If false, the loop statement ends  The loop body can consist of a single statement, or multiple statements enclosed in a pair of braces ({ }) etc. while (boolean_expression) { Statement_1; Statement_2;... Statement_Last; } while true false Just like in Java!

do-while COMPSCI  The do-while statement is used to execute a portion of code (i.e., the loop body), and then repeat it based on the evaluation of a Boolean expression  The loop body is executed at least once  The Boolean expression is checked after the loop body is executed  The Boolean expression is checked after each iteration of the loop body  If true, the loop body is executed again  If false, the loop statement ends  Note: Don't forget to put a semicolon after the Boolean expression do { Statement_1; Statement_2;... Statement_Last; } while (boolean_expression); while true false Just like in Java!

for COMPSCI  The for statement is most commonly used to step through an integer variable in equal increments  It begins with the keyword for, followed by three expressions in parentheses that describe what to do with one or more controlling variables  The first expression tells how the control variable or variables are initialized or declared and initialized before the first iteration  The second expression determines when the loop should end, based on the evaluation of a Boolean expression before each iteration  The third expression tells how the control variable or variables are updated after each iteration of the loop body  The body may consist of a single statement or a list of statements enclosed in a pair of braces ({ }) for (initialization; boolean_expression; update) { Statements_Body; } false Initialize the control variable true statement(s) Almost like in Java, but you can have more than one loop variable! update

Counters COMPSCI  Variables called counters are frequently used to control loops  Counters are initialized before the loop begins (can be just at the beginning with the for loop)  They are also usually modified within the body of the loop  The counter in the body of the loop must eventually make the test expression false  Otherwise, the loop will continuously loop forever - called an infinite loop (case 5)  If you declare the control variable in the for loop, the scope of that variable will only be inside the loop block (case 4)  When to use…  while  Use the while loop when you wish the loop to repeat as long as the test expression is true (case 1 & 2)  for  The for loop is primarily used when the number of required iterations is known (case 4)  The post-test loop (do-while) is ideal when you want the loop to always iterate at least once (case 3 v case 2) //case 1 int i = 1; while (i < 3) { i = i + 1; } //case 2 int i = 20; while (i < 3) { i = i + 1; } //case 3 int i = 20; do { i = i + 1; } while (i < 3); //case 4 for (int i = 1; i < 3; i++) System.Console.WriteLine( " i= " +i); //case 5 int i = 1; while (i < 3) { } Infinite loop! Just like in Java!

Nested Loops  Loop can be nested  When nested, the inner loop iterates from beginning to the end for each single iteration of the outer loop  There is no limit in how many levels you can nest loops. It is usually not more than three levels.  Examples  Multiplication table  row =3, col = 4 COMPSCI for( int i = 1; i <= row; i ++) { for (int j = 1; j <= col; j++) { Console.Write( (i * j) < 10 ? " " +i *j : " " + i * j); } Console.WriteLine(); // Print blank line } for( int i = 0; i < row; i ++) { for (int j = 0; j < row; j++) { Console.Write("*"); } Console.WriteLine(); } for( int i = 0; i < row; i ++) { for (int j = 0; j <= i; j++) { Console.Write("*"); } Console.WriteLine(); } *** * ** *** 3 spaces if <10 else 2

break & continue COMPSCI The break statement terminates the closest enclosing loop or switch statement in which it appears.  Control is passed to the statement that follows the terminated loop (or switch), if any.  The continue statement passes control to the next iteration of the enclosing iteration statement in which it appears.  It must be enclosed by a while, do, for, or foreach statement  It applies only to the innermost statement in nested iteration statements for( int i = 0; i < row; i ++) { for (int j = 0; j < row; j++) { if ( i+j >= row ) break; Console.Write("*"); } Console.WriteLine(); } *** ** * i = 1 i = 3 for (int i= 1; i <= row; i++ ) { if( i % 2 == 0) continue; // Go back to for Console.WriteLine("i = " + i ); } For row=3

goto COMPSCI  The goto statement transfers the program control directly to a labeled statement.  Used in a switch statement  Get out of deeply nested loops switch (x) { case 1: Console.WriteLine("Case 1"); goto case 2; case 2: Console.WriteLine("Case 2"); break; } Case 1 Case 2 int[,] array = { { 1, 2, 3 }, { 4, 5, 6 } }; for (int i = 0; i < x; i++) for (int j = 0; j < y; j++) if (array[i, j]==x) goto Found; Console.WriteLine("The number {0} was not found.", x); goto Finish; Found: Console.WriteLine("The number {0} is found.", x); Finish: Console.WriteLine("End of search."); Output for int x=1 Each set of cases has to have a break or goto Note parameter output formatting

return & using  return  The return statement terminates execution of the method in which it appears and returns control to the calling method.  It can also return a value (in keeping with the type of the method it’s in).  If the method is a void type, the return statement at the end can be omitted.  using  Defines a scope, outside of which an object or objects will be disposed of.  It is usually best to release limited resources such as file handles and network connections as quickly as possible. iLoop testoutcome 11<=4Prints i=1 22<=4Returns COMPSCI public static void returnMethod(int row) { for (int i = 1; i <= row; i++) { if (i % 2 == 0) return; Console.WriteLine("i = " + i); } using (Font font1 = new Font("Arial", 10.0f)) { }

using directive COMPSCI  The using directive has two uses:  You can reference types in the library without fully qualifying the type name  To create an alias for a namespace. using System; namespace B { public class Program1 { static void Main(string[] args){ Console.WriteLine("Hello"); } namespace B { public class Program2 { static void Main(string[] args){ System.Console.WriteLine("Hello"); } using C = System.Console; namespace B { public class Program3 { static void Main(string[] args){ C.WriteLine("Hello"); } With using directive using alias Fully qualifying

Conclusion  We’ve learned some ways to control program flow in C#  And in the journey seen some other aspects of the language, too  Next time – we’ll focus on some of the interesting data types in C# Handout 02COMPSCI 28019