Posts

Showing posts with the label C#

C# Collection and Iteration

C# has powerful structures for dealing with collections and other data structures. In this blog, we'll be using string formatting  and lists . Click on the links if you haven't done them in C# before. var names = new List<string>   { "nobita", "bheem", "oggy", "oggy cockroach", "ninja" }; foreach (var name in names) {     if(name.StartsWith("oggy")) {         Console.WriteLine($"Need to remove {name}!");         names.Remove(name);     } } This code tries to remove names starting with "oggy" from a list. Try it in the interactive editor offered by the above tutorial (click 'Enter focus mode' at the bottom of this site ) Does it work? No! Which is the line that's causing the crash? How would you resolve it? Click here to power back

C# loop optimization

See here for an interactive tutorial on control flows in C#. At the end of the tutorial, you see this piece of code, to sum all numbers between 1 and 20, which are divisible by 3 int sum = 0; for (int number = 1; number < 21; number++) {   if (number % 3 == 0)   {     sum = sum + number;   } }   Check the cyclomatic complexity  of this code. Is there a way you can simplify it by removing the nesting? Type your thoughts below. Going ahead, we'll look at using loops to iterate over a collection

C# arithmetic

See here for a short interactive tutorial about number-arithmetic in C# Of course, arithmetic in C# is similar to any other language.  Here's something to think about: Normally, if we divide & multiply by the same number, we get back the variable. For example: (c / a) * a  Would evaluate to  c  itself. However, there are some situations in which this is not true. It will not evaluate to  c What do you think? Write the situations that come to your mind below. Next, we look at control structures and a small optimization problem