Execute Blocks of Code Multiple Times Telerik Software Academy C# Fundamentals – Part 1.

Slides:



Advertisements
Similar presentations
Solve problems with Java code Algorithms with Java.
Advertisements

AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
2. C# Language Fundamentals
Module 4: Statements and Exceptions. Overview Introduction to Statements Using Selection Statements Using Iteration Statements Using Jump Statements Handling.
Procedural Programming in C# Chapters Objectives You will be able to: Describe the most important data types available in C#. Read numeric values.
Execute Blocks of Code Multiple Times Svetlin Nakov Telerik Corporation
Do-while Loops Programming. COMP102 Prog Fundamentals I: do-while Loops /Slide 2 The do-while Statement l Syntax do action while (condition) l How it.
CSC 221: Computer Programming I Fall 2001  conditional repetition  repetition for: simulations, input verification, input sequences, …  while loops.
C# Language Report By Trevor Adams. Language History Developed by Microsoft Developed by Microsoft Principal Software Architect Principal Software Architect.
Fundamental Programming Structures in Java: Control Flow, Arrays and Vectors.
Introduction to working with Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
Loops More loops Off-by-one errors Infinite loops Nested Loops.
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
Repeating Instructions
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Lecture Review (If-else Statement) if-else statement has the following syntax: if ( condition ) { statement1; } else { statement2; } The condition.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
For Loops Programming. COMP102 Prog Fundamentals I: for Loops/Slide 2 The for Statement condition action true false initialization update.
 Decision making statements Decision making statements if statement if...else statement Nested if...else statement (if...elseif....else Statement) 
Implementing Control Logic in C# Svetlin Nakov Telerik Corporation
Loops, Methods, Classes Loops, Methods, Using API Classes, Exceptions SoftUni Team Technical Trainer Software University
1.6 Loops academy.zariba.com 1. Lecture Content 1.While loops 2.Do-While loops 3.For loops 4.Foreach loops 5.Loop operators – break, continue 6.Nested.
What you need to know Ivaylo Kenov Telerik Corporation Telerik Academy Student.
Loops Repeating Code Multiple Times SoftUni Team Technical Trainers Software University
C# Programming Fundamentals Control Flow Jim Warren, COMPSCI 280 S Enterprise Software Development.
Loops, Methods, Classes Using Loops, Defining and Using Methods, Using API Classes, Exceptions, Defining Classes Bogomil Dimitrov Technical Trainer Software.
Computer Science Department LOOPS. Computer Science Department Loops Loops Cause a section of your program to be repeated a certain number of times. The.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Flow Control in Java. Controlling which instruction to execute next Sequential  Similar to walking, one step after another Branching  Similar to a fork.
Perform Calculations and Control Flow Telerik Software Academy Learning & Development Team.
GAME102 - INTRO WHILE LOOPS G. MacKay. Fundamental Control Structures  STRAIGHT LINE  CONDITIONAL  LOOPS.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
CSCI 171 Presentation 5. The while loop Executes a block as long as the condition is true general form: while (condition) { statement 1; statement 2;
Conditional Loops CSIS 1595: Fundamentals of Programming and Problem Solving 1.
Iteration Hussein Suleman UCT Dept of Computer Science CS115 ~ 2004.
A: A: double “4” A: “34” 4.
1 Class Chapter Objectives Use a while loop to repeat a series of statements Get data from user through an input dialog box Add error checking.
Introduction to Computers and Programming Lecture 7:
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
REPETITION MTS3033 OBJECT ORIENTED PROGRAMMING 1.
Unary Not operator !  !true = false  !false = true.
Why Repetition? Read 8 real numbers and compute their average REAL X1, X2, X3, X4, X5, X6, X7, X8 REAL SUM, AVG READ *, X1, X2, X3, X4, X5, X6, X7, X8.
C Language 1 Program Looping. C Language2 Topics Program looping Program looping Relational operators / expressions Relational operators / expressions.
Loops. More Flow of Control  Sometimes we want to do something many times.  Don’t have to write all the steps out multiple times.  Use a LOOP – control.
Loops, Methods, Classes Using Loops, Defining and Using Methods, Using API Classes, Exceptions, Defining Classes Svetlin Nakov Technical Trainer
Lesson 7 Iteration Structures. Iteration is the third control structure we will explore. Iteration simply means to do something repeatedly. All iteration.
Loops causes program to execute the certain block of code repeatedly until some conditions are satisfied. Suppose you want to execute some code/s 10 times.
UCT Department of Computer Science Computer Science 1015F Iteration
Chapter 6: Loops.
Repeating Code Multiple Times
while Repetition Structure
using System; namespace Demo01 { class Program
Chapter 5: Control Structures II
Programming Fundamentals
Lecture 4B More Repetition Richard Gesick
And now for something completely different . . .
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Outline Altering flow of control Boolean expressions
Chapter (3) - Looping Questions.
Loops in C.
Decisions, decisions, decisions
Repetition Statements (Loops) - 2
Repetition Statements
REPETITION Why Repetition?
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

Execute Blocks of Code Multiple Times Telerik Software Academy C# Fundamentals – Part 1

 What is a Loop?  Loops in C#  while loops  do … while loops  for loops  foreach loops  Special loop operators  break, continue, goto  Nested loops

 A loop is a control statement that allows repeating 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

Repeating a Statement While Given Condition Holds

 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;}

true condition statement false

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

Examples

 Calculate and print the sum of the first N natural numbers 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);

Live Demo

 Checking whether a number is prime or not Console.Write("Enter a positive integer number: "); string consoleArgument=Console.ReadLine(); uint number = uint.Parse(consoleArgument); 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);

Live Demo

 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);}

Live Demo

 Another 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);

true condition statement false

Examples

 Calculating N factorial 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);}

 Calculating N factorial with BigInteger 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 reference to System.Numerics.dll.

Live Demo

 Calculating the product of all numbers in the interval [n..m]: 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[n..m] = " + product);

Live Demo

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

 Executed once, just before the loop is entered  Like it is out of the loop, before it  Usually used to declare a counter variable for (int number = 0;...;...) { // Can use number here } // Cannot use number here

 Evaluated before each iteration of the loop  If true, the loop body is executed  If false, the loop body is skipped  Used as a loop condition for (int number = 0; number < 10;...) { // Can use number here } // Cannot use number here

 Executed at each iteration after the body of the loop is finished  Usually used to update the counter for (int number = 0; number < 10; number++) { // Can use number here } // Cannot use number here

Examples

 A simple for-loop to print the numbers 0 … 9 : 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;}

31  Complex for -loops could have several counter variables: 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:

Live Demo

 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);}

Live Demo

 continue operator ends the iteration of the inner-most loop  Example: sum all odd numbers in [1, n] that are not divisors of 7 : 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);

Live Demo

Iteration over a Collection

 The typical foreach loop syntax is:  Iterates over all 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 foreach (Type element in collection) { statements; }

 Example of foreach loop: string[] days = { "Monday", "Tuesday", "Wednesday", "Thursday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }; "Friday", "Saturday", "Sunday" }; foreach (string day in days) { Console.WriteLine(day); Console.WriteLine(day);}  The above loop iterates of the array of days  The variable day takes all its values  In the foreach loop we cannot set the value of the current item

Live Demo

Using Loops Inside a Loop

 A composition of loops is called a nested loop  A loop inside another loop  Example: for (initialization; test; update) { for (initialization; test; update) for (initialization; test; update) { statements; statements; } …}

Examples

 Print the following triangle: … n 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();}

Live Demo

 Print all prime numbers in the interval [n, m]: 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(num); int maxDivider = Math.Sqrt(num); 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); }}

Live Demo

 Jump statements are:  break, continue, goto  How continue works?  In while and do-while loops jumps to the test expression  In for loops jumps to the update expression  To exit an inner loop use break  To exit outer loops use goto with a label  Avoid using goto ! (it is considered harmful)

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

 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}", Console.WriteLine("{0}{1}{2}{3}", a, b, c, d); a, b, c, d);} Can you improve this algorithm to use 3 loops only?

Live Demo

 Print all combinations from TOTO 6/49 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: execution of this code could take too long time.

Live Demo

 C# supports four types of loops:  while  do-while  for loops  foreach loops  Nested loops can be used to implement more complex logic  The operators continue, break & goto can control the loop execution

форум програмиране, форум уеб дизайн курсове и уроци по програмиране, уеб дизайн – безплатно програмиране за деца – безплатни курсове и уроци безплатен SEO курс - оптимизация за търсачки уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop уроци по програмиране и уеб дизайн за ученици ASP.NET MVC курс – HTML, SQL, C#,.NET, ASP.NET MVC безплатен курс "Разработка на софтуер в cloud среда" BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране, книги – безплатно от Наков безплатен курс "Качествен програмен код" алго академия – състезателно програмиране, състезания ASP.NET курс - уеб програмиране, бази данни, C#,.NET, ASP.NET курсове и уроци по програмиране – Телерик академия курс мобилни приложения с iPhone, Android, WP7, PhoneGap free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране

 Fundamentals of C# Programming Track of Courses  csharpfundamentals.telerik.com csharpfundamentals.telerik.com  Telerik Software Academy  academy.telerik.com academy.telerik.com  Telerik Facebook  facebook.com/TelerikAcademy facebook.com/TelerikAcademy  Telerik Academy Learning System  telerikacademy.com telerikacademy.com