December 8, 2013

Loops and Functions

In this post, we shall see the very basic components of a programming language: loops and functions. If you are familiar with other programming languages like C, C++ or Java; these are essentially the same in C#. Perhaps C# provides a bit more flexibility and easy-to-manage essence in these concepts.

Loops: Loops are blocks of code that executes over and over again. There are two basic rules/principles of running a loop. You run a loop until(while) a condition is met, and you run a loop for a given or predefined number of times. Based on these two principles, we can design three types of loops:
  1. for loop
  2. while loop
  3. do-while loop
While we go through each of these individually, you should keep in mind that there are no such thing as running a loop in exactly any particular way. You can code and design as you wish, over the years of your experience, you will understand why each of them are different and applicable or preferable under certain conditions.

for loop: A for loop has 4 different sections.
  • Initialization
  • Condition
  • Increment/Decrement
  • Code
Here is a simple model.

for(initialization;condition;increment)
{
    //code
}
You can place decrement in place of increment, whichever you need. If you go through the last post, you will see that we needed a for loop in order to determine if the given number is a prime.

for (int i = 2; i * i < num; i++)
{
      if (num % i == 0)
      {
             prime = false;
             break;
      }
}
At line 1, we assign the variable i of type int a value of 2. This is initialization. Then the code checks if the current value of i is within the boundary of the condition. Suppose num=12. So 2*2 = 4 and 4 is less than 12. The condition is met, the flow enters the code at line 3 and onwards. After line 7, the flow is back to line 1, this time it will go to the 3rd section first, i++. i++ is the shorthand form of i = i+1. So the current value of i is 3. The flow enters 2nd section, 3*3 = 9 is less than 12, which is true. So the flow enters the 4th section, that is at line 3 and onwards. Continuing this way, the repeating process goes on until the condition evaluates to false, the flow leaves the loop. This is a basic flow diagram.
Flow Diagram of for-loop
So what happens when the condition section is missing? If there is no condition to check, the loop will run for ever. This particular case is called an infinite loop. Luckily your compiler can sense if you are coding an infinite loop and will probably give you a warning that certain parts of the code won't be reachable.

for(int i=2;;i++)
{
    if(something_is_true)
    {
        break;
    }
}
This is an infinite loop and you should provide a break statement to get out of the loop on some condition.

while loop: The design of a while loop is different from the for loop. But the basic ingredients are the same. Here is a flow diagram with each sections.
while loop flow diagram
Flow 2 and 3 will continue until the condition is evaluated to false. When the condition is false, then the code flow will continue from the red line. 
You should keep in mind that this is a very basic structure of a while loop. Over the years of programming experience, you will notice slightly different styles of while loops, according to the tastes of the programmer. Here is a form of infinite loop-

while(true)
{
    if(something_is_true)
    {
        break;
    }
}
You know true is a keyword. So the condition inside the brace is always true, so it will run forever, unless you apply a break statement on some condition inside. 

do-while loop: The do-while loop is similar to the while loop. The main difference is the condition check on the do-while loop is done at the tail, not at the top. Here is a basic flow diagram of a do-while loop.
do-while loop flow diagram
As you can see, the condition check is at the bottom. do is a keyword, like while. Notice that after examining the condition, if it evaluates to true, the flow is number 3. Otherwise the loop exits and control flow goes to the lines in the red. 

What is so interesting about the do-while loop? The point of interest, do-while loop will execute at least for once before checking the condition. This is not possible with while loop. If the condition evaluates to false on the first instance, you can't enter the loop in any possible way.

Functions: Functions are individual and independent code sections in the program. They are designed to perform a specific task. Functions provide a way to break up large sections of code into smaller, re-usable pieces that make program easier to understand and maintain. 
As you know that C# is an object oriented programming(OOP) language, whatever piece of code that we write should be inside a class. So there are no global functions in C#. Everything belongs to certain class, or nothing. So in OOP terminology, functions are preferably called methods. We shall commonly use the word method in this post, but the words are interchangeable and no harm is done.

So a method essentially has 4 parts.
  • A name
  • Zero, one or more parameter(s)
  • Body
  • A return type
The name can be any name, except the keywords in C#. You should also avoid naming your method anything that any of the build-in methods in .NET already possess, for example Read() or ToString() etc. As you can see, there is a convention in naming your methods. It's a good practice if you follow the convention, this isn't a hard and fast rule. The method name always starts with an uppercase, and if the name consists of more than one word, each word starts with the uppercase as well, for example ToString(). Note that this convention is different in Java, where the camel-case notation is preferred. 
Here is a typical method in C#.

int MyMethod(int a, string str)
{
    int b;
    //do something
    return b;
}
Your method can take any numbers of parameters. You have to specify what type of parameters you are going to use. In this case, I have assumed that the method's name is MyMethod, it takes two parameters, one integer type and the other string type. It has a body where we do something, and then the method gives back a result or a value. We assume that the return value is an integer, so you see the int in front of MyMethod. The return type must match with the method definition. If the variable b on line 5 is something different other than an integer, you will get an error.
A method is not bound to return anything. You can decide not to return anything at all. You do that in the following way-

void MyMethod(int a, string str)
{
    //do something
}
The void in front of the name says that your method doesn't return anything. So you do not return anything. But if it happens that at some point you do not want to execute the rest of your code, you can just return from that point.

void MyMethod(int a, string str)
{
    //do something
    if(something_happens)
    {
        return;
    }
    //more code
}
I think you get the point.


There are keywords that sometimes you have to put on before the definition of your method. For example, public, static, private etc. These are access modifiers and we shall cover them later. For now, let's edit the primality test code from the previous post and use it in a method.

using System;

namespace Spells
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = Console.ReadLine();
            int num = Int32.Parse(input);
            if (IsPrime(num))
            {
                Console.WriteLine("{0} is a prime", num);
            }
            else
            {
                Console.WriteLine("{0} is not a prime", num);
            }
            
            Console.Read(); //keeps the console alive
        }

        static bool IsPrime(int x)
        {
            bool prime = true;

            for (int i = 2; i * i <= x; i++)
            {
                if (x % i == 0)
                {
                    prime = false;
                    break;
                }
            }
            return prime;
        }
    }
}
This is the final code. Notice line 23, the return type is a bool, so the method definition contains the keyword bool. I have named the method as IsPrime, taking a single integer as parameter. For the time being, avoid the access keyword static.

Note that this piece of code is quite neat and clean than the previous. That's what methods do, you can break down your large code in to pieces that can be called repeatedly. If it happens that some other part needs to check if a number is prime or not, it can also call IsPrime method again, saving us from a redundant copy and paste of the same code over and over again.

That's all. I have skipped a different construct of for loop, the foreach loop. I shall explain it once array is done.

No comments:

Post a Comment