Loops Repeating Code Multiple Times SoftUni Team Technical Trainers Software University

Slides:



Advertisements
Similar presentations
Execute Blocks of Code Multiple Times Svetlin Nakov Telerik Corporation
Advertisements

Execute Blocks of Code Multiple Times Telerik Software Academy C# Fundamentals – Part 1.
 Dimitar Ivanov Introduction to programming with microcontrollers.
C# Advanced Topics Methods, Classes and Objects SoftUni Team Technical Trainers Software University
PHP Flow Control Loops, Functions, Return, Exit, Require, Try...Catch Software University SoftUni Team Technical Trainers.
Methods Writing and using methods, overloads, ref, out SoftUni Team Technical Trainers Software University
Software University Curriculum, Courses, Exams, Jobs SoftUni Team Technical Trainers Software University
Fundamentals SoftUni Welcome to Software University SoftUni Team Technical Trainers Software University
Loops, Methods, Classes Loops, Methods, Using API Classes, Exceptions SoftUni Team Technical Trainer Software University
Programming Basics Course Introduction SoftUni Team Technical Trainers Software University
AngularJS Directives Defining Custom Directives SoftUni Team Technical Trainers Software University
Software Testing Lifecycle Exit Criteria Evaluation, Continuous Integration Ivan Yonkov Technical Trainer Software University.
Teamwork and Personal Skills Course Introduction Software University SoftUni Team Technical Trainers.
Design Patterns: Structural Design Patterns
High-Quality Programming Code Code Correctness, Readability, Maintainability, Testability, Etc. SoftUni Team Technical Trainers Software University
NoSQL Databases NoSQL Concepts SoftUni Team Technical Trainers Software University
Conditional Statements Implementing Control-Flow Logic in C# SoftUni Team Technical Trainers Software University
Consuming REST Services from C# SoftUni Team Technical Trainers Software University
Entity Framework Performance SoftUni Team Technical Trainers Software University
Methods, Arrays, Lists, Dictionaries, Strings, Classes and Objects
Svetlin Nakov Technical Trainer Software University
Build Processes and Continuous Integration Automating Build Processes Software University Technical Trainers SoftUni Team.
C# Programming Fundamentals Control Flow Jim Warren, COMPSCI 280 S Enterprise Software Development.
Multidimensional Arrays, Sets, Dictionaries Processing Matrices, Multidimensional Arrays, Dictionaries, Sets SoftUni Team Technical Trainers Software University.
Loops, Methods, Classes Using Loops, Defining and Using Methods, Using API Classes, Exceptions, Defining Classes Bogomil Dimitrov Technical Trainer Software.
Test-Driven Development Learn the "Test First" Approach to Coding SoftUni Team Technical Trainers Software University
Defining Classes Classes, Fields, Constructors, Methods, Properties SoftUni Team Technical Trainers Software University
Functions Reusable Parts of Code SoftUni Team Technical Trainers Software University
Static Members and Namespaces Static Members, Indexers, Operators, Namespaces SoftUni Team Technical Trainers Software University
Graphs and Graph Algorithms Fundamentals, Terminology, Traversal, Algorithms SoftUni Team Technical Trainers Software University
Arrays, Lists, Stacks, Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Very Basic Mathematical Concepts for Programmers
Asynchronous Web Services Writing Asynchronous Web Services SoftUni Team Technical Trainers Software University
C# Basics Course Introduction Svetlin Nakov Technical Trainer Software University
Jekyll Static Site Generator Template-Based Site Generation Svetlin Nakov Technical Trainer Software University
Responsive Design Design that Adapts to Different Devices SoftUni Team Technical Trainers Software University
Exam Preparation Algorithms Course: Sample Exam SoftUni Team Technical Trainers Software University
Console Input / Output Reading and Writing to the Console SoftUni Team Technical Trainers Software University
Tables, Rows, Columns, Cells, Header, Footer, Colspan, Rowspan
High-Quality Programming Code Code Correctness, Readability, Maintainability Svetlin Nakov Technical Trainer Software University
Design Patterns: Structural Design Patterns General and reusable solutions to common problems in software design Software University
Reflection Programming under the hood SoftUni Team Technical Trainers Software University
Mocking with Moq Tools for Easier Unit Testing SoftUni Team Technical Trainers Software University
Regular Expressions /^Hel{2}o\s*World\n$/ SoftUni Team Technical Trainers Software University
Operators and Expressions
Code Formatting Formatting the Source Code Correctly SoftUni Team Technical Trainers Software University
Mocking Unit Testing Methods with External Dependencies SoftUni Team Technical Trainers Software University
Mocking with Moq Mocking tools for easier unit testing Svetlin Nakov Technical Trainer Software University
Test-Driven Development Learn the "Test First" Approach to Coding Svetlin Nakov Technical Trainer Software University
Programming for Beginners Course Introduction SoftUni Team Technical Trainers Software University
Processing Sequences of Elements
Objects and Classes Using Objects and Classes Defining Simple Classes SoftUni Team Technical Trainers Software University
Sets, Dictionaries SoftUni Team Technical Trainers Software University
Loops, Methods, Classes Using Loops, Defining and Using Methods, Using API Classes, Exceptions, Defining Classes Svetlin Nakov Technical Trainer
Functional Programming Data Aggregation and Nested Queries Ivan Yonkov Technical Trainer Software University
Programming Fundamentals Course Introduction SoftUni Team Technical Trainers Software University
Doctrine The PHP ORM SoftUni Team Technical Trainers Software University
Creating Content Defining Topic, Creating Technical Training Materials SoftUni Team Technical Trainers Software University
First Steps in PHP Creating Very Simple PHP Scripts SoftUni Team Technical Trainers Software University
Inheritance Class Hierarchies SoftUni Team Technical Trainers Software University
Static Members Static Variables & Methods SoftUni Team Technical Trainers Software University
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Generics SoftUni Team Technical Trainers Software University
High-Quality Programming Code Code Correctness, Readability, Maintainability, Testability, Etc. SoftUni Team Technical Trainers Software University
C# Basic Syntax, Visual Studio, Console Input / Output
C# Basic Syntax, Visual Studio, Console Input / Output
Repeating Code Multiple Times
Array and List Algorithms
Processing Variable-Length Sequences of Elements
Numeral Types and Type Conversion
Presentation transcript:

Loops Repeating Code Multiple Times SoftUni Team Technical Trainers Software University

Table of Contents 1.What is a Loop? 2.Loops in C#  while loops  do … while loops  for loops  foreach loops 3.Special loop operators  break, continue, goto 4.Nested loops 2

Loop: Definition  A loop is a control statement that repeats the execution of a block of statements  May execute a code block fixed number of times  May execute a code block while given condition holds  May execute a code block for each member of a collection  Loops that never end are called an infinite loops while (condition) { statements; statements;} 3

Using while(…) Loop Repeating a Statement While Certain Condition Holds

How To Use While Loop?  The simplest and most frequently used loop  The repeat condition  Returns a boolean result of true or false  Also called loop condition while (condition) { statements; statements;} 5

While Loop: How It Works? true statement false condition 6

While Loop – Example int counter = 0; while (counter < 10) { Console.WriteLine("Number : {0}", counter); Console.WriteLine("Number : {0}", counter); counter++; counter++;} 7

while(…) Loop Examples

 Calculate and print the sum of the first N natural numbers Sum 1..N – Example Console.Write("n = "); int n = int.Parse(Console.ReadLine()); int number = 1; int sum = 1; Console.Write("The sum 1"); while (number < n) { number++; number++; sum += number ; sum += number ; Console.Write("+{0}", number); Console.Write("+{0}", number);} Console.WriteLine(" = {0}", sum); 9

Calculating Sum 1..N Live Demo

Prime Number Check – Example Console.Write("Enter a positive integer number: "); uint number = uint.Parse(Console.ReadLine()); uint divider = 2; uint maxDivider = (uint) Math.Sqrt(number); bool prime = true; while (prime && (divider <= maxDivider)) { if (number % divider == 0) if (number % divider == 0) { prime = false; prime = false; } divider++; divider++;} Console.WriteLine("Prime? {0}", prime); 11

Checking Whether a Number Is Prime Live Demo

break Using the break Operator  The break operator exits the inner-most loop static void Main() { int n = Convert.ToInt32(Console.ReadLine()); int n = Convert.ToInt32(Console.ReadLine()); // Calculate n! = 1 * 2 *... * n // Calculate n! = 1 * 2 *... * n int result = 1; int result = 1; while (true) while (true) { if (n == 1) if (n == 1) break; break; result *= n; result *= n; n--; n--; } Console.WriteLine("n! = " + result); Console.WriteLine("n! = " + result);} 13

Calculating Factorial Live Demo

do { … } while (…) Loop

Using Do-While Loop  Another classical loop structure is:  The block of statements is repeated  While the boolean loop condition holds  The loop is executed at least once do{ statements; statements;} while (condition); 16

Do-While Statement: How It Works? true condition statements false

do { … } while (…) Examples

Calculating N Factorial – Example static void Main() { string numberAsString = Console.ReadLine(); string numberAsString = Console.ReadLine(); int n = Convert.ToInt32(numberAsString); int n = Convert.ToInt32(numberAsString); int factorial = 1; int factorial = 1; do do { factorial *= n; factorial *= n; n--; n--; } while (n > 0); while (n > 0); Console.WriteLine("n! = " + factorial); Console.WriteLine("n! = " + factorial);} 19

using System.Numerics; static void Main() { int n = 1000; int n = 1000; BigInteger factorial = 1; BigInteger factorial = 1; do do { factorial *= n; factorial *= n; n--; n--; } while (n > 0); while (n > 0); Console.WriteLine("n! = " + factorial); Console.WriteLine("n! = " + factorial);} Don't forget to add a reference to System.Numerics.dll. Factorial with BigInteger – Example 20

Factorial ( do... while ) Live Demo

22  Calculating the product of all integers in the interval [n..m]: Product of Integers [N..M] – Example int n = int.Parse(Console.ReadLine()); int m = int.Parse(Console.ReadLine()); int number = n; decimal product = 1; do{ product *= number; product *= number; number++; number++;} while (number <= m); Console.WriteLine("product[{0}..{1}] = {2}", n, m, product);

Product of the Integers in the Interval [n..m] Live Demo

for Loops

 The typical for loop syntax is:  Consists of  Initialization statement  Boolean test expression  Update statement  Loop body block For Loops for (initialization; test; update) { statements; } 25

 The initialization expression  Executed once, just before the loop is entered  Like it is out of the loop, just before it  Typically used to declare a counter variable The Initialization Expression for (int number = 0;...;...) { // Can use number here } // Cannot use number here (out of scope) 26

 The test expression is evaluated before each loop iteration  If true, the loop body is executed  If false, the loop finishes (and the loop body is skipped)  Used as a loop condition The Test Expression for (int number = 0; number < 10;...) { // Can use number here } // Cannot use number here (out of scope) 27

 The update expression  Executed at each iteration after the body of the loop is finished  Typically used to update the loop counter  Can update multiple variables The Update Expression for (int number = 0; number < 10; number++) { // Can use number here } // Cannot use number here (out of scope) 28

for Loop Examples

 A simple for -loop to print the numbers 0 … 9 : Simple for Loop – Example for (int number = 0; number < 10; number++) { Console.Write(number + " "); Console.Write(number + " ");}  A simple for -loop to calculate n!: decimal factorial = 1; for (int i = 1; i <= n; i++) { factorial *= i; factorial *= i;} 30

31  A complex for -loop could have several counter variables: Complex for Loop – Example for (int i = 1, sum = 1; i <= 128; i = i * 2, sum += i) { Console.WriteLine("i={0}, sum={1}", i, sum); Console.WriteLine("i={0}, sum={1}", i, sum);} i=1, sum=1 i=2, sum=3 i=4, sum=7 i=8, sum=15...  Result:

For Loops Live Demo

N^M – Example  Calculating n to power m (denoted as n^m ): static void Main() { int n = int.Parse(Console.ReadLine()); int n = int.Parse(Console.ReadLine()); int m = int.Parse(Console.ReadLine()); int m = int.Parse(Console.ReadLine()); decimal result = 1; decimal result = 1; for (int i=0; i<m; i++) for (int i=0; i<m; i++) { result *= n; result *= n; } Console.WriteLine("n^m = " + result); Console.WriteLine("n^m = " + result);} 33

Calculating N^M Live Demo

 continue bypasses the iteration of the inner-most loop  Example: sum all odd numbers in [1…n], not divisors of 7 : continue Using the continue Operator int n = int.Parse(Console.ReadLine()); int sum = 0; for (int i = 1; i <= n; i += 2) { if (i % 7 == 0) if (i % 7 == 0) { continue; continue; } sum += i; sum += i;} Console.WriteLine("sum = {0}", sum); 35

Using the continue Operator Live Demo

foreach Loop Iterating over a Collection

 The typical foreach loop syntax is:  Iterates over all the elements of a collection  The element is the loop variable that takes sequentially all collection values  The collection can be list, array or other group of elements of the same type For-Each Loops foreach (var element in collection) { statements; } 38

 Example of foreach loop:  The loop iterates over the array of day names  The variable day takes all its values  Inside a foreach loop we cannot modify the current item foreach Loop – Example string[] days = { "Monday", "Tuesday", "Wednesday", "Thursday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }; "Friday", "Saturday", "Sunday" }; foreach (var day in days) { Console.WriteLine(day); Console.WriteLine(day);} 39

foreach Loop Live Demo

Nested Loops Using a Loop Inside a Loop

 A composition of loops is called a nested loop  A loop inside another loop What Is Nested Loop? for (initialization; test; update) { for (initialization; test; update) for (initialization; test; update) { statements; statements; } …} 42

Nested Loops Examples

 Print the following triangle of numbers: Triangle – Example int n = int.Parse(Console.ReadLine()); for (int row = 1; row <= n; row++) { for (int column = 1; column <= row; column++) for (int column = 1; column <= row; column++) { Console.Write("{0} ", column); Console.Write("{0} ", column); } Console.WriteLine(); Console.WriteLine();} … … n 44

Triangle of Numbers Live Demo

Primes in the Range [N … M] – Example int n = int.Parse(Console.ReadLine()); int m = int.Parse(Console.ReadLine()); for (int number = n; number <= m; number++) { bool prime = true; bool prime = true; int divider = 2; int divider = 2; int maxDivider = Math.Sqrt(number); int maxDivider = Math.Sqrt(number); while (divider <= maxDivider) while (divider <= maxDivider) { if (number % divider == 0) if (number % divider == 0) { prime = false; prime = false; break; break; } divider++; divider++; } if (prime) if (prime) Console.Write("{0} ", number); Console.Write("{0} ", number);} 46

Primes in the Range [n, m] Live Demo

C# Jump Statements  Jump statements are:  break, continue, goto  How continue woks?  In while and do-while loops jumps to the test expression  In for loops jumps to the update expression  To exit the most-inner loop use break  To exit from an outer loop use goto with a label  Note: avoid using goto ! (it is considered harmful) 48

C# Jump Statements – Example int outerCounter = 0; for (int outer = 0; outer < 10; outer++) { for (int inner = 0; inner < 10; inner++) { if (inner % 3 == 0) { if (inner % 3 == 0) continue; if (outer == 7) continue; if (outer == 7) break; if (inner + outer > 9) break; if (inner + outer > 9) goto breakOut; } goto breakOut; } outerCounter++; outerCounter++; } breakOut: Label 49

Loops: More Examples

Nested Loops – Examples  Print all four digit numbers in format ABCD such that A + B = C + D (known as happy numbers) static void Main() { for (int a = 1; a <= 9; a++) for (int a = 1; a <= 9; a++) for (int b = 0; b <= 9; b++) for (int b = 0; b <= 9; b++) for (int c = 0; c <= 9; c++) for (int c = 0; c <= 9; c++) for (int d = 0; d <= 9; d++) for (int d = 0; d <= 9; d++) if (a + b == c + d) if (a + b == c + d) Console.WriteLine("{0}{1}{2}{3}", a, b, c, d); Console.WriteLine("{0}{1}{2}{3}", a, b, c, d);} Can you improve this algorithm to use only 3 nested loops? 51

Happy Numbers Live Demo

Nested Loops – Examples  Print all combinations from TOTO 6/49 lottery static void Main() { int i1, i2, i3, i4, i5, i6; int i1, i2, i3, i4, i5, i6; for (i1 = 1; i1 <= 44; i1++) for (i1 = 1; i1 <= 44; i1++) for (i2 = i1 + 1; i2 <= 45; i2++) for (i2 = i1 + 1; i2 <= 45; i2++) for (i3 = i2 + 1; i3 <= 46; i3++) for (i3 = i2 + 1; i3 <= 46; i3++) for (i4 = i3 + 1; i4 <= 47; i4++) for (i4 = i3 + 1; i4 <= 47; i4++) for (i5 = i4 + 1; i5 <= 48; i5++) for (i5 = i4 + 1; i5 <= 48; i5++) for (i6 = i5 + 1; i6 <= 49; i6++) for (i6 = i5 + 1; i6 <= 49; i6++) Console.WriteLine("{0} {1} {2} {3} {4} {5}", Console.WriteLine("{0} {1} {2} {3} {4} {5}", i1, i2, i3, i4, i5, i6); i1, i2, i3, i4, i5, i6);} Warning: the execution of this code could take a very long time. 53

TOTO 6/49 Live Demo

55  C# supports four types of loops:  while loops  do-while loops  for loops  foreach loops  Nested loops are used to implement more complex logic  The operators continue, break & goto can change the default loop execution behavior Summary

? ? ? ? ? ? ? ? ? Loops: Repeating Code Multiple Times

License  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" licenseCreative Commons Attribution- NonCommercial-ShareAlike 4.0 International 57  Attribution: this work may contain portions from  "Fundamentals of Computer Programming with C#" book by Svetlin Nakov & Co. under CC-BY-SA licenseFundamentals of Computer Programming with C#CC-BY-SA  "C# Part I" course by Telerik Academy under CC-BY-NC-SA licenseC# Part ICC-BY-NC-SA

Free Software University  Software University Foundation – softuni.orgsoftuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg softuni.bg  Software Facebook  facebook.com/SoftwareUniversity facebook.com/SoftwareUniversity  Software YouTube  youtube.com/SoftwareUniversity youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bgforum.softuni.bg