Arrays and Loops

Loops

Loops allow us to do the same task repeatedly a controlled amount of times. 

Use Cases:

- I want to count from 1 to 100 and print out all the even numbers

- While my hand of playing cards totals less than 21, draw a card

- Run the program until the user quits

 

 

For loops


// print out the numbers 0-9
for( each number i between 0 and 9) {
   do something with that number
}

abstract definition 


// print out the numbers 0-9
for( var i = 0; i <= 9; i++) {
    Console.WriteLine(i);
}

For loops example

// Count the numbers 1-100, 
// if the number is /5 then put in the DOM

for(var i = 1; i <= 100; i++) {
    if (i % 5 == 0){
       Console.WriteLine(i  + " is divisble by 5");
    }
}

While loops

While Definition

while (some_truthy_expression){
    // do something
}

While Example

var apples = 10;

while (apples > 0){
   Console.WriteLine("Should we eat an apple?")
   var answer = Console.ReadLine();
   if (answer == "yes")
   {
     apples--;  
   }
}

Fizz buzz!

arrays and loops c#

By Mark Dewey

arrays and loops c#

  • 234